Never been to TextSnippets 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 (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
20 total  XML / RSS feed 

Python script to stitch together image tiles

// python script for image tile stiching

#! /usr/bin/env python

# A tile stitching program.
from glob import glob
from cgi import parse_qs
import os.path
from pprint import pprint

# load all the files in this directory to be processed
filenames = glob('*.png')
except ValueError:

canvas = {}

for name in filenames:
    qs = os.path.splitext(name)[0]
    params = parse_qs(name)
    x = params['x'][0]
    y = params['y'][0]
    if canvas.has_key(x):
        canvas[x][y] = name
        canvas[x] = { y : name }


# calculate the dimensions of the output
tile_size = 256
temp = canvas.popitem()
canvas[temp[0]] = temp[1]
x1 = len(canvas)
y1 = len(temp[1])

xdim = x1 * tile_size
ydim = y1 * tile_size

# create the full size blank image
from PIL import Image
mode = 'RGB'
im =, (xdim,ydim))

# walk the array
position = (0,0)
for row in sorted(canvas):
    for column in sorted(canvas[row]):
        current_tile = canvas[row][column]
        temp =
        im.paste(temp, position)
        position = (position[0], position[1] + 256)
    position = (position[0] + 256, 0)'output.png')

Python - Processing Large Text Files One Line At A Time

// process some very large text files one line at a time

fh = open('foo.txt', 'r')
line = fh.readline()
while line:
    # do something here
    line = fh.readline()

// Update

for line in open('foo.txt', 'r'):
    # do something here

PHAWN Interpreter

// description of your code here

import sys
import time

debug = 0
source = []
stack = []
px = 0
py = 0
pd = 1
mode = 0
register = 0

def Initialize():
    global source
    global px
    global py
    path = raw_input("PHAWN source file: ")
    try: file = open(path, "r")
    except IOError:
        print "Failed to open file!"
        return 0
    else: print "File opened successfully!"
    for line in file:
        try: px = line.index("$")
        except: continue
        else: py = source.index(line.strip("\n"))
    return 1

def Run():
    global debug
    global source
    global stack
    global px
    global py
    global pd
    global mode
    global register
    try: instruction = source[py][px]
        print "--- Pointer moved into an unknowned region."
        return 0
    if debug == 1: print "Instr:", instruction, " Pos:(", px, ",", py, ")", " Dir:", pd
    oy = py
    if instruction == "#":
        return 0
    elif instruction == ">":
        if pd > 0:
        elif len(stack) > 0:
            register = stack.pop()
    elif instruction == "<":
        if pd < 0:
        elif len(stack) > 0:
                register = stack.pop()
    elif instruction == "}":
        if pd > 0:
    elif instruction == "{":
        if pd < 0:
    elif instruction == "/":
        if pd > 0:
            px += 1
            while (source[py][px].isdigit() and source[py][px+1].isdigit()):
                px += 1
    elif instruction == "\\":
        if pd < 0:
            px -= 1
            while (source[py][px].isdigit() and source[py][px-1].isdigit()):
                px -= 1
    elif instruction == "^":
        py -= 1
    elif instruction == "_":
        py += 1
    elif instruction == "~":
        if len(stack) > 1:
            if stack[len(stack) - 1] > stack[len(stack) - 2]:
                py -= 1
                py += 1
    elif instruction == "+":
        if len(stack) > 1:
            val1 = stack.pop()
            val2 = stack.pop()
            stack.append(val1 + val2)
    elif instruction == "-":
        if len(stack) > 1:
            val1 = stack.pop()
            val2 = stack.pop()
            stack.append(val2 - val1)
    elif instruction == "&":
        mode = 1 - mode
    elif instruction == "%":
        if len(stack) > 1:
            val1 = stack.pop()
            val2 = stack.pop()
    elif instruction.isdigit() == True:
    if pd > 0 and px + pd > len(source[py]) - 1:
        pd = -1
    if pd < 0 and px + pd < 0:
        pd = 1
    if oy == py:
        px += pd
    return 1
def Input():
    global stack
    data = raw_input("Input: ")
    if data.isdigit() == False:
def Output():
    global mode
    if len(stack) > 0:
        data = stack.pop()
        if mode == 0:
            print data
            print chr(data)
def ReadInteger():
    global source
    global stack
    global px
    global py
    global pd
    global register
    data = source[py][px]
    if pd > 0:
        while (source[py][px + 1].isdigit() == True):
                px += 1
                data += source[py][px]
            except: break
        while (source[py][px - 1].isdigit() == True):
                px -= 1
                data = source[py][px] + data
            except: break
    register = int(data)
    if px > len(source[py]) - 1:
        px = len(source[py]) - 1
    if px < 0:
        px = 0
