Building PIL for OS X 10.6 – The Right Way
September 12th, 2010

Per my previous post, it may be apparent that I’m working on a just-for-fun Django project that uses the Python Image Library (PIL).  Overall, it’s pretty easy to set up, but the instructions I found on the internet were just wrong enough to make me have to dig around for 20 minutes getting it to work.

Disclaimer: The above instructions *might* work for you, so feel free to try them first.

Anyway the issue I was having: After installing PIL through the above instructions, I tried to upload an ImageField file through the Django Admin interface.  I’d get the following error:

The _imaging C module is not installed

Some quick google-fu led me to this page which explained that Python probably could not find the _imaging module, or else that module wasn’t being loaded correctly.   This was strange because I had just installed PIL, and PIL showed up in my sys.path.  However, running:

>>> import _imaging

Showed the following message:

ImportError: dlopen(/Library/Python/2.6/site-packages/PIL/_imaging.so, 2): no suitable image found.  Did find:
/Library/Python/2.6/site-packages/PIL/_imaging.so: mach-o, but wrong architecture

Ah-ha!  The original instructions indicated that it was required to change the build flags for a 64 bit architecture, but for me that was not necessary and in fact build incompatible binaries for my system.

For those following along, the correct instructions for my system were as follows:

$ curl -O http://effbot.org/downloads/Imaging-1.1.6.tar.gz
$ tar zxf Imaging-1.1.6.tar.gz
$ sudo bash
# cd Imaging-1.1.6
# python setup.py build
# python setup.py install
# exit
Installing Python Image Library (PIL) on Webfaction for Python2.6 / Django
September 9th, 2010

Webfaction is a pretty decent “set it and forget it” webhost, which I’ve been using for a number of years.  One thing I’ve noticed lately is that they’re not totally consistent with which software versions among servers, or at least based on some of the forum threads of theirs I’ve read.  Long story short, python2.5 and lower come with PIL, but for whatever reason, python2.6 doesn’t have it.  To get it going, do the following:

cd /home/<your_username>/lib
mkdir python2.6
easy_install-2.6 http://dist.plone.org/thirdparty/PILwoTk-1.1.6.4.tar.gz

That’s pretty-much it.  For some reason the python2.6 dir doesn’t exist, but you can add it back and easy_install whatever libs you need.

Migrating from Python 2 to Python 3: A Cheat Sheat
December 2nd, 2009

Download it here: http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf

Source: http://www.rhinocerus.net/forum/lang-python/604453-moving-python-2-python-3-4-page-cheat-sheet.html

Automatically Respond to Twitter Messages in Python
August 6th, 2009

Matt Warren has come up with a very elegant script to automatically tweet back to anyone who mentions certain keywords.  Check it out here.

Oh Java Calendar, You So Crazy
June 14th, 2009

I was going through the Docs for Groovy when I came across this little gem of Java (well, Groovy):

Calendar.getInstance().get(Calendar.AM_PM)

Can you guess what it does?  It returns a 0 (Calendar.AM) if the current time is in the morning, and 1 (Calendar.PM) if it is in the evening.  It also points out some reasons Java blows my mind.

First: We’re using a Calendar to find out if it is in the morning or night.  I don’t know about you, but the calendar on my wall cannot tell me if it is AM or PM.  It can’t even tell me the time.  However in the Java world (in which also exists both Date and Time classes), a Calendar knows all, and can tell us what time it is.

Second: Calendar is a factory method, because Calendar objects have a pointer to some “time” that you give it (it defaults to the current system time).  So we can’t just query a Calendar for some bit of information, because a Calendar isn’t really what you are probably thinking it is (a static reference to all things Date related), but instead a specific time.  As such, in order to get the current time, we need to get a new instance of a Calendar that has not been initialized to any specific date.

Third: Now that we have an instance of the current Time Calendar, we’re going to call the method we use to find out if it’s AM or PM.  This is helpfully named “get”, which is then passed the only marginally more usefully named constant from the Calendar class, “AM_PM”.

Now I’m not saying this is the worst implementation of this concept, in fact I can think of a few cases where structuring it as such might be very useful.  However, from a code-readability point of view, contrast the code at the top with similar one liner from other languages.

Ruby:

Time.now.strftime("%p")

Python:

time.strftime("%p")

Both use modules/classes named “Time”.  Ruby explicitly indicates that you’re working with the current time, whereas python does not.  I’ve used strftime for both to return the string “AM” or “PM”.  Probably not the most elegent way to do it (I’d extend either’s time class to contain a new method to return whether it is AM or PM if I were to put this in production code) but certainly easier to understand.

I’m sure there are some Javanistas out there who can point out why the way Java does it is preferable or why the ruby/python way is not right, if so, comment.

Fast GCD in python
April 21st, 2009

Fast GCD (greatest common denominator) in python. Significantly faster than using recursion.

def gcd(x,y):
    while x:
        x, y = y % x, x
    return y
Project Euler #9
April 20th, 2009

For those who don’t know, Project Euler is “a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve.”, or in other words, “challenging, bite-sized programming tasks”.

If you’ve got the programming itch but don’t want to work on anything that will take very long, these are great.
Here’s my solution to #9, in python.

#!/usr/bin/python
 
# A Pythagorean triplet is a set of three natural numbers, a &lt; b &lt; c, for which,
# a^(2) + b^(2) = c^(2)
#
# For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2).
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
 
from math import sqrt
from sys import exit
from time import time
 
SUM = 1000
start = time()
 
for b in range(1,SUM + 1):
    for a in range(1, b + 1):
        c = sqrt(a**2 + b**2)
        if a + b + c == SUM:
            print "(%i, %i, %i)" % (a,b,c)
            print "Product = %i" % (a*b*c)
            end = time()
            print "Completed in %f seconds" % (end-start)
            exit()

And the output:

$ python problem9.py
(200, 375, 425)
Product = 31875000
Completed in 0.090962 seconds

Python Port Scanner in 3 Lines
April 17th, 2009

Just wanted to see how few lines I could do it in.  If you don’t include the ‘includes’ or the ‘except:pass’, it’s really only two lines.

#!/usr/bin/python
 
import sys
from socket import *
 
for port in range(int(sys.argv[2].split('-')[0]), int(sys.argv[2].split('-')[1])+1):
    try:socket(AF_INET, SOCK_STREAM).connect((sys.argv[1], port)); print "Able to connect to port:", port
    except: pass

Usage: <filename> <host> <ports>
So for example if you saved this as pyscanner.py, and chmod +x it, you could do:

./pyscanner.py localhost 1-1024

to scan the priviledged ports on your local box.

If it isn’t obvious from the code, it does not support IPv6 addresses and determines of a port is connectable via a standard TCP connect().