python

Python data structures, dictionary?

Hi I hope somebody can help. I am using Python and I would like to be able to do the following. I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or integers For example the s...

adding lighting effects to an image in python

hi, I want to specify a light source at a particular location in an image using Python. PIL's ImageEnhance module does provide a way to briten an image. but I want to have a control over light source placement to acheieve special effects. Does anyone know how to do this? thank you! ...

How to prevent a module from being imported twice?

Hello, When writing python modules, is there a way to prevent it being imported twice by the client codes? Just like the c/c++ header files do: #ifndef XXX #define XXX ... #endif Thanks very much! ...

python - good places to check out example prog / code online?

there is a year old, similar question - but in case there have been changes afoot: i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- code that i can learn from, ide...

Comparing Python nested lists

I have two nested lists, each nested list containing two strings e.g.: list 1 [('EFG', '[3,4,5]'), ('DEF', '[2,3,4]')] and list 2 [('DEF', '[2,3,4]'), ('FGH', '[4,5,6]')] I would like to compare the two lists and recover those nested lists which are identical with each other. In this case only ('DEF','[2,3,4]') would be returned. Th...

Keeping track of changes since the last save in django models

A couple of times I've run into a situation, when at save time I need to know which model fields are going to be updated and act accordingly. The most obvious solution to this is to take the primary key field and retrieve a copy of the model from the database: class MyModel(models.Model): def save(self, force_insert=False, force_u...

Install Plone egg as a Python module on Windows

I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (http://plone.org/products/grufspaces). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buildout; using buildout would allow me to easily add Grufspaces (collective.groupspace.role...

Writing a LaTeX document with Python code snippets

I am using LaTeX to write a document about Python. This document will contain code snippets (examples). I could use the verbatim environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight would be a plus. Thanks. Edit: I must poin...

Random strings in Python

How do you create a random string in Python? I needed it to be number then character repeat till you're done this is what I created def random_id(length): number = '0123456789' alpha = 'abcdefghijklmnopqrstuvwxyz' id = '' for i in range(0,length,2): id += random.choice(number) id += random.choice(alpha) ...

How to get current_app for using with reverse in multi-deployable reusable Django application?

I'm writing reusable app. And I want to deploy it several times. Here is urls.py: urlpatterns = patterns('', (r'^carphotos/', include('webui.photos.urls', app_name='car-photos') ), (r'^userphotos/', include('webui.photos.urls', app_name='profile-photos') ),) and photos/urls.py: urlpatterns = patterns('webui.photos.views', url(r'^$'...

Project Euler #101 - how to work around numpy polynomial overflow?

Project Euler #101 I just started learning Numpy and it so far looks pretty straightforward to me. One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur. u = numpy.poly1d([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1]) for i in xrange(1, 11): print(i, u(i)) The results are: (1, 1...

How do I ignore lines using difflib.ndiff?

According to the documentation, you can provide a linejunk function to ignore certian lines. However, I can't get it to work. Here is some sample code for discussion: from re import search from difflib import ndiff t1 = 'one 1\ntwo 2\nthree 3' t2 = 'one 1\ntwo 29\nthree 3' diff = ndiff(t1.splitlines(), t2.splitlines(), lambda x: sear...

Logging into facebook with python

If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why? import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.CookieJar() opener = urllib2.bu...

Python Image Library produces a crappy quality jpeg when I resize a picture.

I use the Python Image Library (PIL) to resize an image and create a thumbnail. Why is it that my code produces an image that is so crappy and low-quality? Can someone tell me how to modify the code so that it's the highest quality JPEG? def create_thumbnail(buffer, width=100, height=100): im = Image.open(StringIO(buffer)) if im...

Debugging Django Forms validation errors

One of my forms fails on form.is_valid() First time I debug a Django form so I am not too sure where to look forms.py class ImageForm(forms.ModelForm): def __init__(self,user,*args,**kwargs): super(ImageForm,self ).__init__(*args,**kwargs) # populates the form class Meta: model = KMSImageP fields = ('name', ...

Python Matplotlib rectangular binning

I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this: But I'm looking for something like this: Example Code: from matplotlib import pyplot as plt import random foo = lambda : random.gauss(0.0,1.0) x = [foo() for i in xrange(5000)] y = [foo() for i ...

In Python, how can I put a thread to sleep until a specific time?

I know that I can cause a thread to sleep for a specific amount of time with: time.sleep(NUM) How can I make a thread sleep until 2AM? Do I have to do math to determine the number of seconds until 2AM? Or is there some library function? ( Yes, I know about cron and equivalent systems in Windows, but I want to sleep my thread in pyt...

Detect if a process is already running and collaborate with it.

I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where: The number of producers va...

Using python's map() with multiple args?

Okay, so I've got a piece of Python code which really needs optimizing. I need to iterate over every single pixel of a small (80x60) image and extract the RGB values from it. The code in the loop itself isn't too slow, but I'm doing it using nested for loops, which I assume add quite a bit of overhead... xr = xrange(80) yr = xrange(60)...

Is indentation so very important in python?

I am new to python. I learning this stuff because google app engine doesn't allow php. Python is touted to be an easy and friendly language to use. But I find trying to tamper with an existing code causes indentation errors. For example: this piece of code class SearchThread(Thread): def __init__(self, s, q): Thread.__init__(sel...