content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: question comparing multiprocessing vs twisted Got a situation where I'm going to be parsing websites. each site has to have it's own "parser" and possibly it's own way of dealing with cookies/etc.. I'm trying to get in my head which would be a better choice. Choice I: I can create a multiprocessing function, wher...
question comparing multiprocessing vs twisted
Got a situation where I'm going to be parsing websites. each site has to have it's own "parser" and possibly it's own way of dealing with cookies/etc.. I'm trying to get in my head which would be a better choice. Choice I: I can create a multiprocessing function, where the (masterspawn) app gets an input url, and in t...
[ "There are two dimensions to this question: concurrency and distribution. \nConcurrency: either Twisted or multiprocessing will do the job of concurrently handling fetching/parsing jobs. I'm not sure though where your premise of the \"Twisted overhead\" comes from. On the contrary, the multiprocessing path would in...
[ 2, 1 ]
[]
[]
[ "multiprocessing", "python", "twisted" ]
stackoverflow_0003374943_multiprocessing_python_twisted.txt
Q: How do I choose a task_id using celery? For now I get a task_id from the async_result and have to save it the get it back later. Would be better if I knew what the task_id what made of so I can calculate it back instead of pulling from the DB. E.G: set a task with task_id=("%s-%s" % (user_id, datetime)). A: You ...
How do I choose a task_id using celery?
For now I get a task_id from the async_result and have to save it the get it back later. Would be better if I knew what the task_id what made of so I can calculate it back instead of pulling from the DB. E.G: set a task with task_id=("%s-%s" % (user_id, datetime)).
[ "You can certainly use \"natural ids\", but then to be really useful they would have to\nbe reverseable, which doesn't work if you add that timestamp. Also the ids are unique, so two tasks can't have the same id (the behavior then is undefined)\nIf you have a task to refresh the timeline of a twitter user, then you...
[ 4 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0003357489_celery_django_python.txt
Q: Clarifications on a python script file Just need some clarification on how to design a python script file test.py. When defining functions, do they have to go on the top of the file right after the imports? should I be doing that main check in my file? I want to run this file on my server as a cron job. If the ...
Clarifications on a python script file
Just need some clarification on how to design a python script file test.py. When defining functions, do they have to go on the top of the file right after the imports? should I be doing that main check in my file? I want to run this file on my server as a cron job. If the file gets too big (I have my sqlalchemy defi...
[ "Most scripts look something like the following:\nimport module1\nimport module2\n\nCONSTANT=...\n\ndef foo():\n ...\n\ndef bar():\n ....\n\nclass Baz():\n ....\n\ndef run(verbose=False):\n ....\n\nif __name__=='__main__':\n import optparse\n def parse_options():\n usage = 'usage: %prog [optio...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003379794_python.txt
Q: why are these C / Cython arrays defined as character, not integer arrays? in an effort to solve question #3367795 here on SO i have to cope with a number of subproblems. one of these is: in said algorithm (levenshtein distance), several arrays are allocated in memory and initialized with the lines cdef char *m1 ...
why are these C / Cython arrays defined as character, not integer arrays?
in an effort to solve question #3367795 here on SO i have to cope with a number of subproblems. one of these is: in said algorithm (levenshtein distance), several arrays are allocated in memory and initialized with the lines cdef char *m1 = <char *>calloc( blen + 2, sizeof( char ) ) cdef char *m2 = <ch...
[ "Despite the misleading name, char types in C language are ordinary integral types, just like short, int, long and such. Of all integral types, chars have the smallest range and occupy the smallest amount of memory. So, if in your application it is important to save as much memory as possible, it might make sense t...
[ 8, 2 ]
[]
[]
[ "c", "cython", "python" ]
stackoverflow_0003379795_c_cython_python.txt
Q: Calculation to get page count based on # of items If I have 177 items, and each page has 10 items that means I'll have 18 pages. I'm new to python and having used any of the math related functions. How can I calculate 177/10 and then get round up so I get 18 and not 17.7 A: import math math.ceil(float(177)/10) ...
Calculation to get page count based on # of items
If I have 177 items, and each page has 10 items that means I'll have 18 pages. I'm new to python and having used any of the math related functions. How can I calculate 177/10 and then get round up so I get 18 and not 17.7
[ "import math\nmath.ceil(float(177)/10)\n\n", "You can do it with integer arithmetic:\n\nitems_per_page = 10\nnumber_of_pages = (x + items_per_page - 1) // items_per_page\n\n" ]
[ 7, 5 ]
[]
[]
[ "math", "python" ]
stackoverflow_0003379971_math_python.txt
Q: String formatting issues and concatenating a string with a number I'm coming from a c# background, and I do this: Console.Write("some text" + integerValue); So the integer automatically gets converted to a string and it outputs. In python I get an error when I do: print 'hello' + 10 Do I have to convert to strin...
String formatting issues and concatenating a string with a number
I'm coming from a c# background, and I do this: Console.Write("some text" + integerValue); So the integer automatically gets converted to a string and it outputs. In python I get an error when I do: print 'hello' + 10 Do I have to convert to string everytime? How would I do this in python? String.Format("www.someurl....
[ "From Python 2.6:\n>>> \"www.someurl.com/{0}/blah.html\".format(100)\n'www.someurl.com/100/blah.html'\n\nTo support older environments, the % operator has a similar role:\n>>> \"www.someurl.com/%d/blah.html\" % 100\n'www.someurl.com/100/blah.html'\n\nIf you would like to support named arguments, then you can can pa...
[ 4, 3, 2, 1 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0003380029_formatting_python.txt
Q: Python Window Resize Using Python + PyGTK. Is there a signal/event way of checking for a window resize? If so then what is the easiest way of implementing and using this signal. A: a gtk.Window is also a gtk.Container, so it answers to the check-resize signal. Here's minimal sample code: import gtk def changed(...
Python Window Resize
Using Python + PyGTK. Is there a signal/event way of checking for a window resize? If so then what is the easiest way of implementing and using this signal.
[ "a gtk.Window is also a gtk.Container, so it answers to the check-resize signal.\nHere's minimal sample code:\nimport gtk\n\ndef changed(window):\n print 'I have resized.'\n\nw = gtk.Window()\nw.connect('check-resize', changed)\nw.show()\ngtk.main()\n\n" ]
[ 7 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003380003_gtk_pygtk_python.txt
Q: Python and MySQL compile version How do I check if my python and mysql are 32 bit installations or 64 bit? A: You can use the file command : file `which python` file `which mysql` The file command is available on all UNIX-based systems. A: readelf -h $(which mysqld) | grep Class readelf -h $(which python) | ...
Python and MySQL compile version
How do I check if my python and mysql are 32 bit installations or 64 bit?
[ "You can use the file command :\n\nfile `which python`\nfile `which mysql`\n\nThe file command is available on all UNIX-based systems.\n", "readelf -h $(which mysqld) | grep Class\nreadelf -h $(which python) | grep Class\n\nSeems to work for me. The readelf command is part of the GNU binutils.\n" ]
[ 3, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003379142_mysql_python.txt
Q: Problem making a GET request and spoof User-Agent in urllib2 With this code, urllib2 make a GET request: #!/usr/bin/python import urllib2 req = urllib2.Request('http://www.google.fr') req.add_header('User-Agent', '') response = urllib2.urlopen(req) With this one (which is almost the same), a POST request: #!/usr/...
Problem making a GET request and spoof User-Agent in urllib2
With this code, urllib2 make a GET request: #!/usr/bin/python import urllib2 req = urllib2.Request('http://www.google.fr') req.add_header('User-Agent', '') response = urllib2.urlopen(req) With this one (which is almost the same), a POST request: #!/usr/bin/python import urllib2 headers = { 'User-Agent' : '' } req = ur...
[ "Use:\nreq = urllib2.Request('http://www.google.fr', None, headers)\n\nor:\nreq = urllib2.Request('http://www.google.fr', headers=headers)\n\n" ]
[ 4 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003380183_python_urllib2.txt
Q: How do I use gluLookAt properly? I don't want to get into complex trigonometry to calculate rotations and things like that for my 3D world so gluLookAt seems like a nice alternative. According to the documentation all I need to do is place 3 coordinates for the cameras position, three for what I should be looking ...
How do I use gluLookAt properly?
I don't want to get into complex trigonometry to calculate rotations and things like that for my 3D world so gluLookAt seems like a nice alternative. According to the documentation all I need to do is place 3 coordinates for the cameras position, three for what I should be looking at and an "up" position. The last made...
[ "(The intuition behind the \"up\" vector in gluLookAt is simple: Look at anything. Now tilt your head 90 degrees. Where you are hasn't changed, the direction you're looking at hasn't changed, but the image in your retina clearly has. What's the difference? Where the top of your head is pointing to. That's the up ve...
[ 39 ]
[]
[]
[ "graphics", "opengl", "pyopengl", "python" ]
stackoverflow_0003380100_graphics_opengl_pyopengl_python.txt
Q: Escape quotes contained within certain html tags I've done a mysqldump of a large database, ~300MB. It has made an error though, it has not escaped any quotes contained in any <o:p>...</o:p> tags. Here's a sample: ...Text here\' escaped correctly, <o:p> But text in here isn't. </o:p> Out here all\'s well again... ...
Escape quotes contained within certain html tags
I've done a mysqldump of a large database, ~300MB. It has made an error though, it has not escaped any quotes contained in any <o:p>...</o:p> tags. Here's a sample: ...Text here\' escaped correctly, <o:p> But text in here isn't. </o:p> Out here all\'s well again... Is it possible to write a script (preferably in Pytho...
[ "If the \"lines\" your file is divided into are of reasonable lengths, and there are no binary sequences in it that \"reading as text\" would break, you can use fileinput's handy \"make believe I'm rewriting a file in place\" functionality:\n import re\n import fileinput\n\n tagre = re.compile(r\"<o:p>.*?</o:...
[ 4 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003380146_mysql_python.txt
Q: Check if specific wsgi handler is running I am creating a mapping application that uses a WSGI service and needs a different config file for each map. Currently, I launch the service with: import os, sys tilecachepath = '/usr/local/lib/python2.6/dist-packages/TileCache-2.10-py2.6.egg/TileCache' sys.path.append(ti...
Check if specific wsgi handler is running
I am creating a mapping application that uses a WSGI service and needs a different config file for each map. Currently, I launch the service with: import os, sys tilecachepath = '/usr/local/lib/python2.6/dist-packages/TileCache-2.10-py2.6.egg/TileCache' sys.path.append(tilecachepath) from TileCache.Service import Serv...
[ "WSGI itself offers no way of knowing what layers are already wrapping a certain application, nor does Apache know about that. I would recommend having the wsgiHandler record its presence, so that you can avoid using it multiple times. If you can't alter the existing code, you can do it with your own wrappers for...
[ 2 ]
[]
[]
[ "apache", "gis", "mod_wsgi", "python" ]
stackoverflow_0003380303_apache_gis_mod_wsgi_python.txt
Q: PyGTK connect_signals Ok so I have a little test program here: This is in my file that I load through gtk.Builder <object class="GtkWindow" id="mainWindow"> <property name="default_width">500</property> <property name="default_height">250</property> <signal name="delete_event" handler="endProgram" /> <...
PyGTK connect_signals
Ok so I have a little test program here: This is in my file that I load through gtk.Builder <object class="GtkWindow" id="mainWindow"> <property name="default_width">500</property> <property name="default_height">250</property> <signal name="delete_event" handler="endProgram" /> </object> I then use this: ...
[ "Per the docs, connect_signals takes as the argument a mapping or instance, and\n\nuses Python's introspective features\n to look at the keys (if object is a\n mapping) or attributes (if object is\n an instance) and tries to match them\n with the signal handler names given in\n the interface description. The\n...
[ 3 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003380426_pygtk_python.txt
Q: Replacing value in all cursor rows Using SQLite and Python 3.1, I want to display currency data in a HTML table via. a template which accepts a cursor as a parameter. Hence all currency values must have 2 decimal places, but SQLite stores them as float type (even though the structure states decimal :-( ) so some ...
Replacing value in all cursor rows
Using SQLite and Python 3.1, I want to display currency data in a HTML table via. a template which accepts a cursor as a parameter. Hence all currency values must have 2 decimal places, but SQLite stores them as float type (even though the structure states decimal :-( ) so some must be converted before display (eg. I ...
[ "Yep:\ncur.execute(\"select order_no, amount from orders where cust_id=123\")\ndictrows = [dict(row) for row in cur]\nfor r in dictrows:\n r['amount'] = format(r['amount'],'%.2f')\n\nThere are other ways, but this one seems the simplest and most direct one.\n", "An alternative is to store your value as an intege...
[ 10, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003380360_python_sqlite.txt
Q: Create Explorer.exe's File - Context Menu in WxPython application I have a WxPython app that, among other things, has a integrated file-browser. I want to be able to create a system-default file context menu (e.g. what you get if you right-click on a file in windows explorer) when a user right clicks on one of the...
Create Explorer.exe's File - Context Menu in WxPython application
I have a WxPython app that, among other things, has a integrated file-browser. I want to be able to create a system-default file context menu (e.g. what you get if you right-click on a file in windows explorer) when a user right clicks on one of the items within my application. Note: I already know how to create my own...
[ "If you have python win32 installed, then look under the directory <PYTHON>/lib/site-packages/win32comext/shell/demos/servers. This contains a file context_menu.py which has sample code for creating a shell extension.\nUpdate: I think you want the folder_view.py sample.\n" ]
[ 0 ]
[]
[]
[ "python", "user_interface", "windows_xp", "wxpython" ]
stackoverflow_0003380986_python_user_interface_windows_xp_wxpython.txt
Q: Mod_Rewrite existing file check goes pear shaped, or passes wrong querystring I'm using Apache, Python (fastcgi), mod_rewrite. I want http://foo/bar to redirect internally to http://main.py?q=foo/bar Now my .htacess file contains Options +ExecCGI AddHandler cgi-script .py DirectoryIndex main.py RewriteEngine o...
Mod_Rewrite existing file check goes pear shaped, or passes wrong querystring
I'm using Apache, Python (fastcgi), mod_rewrite. I want http://foo/bar to redirect internally to http://main.py?q=foo/bar Now my .htacess file contains Options +ExecCGI AddHandler cgi-script .py DirectoryIndex main.py RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Rewrite...
[ "It sounds like a problem with content negotiation. Try adding...\nOptions -Multiviews\n\n...at the top of your .htaccess file.\n", "Your first problem is caused by MultiViews, which is resolving the non-existent resource foo/bar to the existing file foo.py, then likely passing it PATH_INFO of /bar. You can disab...
[ 1, 1 ]
[]
[]
[ ".htaccess", "mod_rewrite", "python" ]
stackoverflow_0003381036_.htaccess_mod_rewrite_python.txt
Q: How do I delete an object in a django relation (While keeping all related objects)? I have the following model: One name (Char) Many one (ForeignKey,blank=True,null=True) title (Char) I want to delete a One instance and all related objects should loose their relation to the One instance. At the moment...
How do I delete an object in a django relation (While keeping all related objects)?
I have the following model: One name (Char) Many one (ForeignKey,blank=True,null=True) title (Char) I want to delete a One instance and all related objects should loose their relation to the One instance. At the moment my code looks like this: one=One.objects.get(<some criterion>) more=Many.objects.filter...
[ "The code given is correct. My problem when asking the question was a typo in my implementation.\nshame on me\nwell... there is still a bit that could be improved on:\nmore=Many.objects.filter(one=one)\nfor m in more\n m.one=None\n m.save()\n#and finally:\none.delete()\n\ncan be written as:\nfor m in one.many...
[ 2, 1 ]
[]
[]
[ "django", "django_database", "python" ]
stackoverflow_0003375374_django_django_database_python.txt
Q: xml validation: validating a URI type I'm using python's lxml to validate xmls against a schema. I have a schema with an element: <xs:element name="link-url" type="xs:anyURL"/> and I test, for example, this (part of an) xml: <a link-url="server/path"/> I would like this test to FAIL because the link-url doesn't ...
xml validation: validating a URI type
I'm using python's lxml to validate xmls against a schema. I have a schema with an element: <xs:element name="link-url" type="xs:anyURL"/> and I test, for example, this (part of an) xml: <a link-url="server/path"/> I would like this test to FAIL because the link-url doesn't start with http://. I tried switching anyUR...
[ "(I'm pretty sure xs:anyURL is not valid. The XML Schema standard calls it anyURI. And since link-url is an attribute, shouldn't you be using xs:attribute instead of xs:element?)\nYou could restrict the URIs by creating a new simpleType based on it, and put a restriction on the pattern. For example,\n#!/usr/bin/env...
[ 3 ]
[]
[]
[ "python", "validation", "xml", "xsd" ]
stackoverflow_0003381507_python_validation_xml_xsd.txt
Q: How can I vectorize a function in numpy with multiple arguments? I am trying to do a fit to a given function using Scipy. Scipy.optimize.leastsq needs a vectorized function as one of the input parameters. This all works fine, but now I have a more complicated function which is not vectorized automatically by Scip...
How can I vectorize a function in numpy with multiple arguments?
I am trying to do a fit to a given function using Scipy. Scipy.optimize.leastsq needs a vectorized function as one of the input parameters. This all works fine, but now I have a more complicated function which is not vectorized automatically by Scipy/Numpy. def f1(a, parameters): b, c = parameters result = sc...
[ "Sorry, I'm not sure what the question is. Python *args collects any number of args,\nwhich a function can unpack as it pleases; see\ndocs.python.org/tutorial/...\nimport numpy as np\nfrom scipy.integrate import quad\n\ndef f2( a, *args ):\n print \"args:\", args\n return a + np.sum( args, axis=0 )\n\nx = np....
[ 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0003376018_numpy_python_scipy.txt
Q: Django: autoslug -> custom slugifier I have a prob. I'm trying to create a custom slugify functiom. I use django.autoslug. Due to autoslug documentation I was able to create a custom slugifier, but it needs to be improved and I do not know how do I realize that. So I have a string (book title) i.e. .NET Framework ...
Django: autoslug -> custom slugifier
I have a prob. I'm trying to create a custom slugify functiom. I use django.autoslug. Due to autoslug documentation I was able to create a custom slugifier, but it needs to be improved and I do not know how do I realize that. So I have a string (book title) i.e. .NET Framework 4.0 with C# & VB in VisualStudio 2010. I w...
[ "import re\npoint = re.compile( r\"(?<=\\d)\\.(?=\\d)\" )\npoint.sub( value, \"point\" )\n\nto change the . s that should be \"point\" , and then do str.replace to change the others.\nExplanation\npoint matches a . which is sandwiched between two digits.\n(?<=spam)ham(?=eggs) is a (positive) lookaround. It means \"...
[ 0 ]
[]
[]
[ "django", "python", "regex", "slug" ]
stackoverflow_0003382492_django_python_regex_slug.txt
Q: How do I get some string values from Pylons controller be assigned to JavaScript variables with Mako? I'm developing under Pylons using Mako templates. The problem is that I need to assign a string from some attribute of tmpl_context to a JavaScript variable in a page body. The additional problem is that this stri...
How do I get some string values from Pylons controller be assigned to JavaScript variables with Mako?
I'm developing under Pylons using Mako templates. The problem is that I need to assign a string from some attribute of tmpl_context to a JavaScript variable in a page body. The additional problem is that this string can be quite arbitrary, ie can contain such characters like ", ', <, >, etc... Is there a common way to ...
[ "You have some arbitrary data in c.my_string, and therefore do not want to use \"|n\", right?\nQuickiest way to escape it in JS-style escaping would be\nvar a = ${c.my_string.__repr__()|n}; # Note lack of \"\" around it! \n\nHowever I'm unsure about <> characters (with something like </script> inserted), maybe you ...
[ 2, 1 ]
[]
[]
[ "escaping", "mako", "pylons", "python", "templating" ]
stackoverflow_0003382328_escaping_mako_pylons_python_templating.txt
Q: Python regex help needed I need to get info from a website that outputs it between <font color="red">needed-info-here</font> OR <span style="font-weight:bold;">needed-info-here</span>, randomly. I can get it when I use start = '<font color="red">' end = '</font>' expression = start + '(.*?)' + end match = re.compi...
Python regex help needed
I need to get info from a website that outputs it between <font color="red">needed-info-here</font> OR <span style="font-weight:bold;">needed-info-here</span>, randomly. I can get it when I use start = '<font color="red">' end = '</font>' expression = start + '(.*?)' + end match = re.compile(expression).search(web_sour...
[ "Don't parse HTML with regex.\nRegex is not the right tool to use for this problem. Look up BeautifulSoup or lxml.\n", "You can join two alternatives with a vertical bar:\nstart = '<font color=\"red\">|<span style=\"font-weight:bold;\">'\nend = '</font>|</span>'\n\nsince you know that a font tag will always be cl...
[ 7, 3, 1, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003382552_python_regex.txt
Q: Can this program damage my monitor? I made a Python program that switches the entire monitor back and forth between random colours very quickly. I'm wondering if it can harm my monitor somehow. Also on an unrelated note, it's tripy to stair at the program for extended periods of time. The program import Tkinter ...
Can this program damage my monitor?
I made a Python program that switches the entire monitor back and forth between random colours very quickly. I'm wondering if it can harm my monitor somehow. Also on an unrelated note, it's tripy to stair at the program for extended periods of time. The program import Tkinter import random class AppTk(Tkinter.Tk): ...
[ "I wouldn't say it would damage your monitor since there are programs that do this in an attempt to fix dead pixels. I can't remember any off the top of my head since I haven't used one in 3 years. \nSo it shouldn't do much, but then again you wouldn't be running this for extended periods of time, would you?\n", ...
[ 1, 1, 1 ]
[]
[]
[ "hardware", "monitor", "python" ]
stackoverflow_0003380797_hardware_monitor_python.txt
Q: Where to put my sqlalchemy code in my script? I had my sqlalchemy related code in my main() method in my script. But then when I created a function, I wasn't able to reference my 'products' mapper because it was in the main() method. Should I be putting the sqlalchemy related code (session, mapper, and classes) in...
Where to put my sqlalchemy code in my script?
I had my sqlalchemy related code in my main() method in my script. But then when I created a function, I wasn't able to reference my 'products' mapper because it was in the main() method. Should I be putting the sqlalchemy related code (session, mapper, and classes) in global scope so all functions in my single file sc...
[ "Typical approach is to define all mappings in separate model module, with one file per class/table.\nThen you just import needed classes whenever need them. \n" ]
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003382739_python_sqlalchemy.txt
Q: Downloading an image, want to save to folder, check if file exists So I have a recordset (sqlalchemy) of products that I am looping, and I want to download an image and save it to a folder. If the folder doesn't exist, I want to create it. Also, I want to first check if the image file exists in the folder. If it ...
Downloading an image, want to save to folder, check if file exists
So I have a recordset (sqlalchemy) of products that I am looping, and I want to download an image and save it to a folder. If the folder doesn't exist, I want to create it. Also, I want to first check if the image file exists in the folder. If it does, don't download just skip that row. /myscript.py /images/ I want t...
[ "I think you can just use urllib.urlretrieve here:\nimport errno\nimport os\nimport urllib\n\ndef require_dir(path):\n try:\n os.makedirs(path)\n except OSError, exc:\n if exc.errno != errno.EEXIST:\n raise\n\ndirectory = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"imag...
[ 10, 1 ]
[]
[]
[ "download", "file_io", "python" ]
stackoverflow_0003382812_download_file_io_python.txt
Q: Proper way to edit existing entity in tipfy I'm using a PersonEditHandler class in tipfy to edit a Person entity. I have the get() and post() methods formed, but when I reference self.person (to check if the get method found the existing person by key), I get an 'object has no attribute' error. This is because...
Proper way to edit existing entity in tipfy
I'm using a PersonEditHandler class in tipfy to edit a Person entity. I have the get() and post() methods formed, but when I reference self.person (to check if the get method found the existing person by key), I get an 'object has no attribute' error. This is because I never initialize it in the init method since I...
[ "I would recommend foregoing the __init__ and rather adding a class attribute:\nclass PersonEditHandler(RequestHandler, Jinja2Mixin): \n person = None\n\nThis way, when you access a self.person that's never been set on a specific instance self, it will defer to the class and you'll get None as desired; when you ...
[ 1 ]
[]
[]
[ "google_app_engine", "multiple_inheritance", "python", "tipfy", "web_applications" ]
stackoverflow_0003379084_google_app_engine_multiple_inheritance_python_tipfy_web_applications.txt
Q: active object in python for s60 How do I use active object in python for s60? can anybody give me a code example? A: There's a simple example here: def run(self): self.lock = e32.Ao_lock() self.lock.wait() # restore old title etc. and finish def exit_callback(self): # unlocks the application and...
active object in python for s60
How do I use active object in python for s60? can anybody give me a code example?
[ "There's a simple example here:\ndef run(self):\n self.lock = e32.Ao_lock()\n self.lock.wait()\n # restore old title etc. and finish\n\ndef exit_callback(self):\n # unlocks the application and lets it finish\n self.lock.signal()\n\nand that same URL also contains a detailed explanation (and more info...
[ 1 ]
[]
[]
[ "active_objects", "pys60", "python" ]
stackoverflow_0003382957_active_objects_pys60_python.txt
Q: Greedy versus Non-Greedy matching in Python re Please help me to discover whether this is a bug in Python (2.6.5), in my competence at writing regexes, or in my understanding of pattern matching. (I accept that a possible answer is "Upgrade your Python".) I'm trying to parse a Yubikey token, allowing for the optio...
Greedy versus Non-Greedy matching in Python re
Please help me to discover whether this is a bug in Python (2.6.5), in my competence at writing regexes, or in my understanding of pattern matching. (I accept that a possible answer is "Upgrade your Python".) I'm trying to parse a Yubikey token, allowing for the optional extras. When I use this regex to match a token ...
[ "I'd recommend using yubikey-python for Python interfacing to yubikey -- but, that's a side (and strictly pragmatical) issue;-).\nIn theory, there should be no cases where a choice between greedy and non-greedy causes a RE to match in one case and fail in another -- it should only affects what gets matched (and as ...
[ 3, 0 ]
[]
[]
[ "greedy", "non_greedy", "python", "regex" ]
stackoverflow_0003382690_greedy_non_greedy_python_regex.txt
Q: Mako Templates : How to find the name of the template which the current template is included by? I have multiple templates that include each other, such as : t1.html : ... <%include file="t2.html" args="docTitle='blablabla'" /> ... t2.html: <%page args="docTitle='Undefined'"/> <title>${docTitle}</title> ... And ...
Mako Templates : How to find the name of the template which the current template is included by?
I have multiple templates that include each other, such as : t1.html : ... <%include file="t2.html" args="docTitle='blablabla'" /> ... t2.html: <%page args="docTitle='Undefined'"/> <title>${docTitle}</title> ... And what I want to do is to determine that t2 is included by t1 (or another one, so I can use its name). N...
[ "As far as I can tell, mako does not provide any information about 'parent' template to included. Moreover, it takes some care to delete any bits of information on that from context passed to included file.\nTherefore only solution I see is to use CPython stack, to find nearest mako template frame and extract neede...
[ 1 ]
[]
[]
[ "cherrypy", "mako", "python" ]
stackoverflow_0003382885_cherrypy_mako_python.txt
Q: How do I use owfs to read an iButton temperature logger? I've installed owfs and am trying to read the data off a iButton temperature logger. owfs lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get i...
How do I use owfs to read an iButton temperature logger?
I've installed owfs and am trying to read the data off a iButton temperature logger. owfs lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by catting the files, e.g. cat onewire/{dev...
[ "I've also had problems with owfs. I found it to be an overengineered solution to what is a simple problem. Now I'm using the DigiTemp code without a problem. I found it to be flexible and reliable. For instance, I store the room's temperature in a log file every minute by running\n/usr/local/bin/digitemp_DS909...
[ 3, 2, 2 ]
[]
[]
[ "1wire", "python", "ubuntu" ]
stackoverflow_0000113185_1wire_python_ubuntu.txt
Q: django models filter() and extra() I have a problem with the extra() method of queryset. So, i retrieve my objects with : invoices = Invoice.objects.select_related().filter(quantity__gt=0,begin__gte=values['start_day'],end__lte=values['end_day']) So it works, I have my invoices. After i use another time filter() ...
django models filter() and extra()
I have a problem with the extra() method of queryset. So, i retrieve my objects with : invoices = Invoice.objects.select_related().filter(quantity__gt=0,begin__gte=values['start_day'],end__lte=values['end_day']) So it works, I have my invoices. After i use another time filter() : invoices = invoices.filter(max__gte=du...
[ "Dump the SQL from the query set object:\nprint invoices.query\n\nIf the cause of your bug is not obvious from looking at the generated SQL, update your question and post the SQL for us to see.\nEDIT 1 based on seeing the SQL\nI'm questioning the very last line in your SQL (re-formatted):\n...\n AND (discount=\"YES...
[ 1 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0003383197_django_orm_python.txt
Q: Combining static HTML, a Django backend and a PHP forum on one server? I have a project coming up for client who is basically happy with how he manages his website. It's lots of HTML files (around 300 of them) that he insists on keeping flat HTML files so can easily edit and manage them using Dreamweaver. His site...
Combining static HTML, a Django backend and a PHP forum on one server?
I have a project coming up for client who is basically happy with how he manages his website. It's lots of HTML files (around 300 of them) that he insists on keeping flat HTML files so can easily edit and manage them using Dreamweaver. His site has a lot of traffic and so I'm looking into options of keeping things simp...
[ "I see no problem with such setup, using lightweight frontend is recommended for django (or any other wsgi app) anyway. Although you should serve static html with nginx itself, not django.\n", "I recommend using Cherokee for ease of administration. (It's very fast too) It makes complex configuration very easy, it...
[ 2, 2 ]
[]
[]
[ "django", "html", "php", "python" ]
stackoverflow_0003382390_django_html_php_python.txt
Q: Python error - psycopg2: no appropriate 64-bit architecture? I'm running Mac OSX. Until today I had Python 2.6 with psycopg2 running just fine, I was using it with Django and Pylons. I've just reintalled postgres (I don't know if this is connected) and suddenly I can't import psycopg2 into Python without a strange...
Python error - psycopg2: no appropriate 64-bit architecture?
I'm running Mac OSX. Until today I had Python 2.6 with psycopg2 running just fine, I was using it with Django and Pylons. I've just reintalled postgres (I don't know if this is connected) and suddenly I can't import psycopg2 into Python without a strange error: >>> import psycopg2 Traceback (most recent call last): ...
[ "Have you just upgraded to Snow Leopard by any chance? The Leopard version of Python is 32-bit, while the 64-bit is in Snow Leopard. It breaks some libraries that use native code that aren't available in 64-bit mode.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0003383263_postgresql_psycopg2_python.txt
Q: Pythonic way to intercept calls to a function? For testing things that query the environment (e.g., os.getenv, sys.version, etc.), it's often more convenient to make the queries lie than to actually fake up the environment. Here's a context manager that does this for one os.getenv call at a time: from __future__ i...
Pythonic way to intercept calls to a function?
For testing things that query the environment (e.g., os.getenv, sys.version, etc.), it's often more convenient to make the queries lie than to actually fake up the environment. Here's a context manager that does this for one os.getenv call at a time: from __future__ import with_statement from contextlib import contextm...
[ "You could easily just pass os.getenv itself as the first argument, then analyze it in the context manager much more simply than ast, code, etc etc:\n>>> os.getenv.__name__\n'getenv'\n>>> os.getenv.__module__\n'os'\n\nAfter that, for reasonably general purpose use, you could have the result object to be returned, o...
[ 4, 1 ]
[]
[]
[ "macros", "python", "scope", "testing" ]
stackoverflow_0003383219_macros_python_scope_testing.txt
Q: How can one find Class of calling function in python? I am trying to determine the owning class of a calling function in python. For example, I have two classes, ClassA and ClassB. I want to know when classb_instance.call_class_a_method() is the caller of class_a.class_a_method() such that: class ClassA(object): ...
How can one find Class of calling function in python?
I am trying to determine the owning class of a calling function in python. For example, I have two classes, ClassA and ClassB. I want to know when classb_instance.call_class_a_method() is the caller of class_a.class_a_method() such that: class ClassA(object): def class_a_method(self): # Some unknown proces...
[ "Well, if you want to traverse call stack and find which class (if any) did call it, its trivial:\ndef class_a_method(self):\n stack = inspect.stack()\n frame = stack[1][0]\n caller = frame.f_locals.get('self', None)\n\nIf you want to check whether caller is of type ClassB, you should use isinstance(caller...
[ 7, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003383417_python.txt
Q: Alternative ways to instantiate a class in Python I am currently writing my python classes and instantiate them like this class calculations_class(): def calculate(self): return True Calculations = calculations_class() I was wondering if I was doing this correctly, or if there were any other ways to ...
Alternative ways to instantiate a class in Python
I am currently writing my python classes and instantiate them like this class calculations_class(): def calculate(self): return True Calculations = calculations_class() I was wondering if I was doing this correctly, or if there were any other ways to instantiate them. Thanks!
[ "Apart from the naming convention issue which other answers have correctly pointed out, you're basically fine: calling a class is indeed by far the most common way of instantiating that class. If you need any per-instance initialization (most typically setting some instance-attributes to initial values), be sure t...
[ 7, 4, 1, 0 ]
[ "I tend to use the following format:\nclass CCalculations(): #Classes always begin with \"C\"\n def __init__(self):\n self.foo = 0\n self.fooBar = 0 #Variables use camelCase\n\n def DoCalculations(self): #Methods use uppercase\n return true\n\n def getFoo(self): \n ...
[ -2 ]
[ "python" ]
stackoverflow_0003383383_python.txt
Q: How to get first top five objects with django.views.generic.date_based.archive_index? I'm trying to display the latest 5 posts using a generic view like this: urlpatterns = patterns('', (r'^$', 'django.views.generic.date_based.archive_index', { 'queryset': Post.objects.all()[:5], 'date_field': ...
How to get first top five objects with django.views.generic.date_based.archive_index?
I'm trying to display the latest 5 posts using a generic view like this: urlpatterns = patterns('', (r'^$', 'django.views.generic.date_based.archive_index', { 'queryset': Post.objects.all()[:5], 'date_field': 'created_on', 'template_name': 'index.html'} }) However I am getting AssertionE...
[ "num_latest: The number of latest objects to send to the template context. By default, it's 15.\n" ]
[ 2 ]
[]
[]
[ "django", "django_generic_views", "django_queryset", "python" ]
stackoverflow_0003383693_django_django_generic_views_django_queryset_python.txt
Q: Do I reference the session when making any db calls in sqlalchemy? In this tutorial it says (http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html) to select all rows of an entity like: s = products.select() rs = s.execute() I get an error saying: This select object is not bound and does not support direct execu...
Do I reference the session when making any db calls in sqlalchemy?
In this tutorial it says (http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html) to select all rows of an entity like: s = products.select() rs = s.execute() I get an error saying: This select object is not bound and does not support direct execution ... Do I need to reference the session object? I just want to get a...
[ "Since that tutorial is built for SQLALchemy 0.2, it is likely that you aren't using that old of a version. In the latest documentation using the connection and passing the select statement to it is the preferred method. Try this instead:\nquery = users.select()\nresult = conn.execute(query)\n\nRef: http://www.sqla...
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003382751_python_sqlalchemy.txt
Q: Pythonic way to assign an instance of a subclass to a variable when a specific string is presented to the constructor of the parent class I want to be able to create an instance of a parent class X, with a string "Q" as an extra argument. This string is to be a name being an identifier for a subclass Q of the pare...
Pythonic way to assign an instance of a subclass to a variable when a specific string is presented to the constructor of the parent class
I want to be able to create an instance of a parent class X, with a string "Q" as an extra argument. This string is to be a name being an identifier for a subclass Q of the parent class X. I want the instance of the parent class to become (or be replaced with) an instance of the subclass. I am aware that this is prob...
[ "I would solve this by using a function that encapsulates the choice of object:\nclass SpecialRule:\n \"\"\"\"\"\"\n name=\"Special Rule\"\n description=\"This is a Special Rule.\"\n @staticmethod\n def create(name=None):\n \"\"\"\"\"\"\n print \"SpecialCreate\"\n if name!=None:\...
[ 3, 3 ]
[]
[]
[ "python", "subclass", "variable_assignment" ]
stackoverflow_0003383733_python_subclass_variable_assignment.txt
Q: How to extend distutils with a simple pre uninstall script? I found Question#1321270 for post install. My main target for the moment is bdist_wininst, but i did not find anything related to uninstall... For clarification: I want to register a com server after installation and de-register it before uninstall. Exten...
How to extend distutils with a simple pre uninstall script?
I found Question#1321270 for post install. My main target for the moment is bdist_wininst, but i did not find anything related to uninstall... For clarification: I want to register a com server after installation and de-register it before uninstall. Extended answer: ars' answer seems correct, however, for the completen...
[ "The same post-install script will run at uninstall with different arguments. See the docs for more info:\n\nThis script will be run at installation time on the target system after all the files have been copied, with argv1 set to -install, and again at uninstallation time before the files are removed with argv1 s...
[ 1 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0003383801_distutils_python_setuptools.txt
Q: Zipping Collections How do you zip two sequences in Clojure? IOW, What is the Clojure equivalent of Python zip(a, b)? EDIT: I know how to define such a function. I was just wondering whether standard library provides such a function already. (I would be *very* surprised if it doesn't.) A: You can easily define f...
Zipping Collections
How do you zip two sequences in Clojure? IOW, What is the Clojure equivalent of Python zip(a, b)? EDIT: I know how to define such a function. I was just wondering whether standard library provides such a function already. (I would be *very* surprised if it doesn't.)
[ "You can easily define function like Python's zip:\n(defn zip\n [& colls]\n (apply map vector colls))\n\nIn case of (zip a b), this becomes (map vector a b)\n", "if you want the input to be lists you can define a zip function like this\n(defn zip [m] (apply map list m))\n\nand call it like this \n(zip '((1 2 3)...
[ 3, 0, 0 ]
[]
[]
[ "clojure", "python", "sequence", "zip" ]
stackoverflow_0003382688_clojure_python_sequence_zip.txt
Q: Python daemonize I would like to daemonize a python process, and now want to ask if it is good practice to have a daemon running, like a parent process and call another class which opens 10-30 threads. I'm planning on writing a monitoring script for group of servers and would like to check every server every 5 mi...
Python daemonize
I would like to daemonize a python process, and now want to ask if it is good practice to have a daemon running, like a parent process and call another class which opens 10-30 threads. I'm planning on writing a monitoring script for group of servers and would like to check every server every 5 mins, that each server i...
[ "Maybe you should use http://pypi.python.org/pypi/python-daemon\n", "You can use supervisord for this. You can configure tasks to respond to events. The events can be manually created or automatically by monitoring processes or based on regular intervals.\nIt is fully customizable and written in Python.\nExample:...
[ 8, 1 ]
[ "There's really not much to creating your own daemonize function: The source for Advanced Programming in the Unix Environment (2nd edition) is freely available: http://www.apuebook.com/src.tar.gz -- you're looking for the apue.2e/daemons/init.c file.\nThere is a small helper program that does all the work of creati...
[ -2 ]
[ "daemon", "python" ]
stackoverflow_0003383741_daemon_python.txt
Q: From a python cgi can I write to Lighttpd log file? I have a python cgi script (just python, I didn't use any framework). It's served using Lighttpd on openSUSE. I would like to redirect my logging statements (like logging.info and so on) to be included to Lighttpd log file. If this can't be done, how can I create...
From a python cgi can I write to Lighttpd log file?
I have a python cgi script (just python, I didn't use any framework). It's served using Lighttpd on openSUSE. I would like to redirect my logging statements (like logging.info and so on) to be included to Lighttpd log file. If this can't be done, how can I create my own log file?
[ "Your goal of logging to the lighttpd log file looks unlikely: http://redmine.lighttpd.net/boards/2/topics/16\nIt does seem that you could use the FastCGI interface to provide a place to write error messages.\nHere's a simple tutorial on using python's logger facility to write to your own log files: http://docs.pyt...
[ 1 ]
[]
[]
[ "cgi", "lighttpd", "logging", "python" ]
stackoverflow_0003384021_cgi_lighttpd_logging_python.txt
Q: Mercurial: Permission Denied for hgwebdir Yesterday I setup Apache to serve my Mercurial repositories and got everything working properly. I then tested pushing changes back to this repository and was presented with an error, and now that error pops up for every single operation I attempt - even just a simple GET ...
Mercurial: Permission Denied for hgwebdir
Yesterday I setup Apache to serve my Mercurial repositories and got everything working properly. I then tested pushing changes back to this repository and was presented with an error, and now that error pops up for every single operation I attempt - even just a simple GET request of the repositories! Here is the error:...
[ "This turned out to be a configuration error on my part, and rather than delete the question I'll post the resolution here in case someone has this problem in the future.\nHere was the hgweb.config I was using:\n[paths]\n/ = /var/hg/repos/*\n\n#[web]\nstyle = gitweb\nallow_archive = bz2 gz zip\nmaxchanges = 200\nal...
[ 3 ]
[]
[]
[ "apache", "mercurial", "python" ]
stackoverflow_0003383426_apache_mercurial_python.txt
Q: Storing and replaying binary network data with python I have a Python application which sends 556 bytes of data across the network at a rate of 50 Hz. The binary data is generated using struct.pack() which returns a string, which is subsequently written to a UDP socket. As well as transmitting this data, I would ...
Storing and replaying binary network data with python
I have a Python application which sends 556 bytes of data across the network at a rate of 50 Hz. The binary data is generated using struct.pack() which returns a string, which is subsequently written to a UDP socket. As well as transmitting this data, I would like to save this data to file as space-efficiently as poss...
[ "Python's logging system is intended to process human-readable strings, and it's intended to be easy to enable or disable depending on whether it's you (the developer) or someone else running your program. Don't use it for something that your application always needs to output.\nThe simplest way to store the data i...
[ 4, 1 ]
[]
[]
[ "binary_data", "python", "serialization" ]
stackoverflow_0003384319_binary_data_python_serialization.txt
Q: How to build an undo storage with limit? I want build a data structure to store limited undo buffer, take store 6 dict data for example with below pseudocode: rawdict1 = {1} buffer = [{1}] rawdict1 = {2} buffer = [{2}{1}] # {1} stored on the postion rawdict1 = {3} buffer = [{3}{2}{1}] ... rawdict1 = {...
How to build an undo storage with limit?
I want build a data structure to store limited undo buffer, take store 6 dict data for example with below pseudocode: rawdict1 = {1} buffer = [{1}] rawdict1 = {2} buffer = [{2}{1}] # {1} stored on the postion rawdict1 = {3} buffer = [{3}{2}{1}] ... rawdict1 = {5} buffer = [{5}{4}{3}{2}{1}] # max lengt...
[ "Perhaps use something like this:\nimport collections\n\nclass UndoBuffer(object):\n def __init__(self,value,max_length=5):\n self.max_length=max_length\n self._buffer=collections.deque([value],max_length)\n @property\n def data(self):\n return self._buffer[-1]\n @data.setter\n d...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "fifo", "python", "storage", "undo" ]
stackoverflow_0003384643_fifo_python_storage_undo.txt
Q: How do I track a blob using OpenCV and Python I've gotten OpenCV working with Python and I can even detect a face through my webcam. What I really want to do though, is see movement and find the point in the middle of the blob of movement. The camshift sample is close to what I want, but I don't want to have to se...
How do I track a blob using OpenCV and Python
I've gotten OpenCV working with Python and I can even detect a face through my webcam. What I really want to do though, is see movement and find the point in the middle of the blob of movement. The camshift sample is close to what I want, but I don't want to have to select which portion of the video to track. Bonus poi...
[ "Found a solution at How do I track motion using OpenCV in Python?\n" ]
[ 4 ]
[]
[]
[ "opencv", "python", "webcam" ]
stackoverflow_0003374422_opencv_python_webcam.txt
Q: Python extensions - performance I am using Boost.Python to extend python program functionality. Python scripts do a lot of calls to native modules so I am really concerned about the performance of python-to-cpp type conversion and data marshaling. I decided to try exposing methods natively through Python C API. Ma...
Python extensions - performance
I am using Boost.Python to extend python program functionality. Python scripts do a lot of calls to native modules so I am really concerned about the performance of python-to-cpp type conversion and data marshaling. I decided to try exposing methods natively through Python C API. May be somebody already tried that befo...
[ "I haven't tried Boost.Python, but I've extended Python using raw C as well as Cython. I recommend Cython; if you're careful enough you can get code with the same efficiency as raw C but with a lot less boilerplate code. \nRegarding efficiency, it's relative. It depends on what you want to do and how you do it. For...
[ 1 ]
[]
[]
[ "boost", "native", "performance", "python" ]
stackoverflow_0003384854_boost_native_performance_python.txt
Q: Python 3.2 - GIL - good/bad? Python 3.2 ALPHA is out. From the Change Log, it appears the GIL has been entirely rewritten. A few questions: Is having a GIL good or bad? (and why). Is the new GIL better? If so, how? UPDATE: I'm fairly new to Python. So all of this is new to my but I do at least understand that th...
Python 3.2 - GIL - good/bad?
Python 3.2 ALPHA is out. From the Change Log, it appears the GIL has been entirely rewritten. A few questions: Is having a GIL good or bad? (and why). Is the new GIL better? If so, how? UPDATE: I'm fairly new to Python. So all of this is new to my but I do at least understand that the existence of a GIL with CPython ...
[ "The best explanation I've seen as to why the GIL sucks is here:\nhttp://www.dabeaz.com/python/GIL.pdf\nAnd the same guy has a presentation on the new GIL here:\nhttp://www.dabeaz.com/python/NewGIL.pdf\nIf that's all that's been done it still sucks - just not as bad. Multiple threads will behave better. Multi-core ...
[ 25, 4, 1 ]
[]
[]
[ "interpreter", "locking", "multithreading", "python" ]
stackoverflow_0003384385_interpreter_locking_multithreading_python.txt
Q: rendering multipe html pages I'm working on a project and i need to use multiple html pages to interact with my code like: viewing index.html first:- path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) and then when i press the sign out bu...
rendering multipe html pages
I'm working on a project and i need to use multiple html pages to interact with my code like: viewing index.html first:- path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) and then when i press the sign out button the program should view this ...
[ "You need something like this:\nclass MainPage(webapp.RequestHandler):\n def get(self):\n path = os.path.join(os.path.dirname(__file__), 'index.html') \n self.response.out.write(template.render(path, template_values))\n\nclass SignOutPage(webapp.RequestHandler):\n def get(self):\n ...
[ 2 ]
[]
[]
[ "google_app_engine", "html", "python" ]
stackoverflow_0003385119_google_app_engine_html_python.txt
Q: Python dictionary error In the below code d_arr is an array of dictionaries def process_data(d_arr): flag2 = 0 for dictionaries in d_arr: for k in dictionaries: if ( k == "*TYPE" ): """ Here we determine the type """ if (dictionaries[k].lower() == "name"): d...
Python dictionary error
In the below code d_arr is an array of dictionaries def process_data(d_arr): flag2 = 0 for dictionaries in d_arr: for k in dictionaries: if ( k == "*TYPE" ): """ Here we determine the type """ if (dictionaries[k].lower() == "name"): dictionaries.update({"type" : ...
[ "That error is pretty informative; you can't change the size of a dictionary you are currently iterating over.\nThe solution is to get the keys all at once and iterate over them:\n# Do this\nfor k in dictionaries.keys():\n\n# Not this\nfor k in dictionaries:\n\n", "It is, indeed, forbidden. Moreover, you don't r...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003385219_python.txt
Q: Confused how to import modules in python If I want to use a 3rd party module like a python s3 module (boto http://boto.s3.amazonaws.com/index.html) or http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134. Once I download the .py files, what do I do? Where does the python interpreter look when I...
Confused how to import modules in python
If I want to use a 3rd party module like a python s3 module (boto http://boto.s3.amazonaws.com/index.html) or http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134. Once I download the .py files, what do I do? Where does the python interpreter look when I import a module? Is there a 'lightweight' way...
[ "Look in the import statement reference, a long and involved description.\nThe simple method is to include the module's location in sys.path.\nI'm quoting the starting paragraph only:\n\nOnce the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), sea...
[ 1, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003385204_module_python.txt
Q: How to wrap a python dict? I want to implement a class that will wrap -- not subclass -- the python dict object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read. Supposing I ...
How to wrap a python dict?
I want to implement a class that will wrap -- not subclass -- the python dict object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read. Supposing I was to create an object to act l...
[ "You can subclass the ABC (abstract base class) collections.Mapping (or collections.MutableMapping if you also want to allow code using your instances to alter the simulated/wrapped dictionary, e.g. by indexed assignment, pop, etc).\nIf you do so, then, as the docs I pointed to imply somewhat indirectly, the method...
[ 13, 3, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003385269_dictionary_python.txt
Q: Private Variables and Methods in Python Possible Duplicate: The meaning of a single- and a double-underscore before an object name in Python Which should I use _foo (an underscore) or __bar (double underscore) for private members and methods in Python? A: Please note that there is no such thing as "private met...
Private Variables and Methods in Python
Possible Duplicate: The meaning of a single- and a double-underscore before an object name in Python Which should I use _foo (an underscore) or __bar (double underscore) for private members and methods in Python?
[ "Please note that there is no such thing as \"private method\" in Python. Double underscore is just name mangling:\n>>> class A(object):\n... def __foo(self):\n... pass\n... \n>>> a = A()\n>>> A.__dict__.keys()\n['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']\n>>> a._A__foo()\n\nSo there...
[ 71, 42, 10 ]
[ "Because thats coding convention.\nSee here for more.\n" ]
[ -4 ]
[ "double_underscore", "private", "private_members", "private_methods", "python" ]
stackoverflow_0003385317_double_underscore_private_private_members_private_methods_python.txt
Q: Programming thunderbird Email Client? Anyone has C#/Ruby/Python/Java or Perl scripts to get all the emails in a folder in Thunderbird client and download all the attachments? I have more than 200 resumes as attachment kept in Resumes folder of thunderbird and I need to download the attachment and categories them. ...
Programming thunderbird Email Client?
Anyone has C#/Ruby/Python/Java or Perl scripts to get all the emails in a folder in Thunderbird client and download all the attachments? I have more than 200 resumes as attachment kept in Resumes folder of thunderbird and I need to download the attachment and categories them. Any API reference to program thunderbird wo...
[ "If you are happy using existing tools, instead of writing your own, you could give the Thunderbird Add-on AttachmentExtractor a try.\n", "Give this a try:\nHow To Bulk Export Thunderbird Email & Attachments\nhttp://blog.taragana.com/index.php/archive/how-to-bulk-export-thunderbird-email-attachments/\n" ]
[ 0, 0 ]
[]
[]
[ "java", "python", "ruby", "scripting", "thunderbird" ]
stackoverflow_0003385209_java_python_ruby_scripting_thunderbird.txt
Q: IDLE processes numerical input in a weird way (python 2.6) If you simply type an integer after the >>> prompt they give you in the IDLE interpreter, most of the time it'll simply bounce the number back at you. >>> 3 3 >>> 8 8 >>> 10 10 Start the nubmer off with a 0 however, and some interesting errors happen. >...
IDLE processes numerical input in a weird way (python 2.6)
If you simply type an integer after the >>> prompt they give you in the IDLE interpreter, most of the time it'll simply bounce the number back at you. >>> 3 3 >>> 8 8 >>> 10 10 Start the nubmer off with a 0 however, and some interesting errors happen. >>> 010 8 >>> 020 16
[ "In Python 2, an integer literal starting with 0 is considered octal, i.e. in base 8. And obviously, 10 oct == 8 dec (or generally, 10 in base b == b base 10). Likewise, 12 oct == 10 dec, and so on.\n" ]
[ 11 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003385646_python_syntax.txt
Q: how to access the list in different function I have made a class in which there are 3 functions. def maxvalue def min value def getAction In the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction function so that I can reverse the list and then take out the fi...
how to access the list in different function
I have made a class in which there are 3 functions. def maxvalue def min value def getAction In the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction function so that I can reverse the list and then take out the first entry from it. How can do i that?? def getAct...
[ "Either define the list as a class attribute or as an instance attribute, then all the methods will be able to access it\nIf you'd like to post your class, it'll be easier to show you what I mean\nHere is an example making it a class attribute\nclass Foo(object):\n list_of_actions = ['action1', 'action2']\n d...
[ 1, 1, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0003385796_function_list_python.txt
Q: Reading RSS Feeds: What Aggregators Do That I'm Not I drop the following feed into Google Reader, and it update normally. http://www.indeed.ca/rss?q=&l=Hamilton%2C+ON However, when I use any of a number of approaches suggested thither and yon on the 'net that simply involve reading from this source and parsing the...
Reading RSS Feeds: What Aggregators Do That I'm Not
I drop the following feed into Google Reader, and it update normally. http://www.indeed.ca/rss?q=&l=Hamilton%2C+ON However, when I use any of a number of approaches suggested thither and yon on the 'net that simply involve reading from this source and parsing the XML I receive the same 20 items. What is Google Reader ...
[ "RSS aggregators \"poll\" the sources, i.e., they repeat the HTTP query periodically on each source, and check if anything new appears in the results. That's unfortunate, as polling always is, as it wastes resources in an unending series of \"are we there yet?\" questions (kind of like taking a toddler along in a ...
[ 3, 0 ]
[]
[]
[ "aggregator", "python", "rss" ]
stackoverflow_0003382942_aggregator_python_rss.txt
Q: Including Flash content inline in a custom Weblog? I'm trying to think of a way to place Flash content into a blog post so that it appears inline between paragraphs. I'm writing a custom weblog application in Django (still learning) and I'll be using SWFObject for the embedding. The blog is for me only so the bac...
Including Flash content inline in a custom Weblog?
I'm trying to think of a way to place Flash content into a blog post so that it appears inline between paragraphs. I'm writing a custom weblog application in Django (still learning) and I'll be using SWFObject for the embedding. The blog is for me only so the back-end isn't too fancy. I'm simply using Django's built i...
[ "You might want to look into OEmbed, specifically the django-oembed project.\n" ]
[ 1 ]
[]
[]
[ "blogs", "django", "flash", "python" ]
stackoverflow_0003382170_blogs_django_flash_python.txt
Q: List of lists and "Too many values to unpack" I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code: for index, item in outputList1: outputLi...
List of lists and "Too many values to unpack"
I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code: for index, item in outputList1: outputList2 = outputList2.append(item[6:].extend(outputList...
[ "the for statement iterates over an iterable -- in the case of a list, it iterates over the contents, one by one, so in each iteration, one value is available.\nWhen using for index, item in list: you are trying to unpack one value into two variables. This would work with for key, value in dict.items(): which itera...
[ 25, 11 ]
[]
[]
[ "python" ]
stackoverflow_0003386107_python.txt
Q: Python if statement "SyntaxError: invalid syntax" Trying to execute someone's code, getting a syntax error. No idea why :( def GetParsers( self, systags ): childparsers = reduce( lambda a,b : a+b, [[]] + [ plugin.GetParsers( systags ) for plugin in self.plugins ] ) parsers = [ p for plist in [ self.parsers...
Python if statement "SyntaxError: invalid syntax"
Trying to execute someone's code, getting a syntax error. No idea why :( def GetParsers( self, systags ): childparsers = reduce( lambda a,b : a+b, [[]] + [ plugin.GetParsers( systags ) for plugin in self.plugins ] ) parsers = [ p for plist in [ self.parsers[t] for t in systags if self.parsers.has_key(t) ] for p...
[ "Conditional expressions were added in 2.5 (source) - you have 2.2. So no conditional expressions for you, I fear. They just don't exist yet in that version. Definitively update (not only for this little change, there are literally thousands of them since '06) if you can.\n", "You need to upgrade your Python inst...
[ 5, 4, 1 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0003385539_python_syntax_error.txt
Q: A scalable solution for server side push? I would like to implement a mechanism which will provide a RESTful API that allows a client to register interest in a subject with a sever, and receive asynchronous notifications from the server after the interest is registered. In enterprise (messaging) architecture, this...
A scalable solution for server side push?
I would like to implement a mechanism which will provide a RESTful API that allows a client to register interest in a subject with a sever, and receive asynchronous notifications from the server after the interest is registered. In enterprise (messaging) architecture, this is known as publish/subscribe 'pattern'. With ...
[ "Have a look at the pubsubhubbub protocol: http://en.wikipedia.org/wiki/PubSubHubbub\nHere is the source of the project: http://code.google.com/p/pubsubhubbub/\n", "If you know in advance you'll have a lot of subscribers (people/applications) that want notifications on a certain subject while on other hand you'll...
[ 3, 2, 0 ]
[]
[]
[ "linux", "php", "publish_subscribe", "python", "server_push" ]
stackoverflow_0003377951_linux_php_publish_subscribe_python_server_push.txt
Q: list query, functions in function i have a function: I need to first reverse the list and then take an entry from it. Earlier, I was making the 3 functions but now I am defining the main function and the other 2 functions in it. A: Your code is very unpythonic. Remember Python is not C. The semicolon i...
list query, functions in function
i have a function: I need to first reverse the list and then take an entry from it. Earlier, I was making the 3 functions but now I am defining the main function and the other 2 functions in it.
[ "Your code is very unpythonic. Remember Python is not C. \n\nThe semicolon is optional.\nThe parenthesis in an if is optional. \nTo get the last element of list a, use a[-1], not reversing a then get its first element.\nUse the built-in functions! Your modified maxagent can be written simply using the max function:...
[ 4 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0003386211_function_list_python.txt
Q: A django problem that doesn't show up in runserver In runserver, I can view my website no problems. (viewing it through lynx on the same machine) But when I view the same thing through apache, (passenger) I get an error like the following: Could not import PROJ.APP.views Error was: No module named PROJ.views It l...
A django problem that doesn't show up in runserver
In runserver, I can view my website no problems. (viewing it through lynx on the same machine) But when I view the same thing through apache, (passenger) I get an error like the following: Could not import PROJ.APP.views Error was: No module named PROJ.views It looks like a problem with the urlconf, but again that is ...
[ "SOLVED\nIt was a problem of relative imports. In some files I was importing APP.models instead of PROJ.APP.models.\nThe error wasn't giving any indication of which file was causing the problem. Once I changed all of them it was fine. Thanks, guys.\n" ]
[ 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003386654_django_django_urls_python.txt
Q: How to mimic Python set with django ORM? I am working on a membership application. I would like to make a membership reminder. (member during a period of time which is not member for another period of time). Currently, I am using set for making this calculation. See the code below. class Member(models.Model): ...
How to mimic Python set with django ORM?
I am working on a membership application. I would like to make a membership reminder. (member during a period of time which is not member for another period of time). Currently, I am using set for making this calculation. See the code below. class Member(models.Model): ... class Membership(models.Model): memb...
[ "Isn't it simply negating the second expression and putting it in the same filter? So you have something like !(a&b), which equals to (!a)|(!b), in this case:\nresult = Member.objects.filter(membership__start_date__lte=dt1, membership__end_date__gte=dt1, ~Q(membership__start_date__lte=dt2) | ~Q(membership__end_date...
[ 6, 3, 1 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0003386599_django_django_orm_python.txt
Q: In Sqlalchemy, if i add an object using session.add() and flush it, session.query() does not give that object, why? While using SQLAlchemy, i add a object to a session using session.add(objname), then either explicitly flush it using session.flush or enable autoflush=True while creating the engine itself. Now in t...
In Sqlalchemy, if i add an object using session.add() and flush it, session.query() does not give that object, why?
While using SQLAlchemy, i add a object to a session using session.add(objname), then either explicitly flush it using session.flush or enable autoflush=True while creating the engine itself. Now in the session, if want to return that object via session.query(classname).all(), i cannot retrieve it. Why is that so? or is...
[ "I can't reproduce your issue. Please provide sample code that I can run to reproduce it.\nHere's code that does what you describe, but behaves as one would expect:\nfrom sqlalchemy import Column, Integer, Unicode, create_engine\nfrom sqlalchemy.orm import create_session\nfrom sqlalchemy.ext.declarative import decl...
[ 7 ]
[]
[]
[ "orm", "python", "sql", "sqlalchemy" ]
stackoverflow_0003386572_orm_python_sql_sqlalchemy.txt
Q: Made Django's auth track on emails, how to relate username field to email? My original though was to simply put the email address into both username and email fields when creating accounts, this doesn't work as Django limits the username field to 30 characters which may not be enough for email addresses. My secon...
Made Django's auth track on emails, how to relate username field to email?
My original though was to simply put the email address into both username and email fields when creating accounts, this doesn't work as Django limits the username field to 30 characters which may not be enough for email addresses. My second thought was to md5 the email address, put the hash into username, and that wou...
[ "We developed a django application, which stores emails as usernames. Django builtin username model is restricted to 30 chars, which was good for 90%. \nTo support longer usernames, without altering the django source, we used a tiny additional application, called longer_username:\nfrom django.db.models.signals impo...
[ 4 ]
[]
[]
[ "authentication", "database", "django", "python" ]
stackoverflow_0003385944_authentication_database_django_python.txt
Q: How to bundle a Gnome applet with distutils? I'm trying to write a Gnome applet in Python. In fact, I've written the app and I'm stuck when it comes to packaging it. I started by looking into distutils. The problem I ran into right away was that when specifying py_modules, an extension of .py is expected. However,...
How to bundle a Gnome applet with distutils?
I'm trying to write a Gnome applet in Python. In fact, I've written the app and I'm stuck when it comes to packaging it. I started by looking into distutils. The problem I ran into right away was that when specifying py_modules, an extension of .py is expected. However, Gnome applets are basically shell scripts. (That ...
[ "Scripts should be installed with the script option to distutils.core.setup() as described in distutils documentation. On the other hand, py_modules is used to list individual modules, and they must have .py extension as you described.\nAlso, if you want to add additional files, the data_files option lets you speci...
[ 0 ]
[]
[]
[ "applet", "distutils", "gnome", "python" ]
stackoverflow_0003384012_applet_distutils_gnome_python.txt
Q: Using Python to send/receive text from GUI program I'm using PyWin32's win32process.CreateProcess to start up a GUI program that has functionality I want to use in a Python class. I want to do the following from Python with this GUI: sent text to individual windows within the GUI (which seem to change identifiers...
Using Python to send/receive text from GUI program
I'm using PyWin32's win32process.CreateProcess to start up a GUI program that has functionality I want to use in a Python class. I want to do the following from Python with this GUI: sent text to individual windows within the GUI (which seem to change identifiers every time I create the process if WinSpy++ is to be be...
[ "What you want to do is complicated and I'm not sure you can accomplish that with Python. I can only post some pointers, but can't guarantee that it's right direction.\nAs for sending text to individual windows - there is SendMessage function - you'd probably need to send your data as keystroke messages to desired ...
[ 1 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0003387263_python_pywin32_windows.txt
Q: Writing blob from SQLite to file using Python A clueless Python newbie needs help. I muddled through creating a simple script that inserts a binary file into a blog field in a SQLite database: import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor() input_note = raw_input(_(u'Note: ')) input...
Writing blob from SQLite to file using Python
A clueless Python newbie needs help. I muddled through creating a simple script that inserts a binary file into a blog field in a SQLite database: import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor() input_note = raw_input(_(u'Note: ')) input_type = 'A' input_file = raw_input(_(u'Enter pa...
[ "Here's a script that does read a file, put it in the database, read it from database and then write it to another file:\nimport sqlite3\nconn = sqlite3.connect('database.db')\ncursor = conn.cursor()\n\nwith open(\"...\", \"rb\") as input_file:\n ablob = input_file.read()\n cursor.execute(\"INSERT INTO notes ...
[ 37 ]
[]
[]
[ "binary", "blob", "python", "sql", "sqlite" ]
stackoverflow_0003379166_binary_blob_python_sql_sqlite.txt
Q: How do I use context_instance in my template Django newbie here, I'm using render_to_response('example.html', { 'error_message': error_message, }, context_instance=RequestContext(request)) How do I use the request in the template? (e.g. the request.host etc.) A: The whole point of the context p...
How do I use context_instance in my template
Django newbie here, I'm using render_to_response('example.html', { 'error_message': error_message, }, context_instance=RequestContext(request)) How do I use the request in the template? (e.g. the request.host etc.)
[ "The whole point of the context processors is that they automatically add the elements to the context. So you can just use {{ request.host }} or whatever directly in the template.\nEdit after comment No, this has nothing to do with generic views. Generic views act in exactly the same way as your own views that use ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003387636_django_python.txt
Q: How to convince boss to substitute Java/Netbeans Platform for Python/PyQt? I'm working for small company, which operates in the automation industry. The boss hired me because he wants to sell/give some desktop applications to his current costumers. He imposes me to use the Netbeans Platform (a generic desktop appl...
How to convince boss to substitute Java/Netbeans Platform for Python/PyQt?
I'm working for small company, which operates in the automation industry. The boss hired me because he wants to sell/give some desktop applications to his current costumers. He imposes me to use the Netbeans Platform (a generic desktop application framework). A software engineer friend of his advised him to choose this...
[ "If your selling skills are not working in discussion format I highly suggest that you document it. Some managers/bosses really respond well to this.\nMake a matrix of all the metrics that you yourself use to grade the two frameworks (I leave the level of objectivity to you there: for example if objective it should...
[ 12, 8, 5, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "java", "netbeans", "pyqt", "python" ]
stackoverflow_0003386377_java_netbeans_pyqt_python.txt
Q: How can I fetch emails via POP or IMAP through a proxy? Neither poplib or imaplib seem to offer proxy support and I couldn't find much info about it despite my google-fu attempts. I'm using python to fetch emails from various imap/pop enabled servers and need to be able to do it through proxies. Ideally, I'd like ...
How can I fetch emails via POP or IMAP through a proxy?
Neither poplib or imaplib seem to offer proxy support and I couldn't find much info about it despite my google-fu attempts. I'm using python to fetch emails from various imap/pop enabled servers and need to be able to do it through proxies. Ideally, I'd like to be able to do it in python directly but using a wrapper (e...
[ "You don't need to dirtily hack imaplib. You could try using the SocksiPy package, which supports socks4, socks5 and http proxy (connect):\nSomething like this, obviously you'd want to handle the setproxy options better, via extra arguments to a custom __init__ method, etc. \nfrom imaplib import IMAP4, IMAP4_SSL, I...
[ 14, 7, 2 ]
[]
[]
[ "imap", "pop3", "proxy", "python" ]
stackoverflow_0003386724_imap_pop3_proxy_python.txt
Q: Library for electrical network simulation I'm searching for a free and open source library for electrical network simulation. In (Per preference order) : Python, Ruby, Javascript, PHP, C++ (with Qt if it exist) or bash (ahah). Do you know one ? A: http://www.thedigitalmachine.net/eispice.html
Library for electrical network simulation
I'm searching for a free and open source library for electrical network simulation. In (Per preference order) : Python, Ruby, Javascript, PHP, C++ (with Qt if it exist) or bash (ahah). Do you know one ?
[ "http://www.thedigitalmachine.net/eispice.html\n" ]
[ 3 ]
[]
[]
[ "c++", "python", "ruby", "simulation" ]
stackoverflow_0003387913_c++_python_ruby_simulation.txt
Q: How to do a group by/count(*) pr year, month and day in django based on a datetime database field? I have a table describing files with a datetime field. I want to somehow create a report that gives me the number of files grouped by each year, number of files grouped by each year and month and number of files grou...
How to do a group by/count(*) pr year, month and day in django based on a datetime database field?
I have a table describing files with a datetime field. I want to somehow create a report that gives me the number of files grouped by each year, number of files grouped by each year and month and number of files grouped by each year, month and day. I just want records where count(*) > 0. Preferably using the ORM in dja...
[ "Normally I work on Oracle but a quick google search showed that this should also work for Postgres. For the minutes you could do like this\nselect to_char(yourtimestamp,'yyyymmdd hh24:mi'), count(*)\nfrom yourtable\ngroup by to_char(yourtimestamp,'yyyymmdd hh24:mi') \norder by to_char(yourtimestamp,'yyyymmdd hh24:...
[ 0, 0 ]
[]
[]
[ "aggregate", "datetime", "django", "python", "sql" ]
stackoverflow_0003387680_aggregate_datetime_django_python_sql.txt
Q: Django, Python, Mysql This is the settings.py file for python. I set mysql up via macports (mysql5 & mysqldb) The problem is that I am unsure if I have settings.py configuration correct before I sync the db. Should the PORT be left blank? I believe it should. I know on my Mamp install I have it set to 3306. Thanks...
Django, Python, Mysql
This is the settings.py file for python. I set mysql up via macports (mysql5 & mysqldb) The problem is that I am unsure if I have settings.py configuration correct before I sync the db. Should the PORT be left blank? I believe it should. I know on my Mamp install I have it set to 3306. Thanks.... DATABASES = { 'def...
[ "3306 is the default, so that should be fine.\nWhy do you have the host set to that? I haven't used MySQL on a Mac, but on Linux the host is 'localhost'.\nThe 'invalid syntax' is because you do't have a comma after the host string - wait, after any of the strings but the last one - and that is invalid syntax for P...
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003388071_django_mysql_python.txt
Q: ModelAdmin thread-safety/caching issues Ultimately, my goal is to extend Django's ModelAdmin to provide field-level permissions—that is, given properties of the request object and values of the fields of the object being edited, I would like to control whether or not the fields/inlines are visible to the user. I u...
ModelAdmin thread-safety/caching issues
Ultimately, my goal is to extend Django's ModelAdmin to provide field-level permissions—that is, given properties of the request object and values of the fields of the object being edited, I would like to control whether or not the fields/inlines are visible to the user. I ultimately accomplished this by adding a can_v...
[ "I'm confused about why you think ModelAdmin should be a new instance on each request. The admin objects are instantiated by the admin.site.register(Model) calls in each admin.py, which in turn is called from admin.autodiscover() in urls.py. In other words, this happens on process startup. Given the dynamic multi-p...
[ 3 ]
[]
[]
[ "django", "django_admin", "django_permissions", "python" ]
stackoverflow_0003388111_django_django_admin_django_permissions_python.txt
Q: Python - difference between os.access and os.path.exists? def CreateDirectory(pathName): if not os.access(pathName, os.F_OK): os.makedirs(pathName) versus: def CreateDirectory(pathName): if not os.path.exists(pathName): os.makedirs(pathName) I understand that os.access is a bit more flexi...
Python - difference between os.access and os.path.exists?
def CreateDirectory(pathName): if not os.access(pathName, os.F_OK): os.makedirs(pathName) versus: def CreateDirectory(pathName): if not os.path.exists(pathName): os.makedirs(pathName) I understand that os.access is a bit more flexible since you can check for RWE attributes as well as path exis...
[ "Better to just catch the exception rather than try to prevent it. There are a zillion reasons that makedirs can fail\ndef CreateDirectory(pathName):\n try:\n os.makedirs(pathName)\n except OSError, e:\n # could be that the directory already exists\n # could be permission error\n #...
[ 13, 4 ]
[]
[]
[ "module", "operating_system", "python" ]
stackoverflow_0003388223_module_operating_system_python.txt
Q: logout from command prompt to uploading application on google app I am uploading google app engine application with the help of appcfg.py command from command prompt in windows. But after one login I want to upload another application from the same command prompt but i cannot because this second application has n...
logout from command prompt to uploading application on google app
I am uploading google app engine application with the help of appcfg.py command from command prompt in windows. But after one login I want to upload another application from the same command prompt but i cannot because this second application has no rights with the current login so i want to logout from this session o...
[ "You can run appcfg.py with --no_cookies to tell it not to store authentication cookies, or -e EMAIL to specify an email address that differs from the one in the current cookie.\n" ]
[ 3 ]
[]
[]
[ "command_prompt", "google_app_engine", "python" ]
stackoverflow_0003387605_command_prompt_google_app_engine_python.txt
Q: twitter connection needs to be closed? i developed an aplication built on twitter api , but i get erorrs like a mesage that i've parsed and deleted to be parsed again at the next execution , could that be because i left the twitter connection opened or is just a fault of the twitter API. I also tried to del...
twitter connection needs to be closed?
i developed an aplication built on twitter api , but i get erorrs like a mesage that i've parsed and deleted to be parsed again at the next execution , could that be because i left the twitter connection opened or is just a fault of the twitter API. I also tried to delete all direct messages because it seemed to...
[ "Twitter's API is over HTTP, which is a stateless protocol. you don't really need to close the connection, since connections made and closed for each request\n" ]
[ 2 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003385990_python_twitter.txt
Q: Does gzip work on the development server? Does gzip work on the python development server for appengine? How can I test this in the future? Note: I've used Firebug to look at my HTTP requests from the browser, and I see that Accept-Encoding is set to "gzip,deflate". A: to see if the server responds with gzip e...
Does gzip work on the development server?
Does gzip work on the python development server for appengine? How can I test this in the future? Note: I've used Firebug to look at my HTTP requests from the browser, and I see that Accept-Encoding is set to "gzip,deflate".
[ "to see if the server responds with gzip encoded headers look for \n\nContent-Encoding:gzip\n\nin the response headers\n€: found this in their faq\n\nGoogle App Engine does its best to serve gzipped content to browsers that support it. Taking advantage of this scheme is automatic and requires no modifications to ap...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003388458_google_app_engine_python.txt
Q: Extended call-syntax: Passing parameters I have a function that looks like this: def getColumn(self, name, type, **args): Now I would like to have a function def getColumns(self, columns) where I can pass a tuple that contains a tuple, where each entry in that tuple represents the arguments to be passed go getCo...
Extended call-syntax: Passing parameters
I have a function that looks like this: def getColumn(self, name, type, **args): Now I would like to have a function def getColumns(self, columns) where I can pass a tuple that contains a tuple, where each entry in that tuple represents the arguments to be passed go getColumn. However, I'd like not to have to use nam...
[ "Something like this?\ncolumn_data = (('myName', 'myType', {'other': 'myOther'}),\n ('myName2', 'myType2', {'other2': 'myOther2'}))\n\ndef getColumn(self,name,type,**rest):\n pass\n\ndef getColumns(self,columns):\n return [self.getColumn(name, type, **rest) for name, type, rest in columns]\n\nYo...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003388592_python.txt
Q: What purpose does a python backend serve? I am primarily a PHP developer, and I have been browsing the source code of a few open-source applications recently(Mozilla Bespin in particular), to find that some of them use a Python "back-end." I was just wondering what the purpose of this back-end is. I am assuming ...
What purpose does a python backend serve?
I am primarily a PHP developer, and I have been browsing the source code of a few open-source applications recently(Mozilla Bespin in particular), to find that some of them use a Python "back-end." I was just wondering what the purpose of this back-end is. I am assuming it is the same thing as the model in an MVC fra...
[ "A \"Python backend\" is simply server-side software written in Python, no different in general terms than server-side software written in PHP. It does all the same things, just with a different programming language.\n", "It looks like Bespin uses Python in the same way it would use PHP, if the autors chose PHP ...
[ 2, 1 ]
[]
[]
[ "backend", "php", "python" ]
stackoverflow_0003388829_backend_php_python.txt
Q: pyAA with py2exe Is anyone able to get pyAA working with py2exe? pyAA can be downloaded here. I have trying to do this for the last 2 days and I am unable to reach a solution till now. The example files are like given below: hello.py import pyAA print "Hello, World" setup.py from distutils.core import setup impo...
pyAA with py2exe
Is anyone able to get pyAA working with py2exe? pyAA can be downloaded here. I have trying to do this for the last 2 days and I am unable to reach a solution till now. The example files are like given below: hello.py import pyAA print "Hello, World" setup.py from distutils.core import setup import py2exe setup(conso...
[ "This king of thing seems to be a common problem with py2exe. Maybe try using another installer such as PyInstaller.\n", "When I install pyAA and run depends on _pyAAc.pyd, it tells me I'm missing IESHIMS.DLL, though that might be because I'm on Windows 7.\n", "_pyAAc.pyd is a DLL, I think those have to be loa...
[ 2, 0, 0, 0 ]
[]
[]
[ "automation", "py2exe", "python" ]
stackoverflow_0003362698_automation_py2exe_python.txt
Q: Python class variables or class variables in general From Dive into Python: Class attributes are available both through direct reference to the class and through any instance of the class. Class attributes can be used as class-level constants, but they are not really constants. You can also change them. So I...
Python class variables or class variables in general
From Dive into Python: Class attributes are available both through direct reference to the class and through any instance of the class. Class attributes can be used as class-level constants, but they are not really constants. You can also change them. So I type this into IDLE: IDLE 2.6.5 >>> class c: ...
[ "Because ints are immutable in python\nv.counter += 1\n\nrebinds v.counter to a new int object. The rebinding creates an instance attribute that masks the class attribute\nYou can see this happening if you look at the id() of v.counter\n>>> id(v.counter)\n149265780\n>>> v.counter+=1\n>>> id(v.counter)\n149265768\n\...
[ 8, 0, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003389148_oop_python.txt
Q: Importing from module with the same name as executable file in Python I have an executable file, named, for example, resource.py. It is disposed in the folder named resource. Renaming file or folder is objectionable - it is old product and users accustomed to use such naming. At old version it was under another pr...
Importing from module with the same name as executable file in Python
I have an executable file, named, for example, resource.py. It is disposed in the folder named resource. Renaming file or folder is objectionable - it is old product and users accustomed to use such naming. At old version it was under another project, so imports to it sound like import main_product.resource.<..>. Now I...
[ "Use imp.find_module() and imp.load_module()\nfind_module lets you specify your own path to search\n" ]
[ 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003389313_import_python.txt
Q: Help removing items from a text file using python After implementing some of the solutions in my previous question, I've come up with the following solution: reader = open('C://text.txt') writer = open('C://nona.txt', 'w') counter = 1 names, nums = [], [] row = reader.read().split(' ') x = len(row)/2 for ...
Help removing items from a text file using python
After implementing some of the solutions in my previous question, I've come up with the following solution: reader = open('C://text.txt') writer = open('C://nona.txt', 'w') counter = 1 names, nums = [], [] row = reader.read().split(' ') x = len(row)/2 for (a, b) in [(c, d) for c, d in zip(row[:x], row[x:]) if ...
[ "What you should do is break your file up into two separate files. Your logic should do something like this:\n\nOpen data file\nopen name file\nread next data\nis it name? see 5. Otherwise see 6\nwrite name to name file, see 3\nis it number or na? close name file and open number file\nread next data\nis it number o...
[ 1, 0 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0003389260_memory_python.txt
Q: How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output? I am writing a simple http server as part of my project. Below is a skeleton of my script: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyHanlder(BaseHTTPRequestHandler): def do_GET(self): self.send_resp...
How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output?
I am writing a simple http server as part of my project. Below is a skeleton of my script: from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class MyHanlder(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_...
[ "This will probably do it:\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\n\nclass MyHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write('<html><body><p>O...
[ 149 ]
[]
[]
[ "basehttpserver", "httpserver", "python" ]
stackoverflow_0003389305_basehttpserver_httpserver_python.txt
Q: Nose: Capture script output as well as test output If I put any print statements at the top of my module, not inside any class/function, nothing gets printed while running my test through nose. import os print 'hi' #---------------------------------------------------------------------- def make_shapes(canvas): ...
Nose: Capture script output as well as test output
If I put any print statements at the top of my module, not inside any class/function, nothing gets printed while running my test through nose. import os print 'hi' #---------------------------------------------------------------------- def make_shapes(canvas): """ Generates shapes. Needs a Canvas instance to a...
[ "Not sure if this is the problem, but you can run nosetests with the -s argument to prevent capturing of stdout.\n" ]
[ 6 ]
[]
[]
[ "nose", "nosetests", "python" ]
stackoverflow_0003388981_nose_nosetests_python.txt
Q: What's wrong with the "or" in my "if" statement? I've tried Google, but I can't find the answer to this simple question. I hate myself for not being able to figure this out, but here we go. How do I write an if statement with or in it? For example: if raw_input=="dog" or "cat" or "small bird": print "You can h...
What's wrong with the "or" in my "if" statement?
I've tried Google, but I can't find the answer to this simple question. I hate myself for not being able to figure this out, but here we go. How do I write an if statement with or in it? For example: if raw_input=="dog" or "cat" or "small bird": print "You can have this animal in your house" else: print "I'm af...
[ "You can put the allowed animals into a tuple then use in to search for a match\nif raw_input() in (\"dog\", \"cat\", \"small bird\"):\n print \"You can have this animal in your house\"\nelse:\n print \"I'm afraid you can't have this animal in your house.\"\n\nYou can also use a set here, but I doubt it would...
[ 17, 11, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003388788_python.txt
Q: advice on storing 3rd party modules on my computer How do you guys go about storing your python modules locally? And how do you then go about referencing them in your python scripts? Should I do this? /home/python/modules And then create a sub-directory for each module, like say the amazon s3 module: /home/pytho...
advice on storing 3rd party modules on my computer
How do you guys go about storing your python modules locally? And how do you then go about referencing them in your python scripts? Should I do this? /home/python/modules And then create a sub-directory for each module, like say the amazon s3 module: /home/python/modules/amazon-s3/s3.py Now I have to somehow tell py...
[ "I usually store my modules in /usr/local/lib/python for the whole system, and /home/user/lib/python for the user. That's if they weren't installed via the system package manager. If they were a .deb or .rpm or whatever, they'll probably be placed in /usr/lib/python, as per the FHS standard, which specifies where...
[ 2, 1, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003389817_module_python.txt
Q: Stop module loading I'd like to stop the loading of a module if some modules dependencies arent on machine, how can i do that? try: import lxml except: print "This module requires lxml" # WHAT SHOULD I PUT HERE TO STOP MODULE LOADING? class foo: pass A: Raise the exception, or raise a new one: t...
Stop module loading
I'd like to stop the loading of a module if some modules dependencies arent on machine, how can i do that? try: import lxml except: print "This module requires lxml" # WHAT SHOULD I PUT HERE TO STOP MODULE LOADING? class foo: pass
[ "Raise the exception, or raise a new one:\ntry:\n import lxml\nexcept:\n raise SomeError('This module requires lxml')\n\nIf you want to stop the interpreter entirely, use exit() to terminate the program.\n", "To stop the whole python interpreter you can use sys.exit()\n" ]
[ 1, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003390299_module_python.txt
Q: Reading from file I am a beginner and just started learning Python couple days ago (yay!) so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines) def output(): xf=open("data.txt", "r") print xf print("opened, printing now") ...
Reading from file
I am a beginner and just started learning Python couple days ago (yay!) so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines) def output(): xf=open("data.txt", "r") print xf print("opened, printing now") for line in xf: ...
[ "You don't use line, try:\nwith open('data.txt') as f:\n for line in f:\n print line\n\n", "This should print out each number on its own line, like you want, in a lot less code, and more readable.\ndef output():\n f = open('data.txt', 'r').read()\n print f\n\n", "When you used for line in xf: yo...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003390334_file_io_python.txt
Q: Naming practice for objects of a class in Python I have this weird problem as to how to name objects of a class. For example, consider the class: >>> class DoSomething: pass What should I call the object of this class? do_something or what? Since I came out of the learning stage, I used to use x, y or z ...
Naming practice for objects of a class in Python
I have this weird problem as to how to name objects of a class. For example, consider the class: >>> class DoSomething: pass What should I call the object of this class? do_something or what? Since I came out of the learning stage, I used to use x, y or z or whatever came to my mind. But now since I am learni...
[ "Name it something representative of what it's actually being used for. For instance:\nclass Cereal:\n def eat(self):\n print 'yum'\n\nbreakfast = Cereal()\nbreakfast.eat()\n\nor\nclass User:\n def __init__(self, userid):\n # ...\n\nadmin_user = User(ADMIN_ID)\n\n", "You should name it after w...
[ 4, 2, 0 ]
[]
[]
[ "naming_conventions", "oop", "python" ]
stackoverflow_0003390220_naming_conventions_oop_python.txt
Q: help sorting a dictionary into another dictionary I have a dictionary (index2) of 3-item lists, organized by key from 0-150 or so. I need to sort it into another dictionary, with the following constraints: 1.) all items attached to one key must stay together in the second dictionary 2.) length of items in the seco...
help sorting a dictionary into another dictionary
I have a dictionary (index2) of 3-item lists, organized by key from 0-150 or so. I need to sort it into another dictionary, with the following constraints: 1.) all items attached to one key must stay together in the second dictionary 2.) length of items in the second dictionary must all be the same. To help with this o...
[ "Your problem description isn't really clear, and non-working code rarely helps to clarify, but I suspect that this line is your problem: elif len(dict[a]) < length.\n" ]
[ 0 ]
[]
[]
[ "dictionary", "iteration", "python" ]
stackoverflow_0003390469_dictionary_iteration_python.txt
Q: Python - Hashlib MD5 differs between linux/windows I have a python app in which I am creating packages in windows to be used and later compared in a linux python app. I am creating an md5 for a file in windows to be checked later in linux. The problem is that the same code on the same file gives different Md5 ha...
Python - Hashlib MD5 differs between linux/windows
I have a python app in which I am creating packages in windows to be used and later compared in a linux python app. I am creating an md5 for a file in windows to be checked later in linux. The problem is that the same code on the same file gives different Md5 hash results in each environment. Below is the method I u...
[ "Change open(filePath) to open(filePath, 'rb'), where the b is for binary mode. You're currently opening in text mode, which can cause portability issues.\n", "check if the two files use the same encoding and lineendings\n" ]
[ 24, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003390484_python.txt
Q: Django Error: Unhandled Exception after running: "python manage.py runserver", I'm getting the error: Validating models... Unhandled exception in thread started by <function inner_run at 0xc942a8> File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/commands/runserver.py", line 48, in ...
Django Error: Unhandled Exception
after running: "python manage.py runserver", I'm getting the error: Validating models... Unhandled exception in thread started by <function inner_run at 0xc942a8> File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_err...
[ "Sounds like you are running a very old version of Python - versions 2.4 and earlier did not support y if x else z. You should upgrade, if possible, or find a version of the massivecoupon package that is compatible with Python 2.4.\n", "Python's only supported the 'a if b else c' syntax since version 2.5. Are you...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003390722_django_python.txt
Q: How do I search a range for a single integer? My Python code generates a random number between 0 and 35 and stores that number as 'random'. I am looking to compare 'random' against several ranges of numbers to determine which of three groups it falls into and assign another value to 'winning' based on which group ...
How do I search a range for a single integer?
My Python code generates a random number between 0 and 35 and stores that number as 'random'. I am looking to compare 'random' against several ranges of numbers to determine which of three groups it falls into and assign another value to 'winning' based on which group 'random' is in. The groups are: 0-16, 16-34, and 34...
[ "First of all, please don't name your variable random. It shadows the random module name and you won't be able to use the random module in the rest of scope because of this.\nSo let's call the result rnd.\n\nYou should use if rnd in range(0, 16): ... instead of for. The syntax\nfor a in list_:\n foo(a)\n\nwill ext...
[ 4, 3, 2, 2, 2 ]
[]
[]
[ "python", "random", "range" ]
stackoverflow_0003390659_python_random_range.txt
Q: when updating an object, what do I call? session.add is for adding, where is update? http://www.sqlalchemy.org/docs/reference/orm/sessions.html I don't see anything for updating an object that was just retrieved from the database using: q = session.query(products) for p in q: p.blah = 'hello' sesion.??...
when updating an object, what do I call? session.add is for adding, where is update?
http://www.sqlalchemy.org/docs/reference/orm/sessions.html I don't see anything for updating an object that was just retrieved from the database using: q = session.query(products) for p in q: p.blah = 'hello' sesion.???? session.commit()
[ "That line p.blah = 'hello' is updating the property (column) blah of the object p.\nThat's the power of object relational mapping in newer languages. Enjoy.\n" ]
[ 4 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003390915_python_sqlalchemy.txt
Q: Python introspection: description of the parameters a function takes Is there is a tool similar to dir() for modules that will tell me what parameters a given function takes? For instance, I would like to do something like dir(os.rename) and have it tell me what parameters are documented so that I can avoid check...
Python introspection: description of the parameters a function takes
Is there is a tool similar to dir() for modules that will tell me what parameters a given function takes? For instance, I would like to do something like dir(os.rename) and have it tell me what parameters are documented so that I can avoid checking the documentation online, and instead use only the Python scripting in...
[ "I realize that you're more interested in help(thing) or thing.__doc__, but if you're trying to do programmatic introspection (instead of human-readable documentation) to find out about calling a function, then you can use the inspect module, as discussed in this question.\n", "help(thing) pretty prints all the d...
[ 12, 4 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0003391013_introspection_python.txt