python

Trappings MySQL Warnings on Calls Wrapped in Classes -- Python

I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes. I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. These seem to run ...

Bimodal distribution in C or Python

What's the easiest way to generate random values according to a bimodal distribution in C or Python? I could implement something like the Ziggurat algorithm or a Box-Muller transform, but if there's a ready-to-use library, or a simpler algorithm I don't know about, that'd be better. ...

Which version of python is currently best for os x?

After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard. I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6 For me it's most important for Twisted, PIL and psycopg2 to be working without a problem. Can an...

What's the best way to initialize a dict of dicts in Python?

A lot of times in Perl, I'll do something like this: $myhash{foo}{bar}{baz} = 1 How would I translate this to Python? So far I have: if not 'foo' in myhash: myhash['foo'] = {} if not 'bar' in myhash['foo']: myhash['foo']['bar'] = {} myhash['foo']['bar']['baz'] = 1 Is there a better way? ...

Django: Access primary key in models.filefield(upload_to) location.

I'd like to save my files using the primary key of the entry. Here is my code: def get_nzb_filename(instance, filename): if not instance.pk: instance.save() # Does not work. name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower() name_slug = re.sub('[-]+', '-', name_slug) return u'files/%s_%s.n...

Simultaneously inserting and extending a list?

Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element): >>> a = ['1', '2', '3', '4'] >>> b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'):] >>> b <<< ['1', '2', '2.4', '2.6', '3', '4'] ...

Is it possible to create anonymous objects in Python?

I'm debugging some Python that takes, as input, a list of objects, each with some attributes. I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number. Is there a more concise way than this? x1.foo = 1 x2.foo = 2 x3.foo = 3 x4.foo = 4 myfunc([x1, x2, x3, x4]) Ideally, I'...

Can a neural network be used to find a functions minimum(a)?

I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest). Then I realized I didn't even know if a NN is good for minimization. What do you think? ...

sorting a list of dictionary values by date in python

I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys. ex: data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) I want to sort the list in reverse order by value of 'date' ...

Check if value exists in nested lists

in my list: animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') The add function should check that the animal and action haven't been added before adding them to the list. Is there a way to accomplish...

Separating Models and Request Handlers In Google App Engine

I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily? Thanks, Collin ...

Writing a binary buffer to a file in python

Hi there, I have some python code that: Takes a BLOB from a database which is compressed. Calls an uncompression routine in C that uncompresses the data. Writes the uncompressed data to a file. It uses ctypes to call the C routine, which is in a shared library. This mostly works, except for the actual writing to the file. To uncomp...

How to unlock an sqlite3 db?

OMG! What an apparent problem... my django based scripts have locked my sqlite db... Does anyone know how to fix? ...

Effective way to iteratively append to a string in Python?

I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this? def getwords(text, splitchars=' \t|!?.;:"'): """ Genera...

How to create a Python decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the pro...

How can I profile a multithread program in Python?

I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation? ...

How can I cluster a graph in Python?

Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. So, what I did was to store all the lin...

Breaking out of nested loops

Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.) for x in range(10): for y in range(10): print x*y if x*y > 50: "break both loops" I.e., is there a nicer way than: class BreakIt(Exception):...

Django Forms, set an initial value to request.user

Is there some way to make the following possible, or should it be done elsewhere? class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = request.user # is there some way to make t...

Python - Acquire value from dictionary depending on location/index in list

Hi Everybody, From MySQL query I get data which I put into a dictionary "d": d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)} I have a list "m" with...