Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 372 total  RSS 

Generating Taconite command documents

// description of your code here
Hello,

This is a port of a php class used to generate XML taconite command documents, useful for (very) easy and powerful ajaxy stuff, if you don't know what that is just check it there in french : http://www.desfrenes.com/playground/taconite/ or there in english : http://www.malsup.com/jquery/taconite/.

Basically what it does is generate an XML document that is later processed by a javascript plugin which executes a serie of DOM modifications.

About the code, I'm a Django beginner as well as a Python beginner so kind advices are welcome.

Cheers.
# usage:
#
# t = Taconite()
#
# t.append("#toto","<label>test</label>")
# t.remove("#tutu")
# t.js('alert("hello world");')
# t.toggleClass('blue','body')
# t.css("body","background-color","white")
# [...]
# print t.toprettyxml()

import xml.dom.minidom as dom

class Taconite(dom.Document):
    def __init__(self):
        dom.Document.__init__(self)
        taconite = self.createElement("taconite")
        self.appendChild(taconite)

    def __str__(self):
        return self.toxml(encoding="utf-8")
    
    def camelizeCssProperty(self,property):
        words = property.split('-')
        camelized = words[0].lower()
        for word in words[1:] :
            camelized = camelized + word[0].upper() + word[1:]
        return camelized
    
    def js(self,script):
        command = self.createElement("eval")
        js = self.createTextNode(script)
        command.appendChild(js)
        self.childNodes[0].appendChild(command)
    
    def changeContentCommand(self,method,selector,content):
        html_dom = dom.parseString(content)
        command = self.createElement(method)
        command.setAttribute("select",selector)
        command.appendChild(html_dom.childNodes[0])
        self.childNodes[0].appendChild(command)
    
    def changeStateCommand(self,action,selector):
        command = self.createElement(action)
        command.setAttribute("select",selector)
        self.childNodes[0].appendChild(command)
    
    def CssCommand(self,action,css_class,selector):
        command1 = self.createElement(action)
        command1.setAttribute("select",selector)
        command1.setAttribute("arg1",css_class)
        command2 = self.createElement(action)
        command2.setAttribute("select",selector)
        command2.setAttribute("value",css_class)
        self.childNodes[0].appendChild(command1)
        self.childNodes[0].appendChild(command2)
    
    def addClass(self,css_class,selector):
        self.CssCommand("addClass",css_class,selector)

    def removeClass(self,css_class,selector):
        self.CssCommand("remove",css_class,selector)

    def toggleClass(self,css_class,selector):
        self.CssCommand("toggleClass",css_class,selector)
    
    def append(self,selector,content):
        self.changeContentCommand("append",selector,content)
    
    def prepend(self,selector,content):
        self.changeContentCommand("prepend",selector,content)
        
    
    def before(self,selector,content):
        self.changeContentCommand("before",selector,content)
        
    
    def after(self,selector,content):
        self.changeContentCommand("after",selector,content)
    
    def wrap(self,selector,content):
        self.changeContentCommand("wrap",selector,content)
    
    def replace(self,selector,content):
        self.changeContentCommand("replace",selector,content)
    
    def replaceContent(self,selector,content):
        self.changeContentCommand("replaceContent",selector,content)
    
    def remove(self,selector):
        self.changeStateCommand("remove",selector)
    
    def show(self,selector):
        self.changeStateCommand("show",selector)
    
    def hide(self,selector):
        self.changeStateCommand("hide",selector)
    
    def removeContent(self,selector):
        self.changeStateCommand("empty",selector)
    
    def css(self,selector,property,value):
        command = self.createElement("css")
        command.setAttribute("select",selector)
        command.setAttribute("name",self.camelizeCssProperty(property))
        command.setAttribute("value",value)
        self.childNodes[0].appendChild(command)

Using Google Talk as a distributed Twitter client

A distributed Twitter client in the spirit of:
http://blog.labnotes.org/2008/05/05/distributed-twitter-client-in-20-lines-of-code/
#!/usr/bin/env python
import xmpp
import sys