debug = raw_input("Debug Mode? (1 = Yes / 0 = No) ")
if debug.isdigit() == True: debug = int(debug)

if Initialize() == 1:
    start = time.clock()
    while(Run() == 1):
        if debug == 1:
            print "Stack: ", stack
            raw_input("Pressed  To Continue.")
        else: continue
    print "Executed in ", time.clock() - start, " seconds."
else: print "--- Exited without execution."    
raw_input("Press  to exit.") 

Simple asx decoder

asx decoder: associate it to MIME: video/x-ms-asf in your browser.

#! /usr/bin/env python

from xml.dom.minidom import parse;
from sys import argv
from os import system

if __name__ == '__main__':
    if len(argv)>1:
# print >> file('/tmp/asp.log', 'w'), argv 
        d = parse(file(argv[1]));
        links = [ ref.getAttribute('HREF')
                  for ref in d.getElementsByTagName('REF')
                  if ref.hasAttribute('HREF') ]
        for link in links:
            system('mplayer ' + link)

Vigenere Subsitution

Just for fun, the Vigenere Cipher, in just a few lines of Python. For more info, see:ère_cipher
import string

def vigenere(c,k,e=1):
# e=1 to encrypt, e=-1 to decrypt
    wk=[string.ascii_uppercase.find(ch) for ch in k.upper()]
    wc=[string.ascii_uppercase.find(ch) for ch in c.upper()]

    wc = [ (x[0]+(e*x[1]))%26 for x in zip(wc,wk*(len(wc)/len(wk)+1))]

    print string.join([string.ascii_uppercase[x] for x in wc],"")

>>> vigenere('thiscryptosystemisnotsecure', 'cipher')
>>> vigenere('VPXZGIAXIVWPUBTTMJPWIZITWZT', 'cipher', -1)


This class implements a sorta circular stack. If you get the top item, it will pop off but be added to the bottom.

class CircularStack(list):

    def gettop(self):
        item = self.pop()
        return item

LightTPD subdomain rewrite, Backpack/Basecamp style.

Rewrites to

This example show the values being passed to FCGI for use by Django.

