python

Calculating average in interchangable range?

I know it's because of n, but n is supposed to be any variable, and left as n, this is what I have: def average(n): if n >= 0: avg = sum((range(1:int(n)))/float(len(range(1:int(n))))) print avg how do I fix it? ...

Django Forms - Can the initial value of one field be dependant on another?

Example, for this form: >>> class CommentForm(forms.Form): ... name = forms.CharField(initial='class') ... action = forms.ChoiceField(...) Can I have the choices in the action field be different depending on what is in the name field? ...

Python Service Custom Command Arguments

I am currently working on a python program which runs as a windows service using win32service and win32serviceutil. The service runs as it should and even after using py2exe, everything is fine (the service monitors target folder(s) and autmotically FTP's newly created files to specified FTP location). I would like, however, to add some ...

python string replacement with % character/**kwargs weirdness

Following code: def __init__(self, url, **kwargs): for key in kwargs.keys(): url = url.replace('%%s%' % key, str(kwargs[key])) Throws the following exception: File "/home/wells/py-mlb/lib/fetcher.py", line 25, in __init__ url = url.replace('%%s%' % key, str(kwargs[key])) ValueError: incomplete format The string has a forma...

Python pysqlite2 dbapi2 problem

I'm having an issue with the line: from pysqlite2 import dbapi2 as sqlite The error i'm getting is: ImportError: /usr/lib/python2.4/site-packages/pysqlite2/_sqlite.so: undefined symbol: sqlite3_enable_shared_cache What can I do to solve this problem? Thanks! ...

Appscript to write iTunes artwork

I'm trying to capture artwork from a pict file and embed into a track on iTunes using python appscript. I did something like this: imFile = open('/Users/kartikaiyer/temp.pict','r') data = imFile.read() it = app('iTunes') sel = it.current_track.get() sel.artworks[0].data_.set(data[513:]) I get an error OSERROR: -1731 MESSAGE: Unknow...

Data Structure for storing a sorting field to efficiently allow modifications

I'm using Django and PostgreSQL, but I'm not absolutely tied to the Django ORM if there's a better way to do this with raw SQL or database specific operations. I've got a model that needs sequential ordering. Lookup operations will generally retrieve the entire list in order. The most common operation on this data is to move a row to th...

Get json data via url and use in python (simplejson)

I imagine this must have a simple answer, but I am struggling: I want to take a url (which outputs json) and get the data in a usable dictionary in python. I am stuck on the last step. >>> import urllib2 >>> import simplejson >>> req = urllib2.Request("http://vimeo.com/api/v2/video/38356.json", None, {'user-agent':'syncstream/vimeo'}) ...

post_save in django to update instance immediately

hello, I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record: def my_handler(sender, instance=False, **kwargs): t = Test.objects.filter(id=instance.id) t.blah = 'hello' t.save() class...

Android: Java v. Python

Is there any reason to favor Python or Java over the other for developing on Android phones, other than the usual Python v. Java issues? ...

PyQt: Trouble with asterisk on modification in QPlainTextEdit

I'm having a problem with a QPlainTextEdit. I want the "contents have been modified" asterisk to appear in the title bar whenever the contents have been modified. In the example below, type a few letters. The asterisk appears as it should. Hit Ctrl+S, the asterisk disappears as it should. But then if you type a few more letters... w...

[Django] Custom authentication backend functions in some cases, not always

I am using a custom authentication backend built on CAS and LDAP in a Django project. I intend to have it set up such that it can get permissions based on the what LDAP groups a user is part of. However, I have had problems with it and took a step back, so that both has_perm and has_module_perms in my backend return True always. What I ...

Does python have 'private' variables in classes?

I'm coming from the JAVA world and reading bruce eckels' python 3 patterns idioms. While reading about classes...it goes on to say that in python there is no need to declare class variables. You just use them in the constructor...and boom..they are there. So for example: class Simple: def __init__(self1, str): ...

Python - Working around memory leaks

I have a Python program that runs a series of experiments, with no data intended to be stored from one test to another. My code contains a memory leak which I am completely unable to find (I've look at the other threads on memory leaks). Due to time constraints, I have had to give up on finding the leak, but if I were able to isolate eac...

Why can't Python find my path? (django)

import sys sys.path.append('/home/myuser/svn-repos/myproject') from myproject.settings import * But, it says module not found when I run the script? By the way, settings.py has been set up and manage.py syncdb works. ...

How to permanently append a path to Python for Linux?

I know there are multiple solutions online, but some are for windows, some are environmental variable, etc.. What is the best way? ...

Why am I getting this error in Django?

I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong. Traceback (most recent call last): File "parse.py", line 8, in ? from butterfly.flower.models import Channel, Item ...

General programming question. When to use OOP?

My program needs to do 2 things. Extract stuff from a webpage. Do stuff with a webpage. However, there are many webpages, such as Twitter and Facebook. should I do this? def facebookExtract(): code here def twitterExtract(): code here def myspaceExtract(): code here def facebookProcess(): code here def twitterProce...

Checking arguments in numerical python code

I find myself writing the same argument checking code all the time for number-crunching: def myfun(a, b): if a < 0: raise ValueError('a cannot be < 0 (was a=%s)' % a) # more if.. raise exception stuff here ... return a + b Is there a better way? I was told not to use 'assert' for these things (though I don't see th...

I'm a python beginner, dictionary is new

Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary. How to think of the solution? ...