class DistTwit(object):
    def __init__(self,user,pwd,callbacks=None,showself=False):
        self._my_jid = xmpp.protocol.JID(user+"/distwit.py")
        self._client = xmpp.Client(self._my_jid.getDomain(), debug=[])
        if not callbacks:
            self._callbacks=[]
        else:
            self._callbacks=callbacks
        self.showself=showself

        self._connect()
        self._auth(pwd)
        self._run()

    def _connect(self):
        print "Connecting..."
        if self._client.connect(server=('talk.google.com',5223)) == "":
            raise ConnectionException()

    def _auth(self,pwd):
        print "Authenticating..."
        if self._client.auth(self._my_jid.getNode(),pwd) == None:
            raise AuthException()

    def add_callback(self,func):
        self._callbacks.append(func)

    def _run(self):
        self._client.sendInitPresence()
        self._roster = self._client.getRoster()

        self._client.RegisterHandler('presence', self._presence)
        quit=False
        while not quit:
            try:
                self._client.Process(1)
            except KeyboardInterrupt:
                quit=True

    def _presence(self,conn,msg):
        jid=xmpp.protocol.JID(msg.getFrom())
        name=self._roster.getName(jid.getNode()+"@"+jid.getDomain())

        if not name:
            name=jid.getNode()+"@"+jid.getDomain()

        if not self.showself and name == self._my_jid.getNode()+"@"+self._my_jid.getDomain():
            return

        status = msg.getStatus()
        show = msg.getShow()

        if not msg.getPriority():
            status="Signed out"
        elif not status and show:
            status="("+msg.getShow()+")"
        elif show and status:
            status="("+msg.getShow()+") "+status

        for f in self._callbacks:
            f(name,status)
        
class ConnectionException(Exception):
    def __init__(self):
        pass
    def __str__(self):
        return "Error connecting to talk.google.com"

class AuthException(Exception):
    def __init__(self):
        pass
    def __str__(self):
        print "Error authenticating to talk.google.com"


if __name__=="__main__":
    def callback(name,status):
        print "%s: %s" % (name,status)
    
    DistTwit(sys.argv[1],sys.argv[2],callbacks=[callback])

Print color highlighted strings to unix terminal

Sample of escape sequences needed to print in color to unix/linux terminal.

print x.replace('toostis', '\033[0;31mtoostis\033[m')


This will highlight all 'toostis' instances in x with red.

Filesize with nice units

Simple function to format filesizes in bytes to human-readable units.

def prettySize(size):
	suffixes = [("B",2**10), ("K",2**20), ("M",2**30), ("G",2**40), ("T",2**50)]
	for suf, lim in suffixes:
		if size > lim:
			continue
		else:
			return round(size/float(lim/2**10),2).__str__()+suf

print prettySize(213458923)
# Output: 203.57M

print prettySize(1234)
# Output: 1.21K

Calculate Pi

This script presents a way to compute Pi using a statistic method.
See http://en.wikipedia.org/wiki/Computing_π for further algorithms.

import random, math

class calcPi:
    def __init__(self):
        self.times = pow(10,6)
        self.i = 0
        self.isnot = 0

    def IsOnCircle(self,x,y):
        if math.sqrt(x**2+y**2) < 1:
            return True
        else:
            return False
    
    def run(self):
        for x in range(self.times):
            x,y = random.random(),random.random()
            if self.IsOnCircle(x,y):
                self.i+=1
            else:
                self.isnot+=1
    
    def getResults(self):
        return (float(self.i), float(self.isnot))

    def getPi(self):
        self.run()
        r = self.getResults()
        return r[0]/(r[0]+r[1])*4

if __name__ == '__main__':
    print calcPi().getPi()

Progress bar

This is a simple class to generate char-based progress bars.

Example:
[++++++      ]


class Bar:
	def __init__(self):
		self.len = 80
		self.chars = (' ', '+')
		self.wrap = ('[', ']')
		self.filledc = 0

	def fill(self, i):
		assert not (i > 100) or (i < 0)
		self._setP(i)

	def _setP(self, p):
		self.filledc = int(round(float(self.len*p)/100))

	def show(self):
		out = []
		out.append(self.wrap[0])
		out.append(self.filledc*self.chars[1])
		out.append((self.len-self.filledc)*self.chars[0])
		out.append(self.wrap[1])
		return "".join(out)

b = Bar()
b.len = 20
b.fill(20)
print b.show()

Convert cp1252-> utf-8 character set (python and ruby)

Oooh, I hate character sets. Specifically that there are more than one of them. Here is a Ruby version of a Python script I found to convert cp1252 (aka windows-1252) into utf-8.

  def clean_up dirty_text
    newstr = ""
    dirty_text.length.times do |i|
      character = dirty_text[i]
      newstr += if character < 0x80
        character.chr
      elsif character < 0xC0
        "\xC2" + character.chr
      else
        "\xC3" + (character - 64).chr
      end
    end
    newstr
  end


