« Earlier 7 items total Later »

On this page: 

Enable arrow keys in python interpreter in OS X

Something that has always bothered me is that in OS X's default python install, typing an arrow enters the escape sequence # ex: [^[[A, ^[[D]; instead of moving the cursor or going to the previous commands. To solve this issue, one needs to install the readline module.

From Bob Ippolito:
In the terminal, enter:
python `python -c “import pimp; print pimp.__file__”` -i readline

----
This works with the standard installation of python 2.3 included with OS X. I have not yet gotten readline to work with python 2.4.2.

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.datetime.today() - 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.

Example:
>>> 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
                        else:
                                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))
                        else:
                                if isinstance(v, (type(1), type(1.0))): 
                                        item += (str(v))                ## if an int or float, no quotes
                                else:
                                        item += ("'%s'" % str(v))
                        list.append(item)
        else:
                raise NameError, "Error - neither a array or a dictionary was passed to this function"
        
        
        if len(list) > 0:
                ret = "array(" + ", ".join(list) + ")"
        else:
                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(sys.stdin.read())

for part in msg.walk():
  if part.get_content_type() == 'text/calendar':
    f = open(part.get_filename(), 'w')
    f.write(part.get_payload())
    f.close()

« Earlier 7 items total Later »