$HTTP["host"] =~ "([^.]+)\.example\.com" {
  server.document-root = "/users/home/username/domains/"
  server.errorlog = "/users/home/username/var/log/lighttpd.example_com.error.log" 
  accesslog.filename = "/users/home/username/var/log/lighttpd.example_com.access.log" 

  fastcgi.server = (
    "/main.fcgi" => (
      "main" => (
        "socket" => "/users/home/username/tmp/django/example_com.socket"

  url.rewrite-once = ( "^(/.*)$" => "/main.fcgi/%1/$1" )
  server.error-handler-404 = "/main.fcgi" 

Python Towers of Hanoi

Use the following as a template, replace the print line with any work for moving the discs using your data structure. The code below just prints the necessary moves.

def hanoi(n, a='A', b='B', c='C'):
    move n discs from a to c using b as middle
    if n == 0:
    hanoi(n-1, a, c, b)
    print a, '->', c
    hanoi(n-1, b, a, c)


Win32 Shortcuts (.lnk files) with com in python

Class and general usage for accessing windows shortcuts in Python.

import pythoncom

class Win32Shortcut:
    def __init__(self, lnkname):
        self.shortcut = pythoncom.CoCreateInstance(
            shell.CLSID_ShellLink, None,
            pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)

    def __getattr__(self, name):
        return getattr(self.shortcut, name)

s = Win32Shortcut(path)
iconPath = s.GetIconLocation()[0]
itemPath = s.GetPath(0)[0]

Psyco Decorator

This will cause decorated functions to be run using the psyco optimizer. It will allow the code to continue working even if psyco is not available

    import psyco

def optimize(func):
        return psyco.proxy(func)
        return func

def complex_function(n):
    ... do complex stuff with n ...

Implement automatic comment moderation queue in Django

Assuming you're using latest trunk (i.e., post-magic-removal merge), you need a few things:

1. A method on your content object which returns whether a comment should go to moderation or not.
2. A method on the FreeComment model which checks this and sets the 'approved' field appropriately.
3. A list filter for the FreeComment admin to show comments in need of moderation.

For the first bit, we borrow from my method for automatically closing comments (

def auto_moderate(self):
    return - datetime.timedelta(30) >= self.pub_date

This returns False if the object is less than 30 days old, True if it's 30 days old or older.

For the second bit, you'll need to hack on the FreeComment model; it's located in django/contrib/comments/ Add this:

def save(self):
    if self.get_content_object().auto_moderate:
        self.approved = False
    super(FreeComment, self).save()

And for the third bit, just add 'approved' to the list of properties the admin can filter on, and you'll be able to click and get a list of all comments which have not yet been approved.

In your templates, you can then manually check whether each comment is approved or not with {% if comment.approved %} or, if you're feeling adventurous, you can add a custom manager to the FreeComment model which only returns comments which have been approved.

Test whether an SGML attribute value requires quoting

SGML attribute values don't always need to be quoted; here's a quick bit of Python which returns whether an attribute value needs to be quoted or not:

import re
if re.compile('^[a-zA-Z0-9_\-\.:]+$').search(value):
   ...does not need quoting..
   ...does need quoting...

Download a file from the internet

Download a file from the internet

def downloadUrl(url):
    import urllib
    data = urllib.urlopen(url)
    return data.readlines()

url = ''
print downloadUrl(url)

See Clearsilver runtime template data (in Trac)


Append the above to a Clearsilver generated page URL for a structured view of the template data.

For pkit

entries.get_list(pub_date__year=2005, pub_date__month=11)

lighttpd.conf update for use with Django

If you grabbed my sample lighttpd.conf before I made this post in the forum, then open up your lighttpd.conf, scroll down to the url.rewrite section, and change this:

"^(/[^media]/.*)$" => "/main.fcgi$1"

To this:

"^(/[^media].*)$" => "/main.fcgi$1"

Close comments after a set time in Django apps

If you're using Django's bundled comments application, you might want to have comments for objects closed after a set period of time; to do this, just add a method to the model of the object which will be getting the comments (e.g., the 'Entry' class if you have a weblog), like so (this assumes a DateTimeField called 'pub_date' which represents the object's date of publication):

def allow_comments(self):
    return - datetime.timedelta(30) >= self.pub_date

Change the timedelta value to however many days you'd like to leave comments open after publication, and now you'll be able to selectively display the comment form only when comments are open, by adding this to your template (assuming the object is being referenced by the name 'entry'):

{% if entry.allow_comments %}
... display the comment form here ...
{% endif %}

Python dictionary to PHP array

Pass any python dictionary into convertArray.
It will return an array that PHP can read.

>>> convertArray({"One":1, "Two":[2,"Two"], "Three":[{"ThreeAgain":[3,3,3]} ,[1,2,3], "Three"]})

Returns: array('Three'=>array(array('ThreeAgain'=>array(3, 3, 3)), array(1, 2, 3), 'Three'), 'Two'=>array(2, 'Two'), 'One'=>1)

## Converts a python dictionary to a php array.
def convertArray(arr):
        ret = ""
        list = []
        if isinstance(arr, type([]) ):                ## If the instance is an array
                for ele in arr:
                        if isinstance(ele, ( type([]), type({})) ):  ## If the instance is an array
                                list.append( convertArray(ele))                                 ## recursive it
                        elif isinstance(ele, (type(1), type(1.0))): 
                                list.append(str(ele))           ## if an int or float, no quotes
                                list.append("'%s'" % str(ele))
        elif isinstance(arr, type({}) ):                ## If the instance is an array
                for (k,v) in arr.items():
                        item = "'" + str(k) + "'=>"
                        if isinstance(v, ( type([]), type({})) ):
                                item += ( convertArray(v))
                                if isinstance(v, (type(1), type(1.0))):   
                                        item += (str(v))           ## if an int or float, no quotes
                                        item += ("'%s'" % str(v))
                raise NameError, "Error - neither a array or a dictionary was passed to this function"
        if len(list) > 0:
                ret = "array(" + ", ".join(list) + ")"
                ret = "array()"
        return ret

Quickly put a bunch of emails into one file

A little bit of Python I used to run through a couple hundred emails in an Evolution folder and put their contents (minus headers) into one file for analysis.

import os, re
output_file = open('/path/to/output/file', 'a')
email_pat = re.compile('^\d+\.$')
[output_file.write(open(email).read().split('From: ')[1]) for email in os.listdir(os.getcwd()) if email_pat.match(email)]

rip calendar attachments from an email

See here for context.

#!/usr/bin/env /usr/local/bin/python

import sys, email

msg = email.message_from_string(

for part in msg.walk():
  if part.get_content_type() == 'text/calendar':
    f = open(part.get_filename(), 'w')
« Newer Snippets
Older Snippets »
20 total  XML / RSS feed