The original Python script was (http://miscoranda.com/96):

#!/usr/bin/python
import sys
for c in sys.stdin.read(): 
   if ord(c) < 0x80: sys.stdout.write(c)
   elif ord(c) < 0xC0: sys.stdout.write('\xC2' + c)
   else: sys.stdout.write('\xC3' + chr(ord(c) - 64))

Code 2 HTML

This is a simple python program that reads a file (code), and replaces line breaks and spaces with appropriate tag and entity.

import sys

line_break='<br>'
nb_space='&#160;'

def toHtml(f,out):
    try:
        fo=open(out,'w')
    except IOError:
        print 'output file error!'
    else:
        for line in f:
            line=line.replace('\t',nb_space*8)
            line=line.replace(' ',nb_space)
            line=line.replace('\n',line_break)
            fo.write(line)
        fo.close()
        

if len(sys.argv) == 1:
    print("at least one argument / input filename / required")
    sys.exit()
if len(sys.argv) > 3:
    print"too many arguments"
    sys.exit()       
try:
    f=open(sys.argv[1],'r')
except IOError:
    print 'cannot open file ', sys.argv[1]
else:
    if len(sys.argv) == 2:
        out=f.name + '.html'
    else:
        out=sys.argv[2]
    toHtml(f, out)
    f.close()

decompressing various archive types

// decompressing various archive types with this python script
// usage unpack <archive filename>

#!/usr/bin/env python
#
# simple python script for extracting mostly used types of archives
# this script extracts .tar, .tar.gz, .tar.bz2, .gz and .zip archives 
#

import sys	# required for fetching command line arguments 
import os	# required for calling commands for archive extracting

def unpack(s):									# this is definition of depack
	if (s.find('.tar.gz') != -1):				#	function. It takes string
		os.system("tar -xvvzf " + filename)		#   filename as argument.
	elif (s.find('.tar.bz2') != -1):			#	functon than calls 
		os.system("tar -xvvjf " + filename)		#   appropriate command according
	elif (s.find('.tar') != -1):				# 	to file extension
		os.system("tar -xvvf " + filename)
	elif (s.find('.gz') != -1):
		os.system("gunzip" + filename)			
	elif (s.find('.zip') != -1):		
		os.system("unzip " + filename)
	else: print "Wrong archive or filename"		# other types not supported

try:											# this is main program
	filename = sys.argv[1]						# first argument right after
	unpack(filename)							#	'unpack' command goes in the
except IndexError:								#	filename string
	print "Filename is invalid!"				#	than the depack function is called

# try-except block is used for handling IndexError exception if no argument is passed

Quick English to Portuguese 1-word Translator

// description of your code here
This is a very simple python code that access babylon translator. For now It just translates 1-word from english to portuguese. It's probably a bit buggy also, because I'm a python noob.

import urllib2, sys, re

def translate(word, lang):
	print "WORD: "+word
	print "TRANSLATION TO LANGUAGE: "+lang
	print "-----------------------------------"
	sock = urllib2.urlopen("http://online.babylon.com/cgi-bin/trans.cgi?layout=txt&lang=ptg&word="+word)
	htmlsource = sock.read()
	sock.close()

	#Replacing some specific html tags for \n in order to format the final output:
	htmlsource = htmlsource.replace("<hr>","\n");
	htmlsource = htmlsource.replace("<BR>","\n");
	htmlsource = htmlsource.replace("<br>","\n");
	htmlsource = htmlsource.replace("</BR>","");
	htmlsource = htmlsource.replace("</br>","");
	htmlsource = htmlsource.split(word)[1]

	#Removing unwanted html tags (acctually all the tags):
	iter = re.finditer(r'<.*?>',htmlsource)
	for m in iter:
		htmlsource = htmlsource.replace(m.string[m.start():m.end()],"")

	#More output formating
	tags = htmlsource.split("\n");
	output = ""
	for str in tags:
		output += str.strip()+"\n"

	#tweak this up for your language
	output = output.decode("iso-8859-1").encode("utf-8")	
	print output

try:
	word = sys.argv[1]
	lang = sys.argv[2]
	translate(word,"")

except(IndexError):
	if(word.__len__() != 0):
		translate(word, "")
« Newer Snippets
Older Snippets »
Showing 1-10 of 372 total  RSS