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: python instance variables as optional arguments In python, is there a way I can use instance variables as optional arguments in a class method? ie: def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... Any help would be appreciated. A: Try this: def foo(self, blah=None): if bl...
python instance variables as optional arguments
In python, is there a way I can use instance variables as optional arguments in a class method? ie: def function(self, arg1=val1, arg2=val2, arg3=self.instance_var): # do stuff.... Any help would be appreciated.
[ "Try this:\ndef foo(self, blah=None):\n if blah is None: # faster than blah == None - thanks to kcwu\n blah = self.instance_var\n\n", "All the responses suggesting None are correct; if you want to make sure a caller can pass None as a regular argument, use a special sentinel and test with is:\nclass Foo...
[ 16, 5, 2, 0 ]
[ "An alternative way of doing this would be:\ndef foo(self, blah=None):\n blah = blah or self.instance_var\n\nThis shorter version looks better, specially when there is more than one optional argument.\nUse with care. See the comments below...\n" ]
[ -1 ]
[ "class", "function", "python" ]
stackoverflow_0000867115_class_function_python.txt
Q: Implementation of an async method in Python DBus How do I implement an async method in Python DBus? An Example below: class LastfmApi(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('fm.lastfm.api', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/...
Implementation of an async method in Python DBus
How do I implement an async method in Python DBus? An Example below: class LastfmApi(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('fm.lastfm.api', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/') @dbus.service.method('fm.last.api.account', ou...
[ "I haven't tried this, but reading the documentation for dbus.service.method reveals the async_callbacks parameter. It sounds like one uses this parameter to provide an asynchronous result. For example:\n@dbus.service.method('fm.last.api.account', out_signature=\"s\",\n async_callbacks=(\"call...
[ 6 ]
[]
[]
[ "asynchronous", "dbus", "python", "twisted" ]
stackoverflow_0002142115_asynchronous_dbus_python_twisted.txt
Q: How can you search Github project Network for unmerged commits to a particular file? I'm working on a project that is hosted @ Github.com It seems that forum/models.py has some errors in it that are preventing me from syncdb. I was curious if there was a way to search through the network to find all the changes th...
How can you search Github project Network for unmerged commits to a particular file?
I'm working on a project that is hosted @ Github.com It seems that forum/models.py has some errors in it that are preventing me from syncdb. I was curious if there was a way to search through the network to find all the changes that had been made in the entire Branch Network to forum/models.py to see if someone had fix...
[ "The closest thing I can think of is to do something like the following:\ngit log branch1 branch2 branch3 -- forum/models.py\n\nwhere branch1 etc. are the various branches, which you would need local copies of.\n", "I contacted Github:\nThere isn't a search for unmerged commits, but if you hit the forkqueue you'l...
[ 1, 1, 0, 0 ]
[]
[]
[ "git", "github", "python" ]
stackoverflow_0002140756_git_github_python.txt
Q: Convert google search results into json in python 3.1 I am writing a Python program that feeds a search term to google using the google search API and downloads the first 10 results. I was able to do this in Python 2.6 as follows: query = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false) url = '...
Convert google search results into json in python 3.1
I am writing a Python program that feeds a search term to google using the google search API and downloads the first 10 results. I was able to do this in Python 2.6 as follows: query = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%...
[ "You'll need to decode the byte object if you want to use it with json.loads\nresultjson = json.loads(results.read().decode())\n\ndocs also suggest to pass encoding parameter to the loads function:\njson.loads(results.read(), encoding=<encoding-type>)\n\nI think Lennart has an explanation how to get the encoding-t...
[ 2, 1 ]
[]
[]
[ "google_search_api", "httpresponse", "json", "python" ]
stackoverflow_0002143206_google_search_api_httpresponse_json_python.txt
Q: How do I get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware) def index(request): fbdata = [] if request.facebook.check_session(request): fbdata = request.facebook.users.getInfo(request.facebook.uid, ['name', 'pic']) print fbdata Thi...
How do I get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware)
def index(request): fbdata = [] if request.facebook.check_session(request): fbdata = request.facebook.users.getInfo(request.facebook.uid, ['name', 'pic']) print fbdata This works! I am able to get the user's picture and name. However...I'd like to get the interests of that user. How can I do that?...
[ "Add \"interests\" in the fields you want to fetch, like this:\nfbdata = request.facebook.users.getInfo(request.facebook.uid, \n ['name', 'pic', 'interests'])\n\n" ]
[ 2 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0002143148_django_facebook_python.txt
Q: Python indentation issue? I'm pretty new to python. This is my first time working with classes in python. When I try to run this script, I get IndentationError: expected an indented block What is wrong with this? import random class Individual: alleles = (0,1) length = 5 string = "" def __...
Python indentation issue?
I'm pretty new to python. This is my first time working with classes in python. When I try to run this script, I get IndentationError: expected an indented block What is wrong with this? import random class Individual: alleles = (0,1) length = 5 string = "" def __init__(self): #some con...
[ "All of those methods that consist of just a comment.\nTo fix it, for example, do this\ndef twoPointCrossover(self, partner):\n #at two random(?) points, crossover.\n pass\n\nThe comments don't count as compilable statements, so you have a bunch of empty blocks. That is why it gives you the indent err...
[ 11, 4, 3, 2, 2, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002143291_python.txt
Q: How do I get a content-type of a file in Python? (with url..) Suppose I haev a video file: http://mydomain.com/thevideofile.mp4 How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file. i want it to return: video/mp4 Edit: this is what I did. What do y...
How do I get a content-type of a file in Python? (with url..)
Suppose I haev a video file: http://mydomain.com/thevideofile.mp4 How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file. i want it to return: video/mp4 Edit: this is what I did. What do you think? f = urllib2.urlopen(url) params['mime'] = f.headers[...
[ "Like so:\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"mydomain.com\")\n>>> conn.request(\"HEAD\", \"/thevideofile.mp4\")\n>>> res = conn.getresponse()\n>>> print res.getheaders()\n\nThat will only download and print the headers because it is making a HEAD request:\n\nAsks for the response identical to ...
[ 12, 4, 0 ]
[]
[]
[ "content_type", "http", "python", "url" ]
stackoverflow_0002143674_content_type_http_python_url.txt
Q: Python DBUS SESSION_BUS - X11 dependency I've got running sample python code which is fine in Ubuntu desktop: import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import threads_init import subprocess from subprocess import call gobject.threads_init() threads_init() dbus.mainl...
Python DBUS SESSION_BUS - X11 dependency
I've got running sample python code which is fine in Ubuntu desktop: import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import threads_init import subprocess from subprocess import call gobject.threads_init() threads_init() dbus.mainloop.glib.DBusGMainLoop( set_as_default = True ...
[ "The problem is that you're running the export calls in separate shells. You need to capture the output of dbus-launch, parse the values, and use os.environ to write them to the environment:\np = subprocess.Popen('dbus-launch', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\nfor var in p.stdout:\n s...
[ 5 ]
[]
[]
[ "dbus", "python", "x11" ]
stackoverflow_0002143785_dbus_python_x11.txt
Q: Read the first line of batch file from the same batch file? I have a batch file that tries to run the program specified in its first line. Similar to Unix's shebang: C:\> more foo.bat #!C:\Python27\python.exe %PYTHON% foo-script.py C:\> What I want to know is: is there a way to automatically set %PYTHON% to C:\Py...
Read the first line of batch file from the same batch file?
I have a batch file that tries to run the program specified in its first line. Similar to Unix's shebang: C:\> more foo.bat #!C:\Python27\python.exe %PYTHON% foo-script.py C:\> What I want to know is: is there a way to automatically set %PYTHON% to C:\Python27\python.exe which is specified in the first line of the scr...
[ "Firstly , on windows, there is no need for shebang. Its best to include the path of the Python interpreter to the PATH environment variable of the user who is running the script. That said, to get the first line in batch, you can use set\nset /p var=<file\n\nsince you have multiple version of interpreter, why not ...
[ 4, 0 ]
[]
[]
[ "batch_file", "python", "shebang", "windows" ]
stackoverflow_0002143897_batch_file_python_shebang_windows.txt
Q: psp (python server pages) code under mod_wsgi? Is there some way to run .psp (python server pages) code under apache + mod_wsgi? While we are moving towards newer wsgi based frameworks we still have some legacy code written in psp which runs under mod_python. We'd like to be able to run it on the same server that...
psp (python server pages) code under mod_wsgi?
Is there some way to run .psp (python server pages) code under apache + mod_wsgi? While we are moving towards newer wsgi based frameworks we still have some legacy code written in psp which runs under mod_python. We'd like to be able to run it on the same server that hosts other wsgi based python code. In short - is t...
[ "No, there is no port of mod_python PSP for mod_wsgi.\nYes, you can run mod_python and mod_wsgi on same server so long as both use same version of Python and both link dynamically with Python library. See:\nhttp://code.google.com/p/modwsgi/wiki/InstallationIssues\nIt isn't recommended to run both together though as...
[ 1 ]
[]
[]
[ "mod_python", "python", "python_server_pages", "wsgi" ]
stackoverflow_0002143915_mod_python_python_python_server_pages_wsgi.txt
Q: what is {% trans "This is the title." %} used for,i can't understand the api i know the {% trans %} is for translation, and how can i translate {% trans "This is the title." %} to chinese. thanks D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm in.py compilemessages processing f...
what is {% trans "This is the title." %} used for,i can't understand the api
i know the {% trans %} is for translation, and how can i translate {% trans "This is the title." %} to chinese. thanks D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm in.py compilemessages processing file django.po in D:\zjm_code\register2\locale\cn\LC_MESSAGES msgfmt: iconv failure...
[ "You don't follow the documentation?\n3 steps:\n\nAdd {% load i18n %} in the template (as Michał Ludwiński says). Put the {% trans %} in your templates, or _ in python code, etc.\nBuild a translation dictionary:\n\nRun django-admin.py makemessages -l cn (cn = China language code) in your Django project root.\nEdit ...
[ 4, 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002144319_django_python.txt
Q: my pythonpath has 'register2',why i can't import it import sys print sys.path ['D:\\zjm_code\\register2', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages'] and #from dj...
my pythonpath has 'register2',why i can't import it
import sys print sys.path ['D:\\zjm_code\\register2', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages'] and #from django.core.management import setup_environ from register2 ...
[ "When directory 'D:\\\\zjm_code\\\\register2' is on sys.path, this means you can import modules and packages that are INSIDE that directory.\nTo import the directory register2 itself, two conditions:\n\nits parent, 'D:\\\\zjm_code', must be on sys.path; and\nfile 'D:\\\\zjm_code\\\\register2\\\\__init__.py' must ex...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002144451_django_python.txt
Q: Why can't I use 'django-admin.py makemessages -l cn' print : D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm in.py makemessages -l cn Error: This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your proje...
Why can't I use 'django-admin.py makemessages -l cn'
print : D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm in.py makemessages -l cn Error: This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or applica tion, maybe you are just missing the conf/lo...
[ "\nis register2 your project or app tree?\ndid you make directory register2\\\\locale?\n\n" ]
[ 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002144503_django_python.txt
Q: best way to add file way to my pythpath.which can be saved import sys print sys.path sys.path+=['D:\\zjm_code'] print sys.path it can't be save,how does do it. A: Where is environment variable PYTHONPATH defined in your working environment? In Unix-like systems it would be in a bash script such as ~/.bashrc. I...
best way to add file way to my pythpath.which can be saved
import sys print sys.path sys.path+=['D:\\zjm_code'] print sys.path it can't be save,how does do it.
[ "Where is environment variable PYTHONPATH defined in your working environment?\nIn Unix-like systems it would be in a bash script such as ~/.bashrc.\nIn Windows it could be a .BAT or .CMD file but more often will be in the registry.\n\"Saving\" a setting of PYTHONPATH to a file is easy.\nWriting to the Windows regi...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002144530_python.txt
Q: How can I access the current URI in python's mako templating system? I'd like to submit the form to the current URI, like this: <form action="${CURRENT_URI}" method="post"> <input type="text" name="email" /> </form> from within a mako template. But I am not sure what variable holds the current uri information. ...
How can I access the current URI in python's mako templating system?
I'd like to submit the form to the current URI, like this: <form action="${CURRENT_URI}" method="post"> <input type="text" name="email" /> </form> from within a mako template. But I am not sure what variable holds the current uri information. Thanks.
[ "Actually, you don't need it. \n<form action=\"\" method=\"post\">\n<input type=\"text\" name=\"email\" />\n</form>\n\nIf you leave the action empty, it will be posted to the current url.\nHowever, if you need the current url for some other reason, it can be retrieved by calling pylons.url.current() \n" ]
[ 1 ]
[]
[]
[ "mako", "pylons", "python" ]
stackoverflow_0002144284_mako_pylons_python.txt
Q: Nested Choices in a python program I have a script that I wrote in python for testing out the sorting algorithms that I've implemented. The main part of the program asks the user to select one of the sort algorithms from a list. And then whether they would like to sort from a file of numbers or select a list of ra...
Nested Choices in a python program
I have a script that I wrote in python for testing out the sorting algorithms that I've implemented. The main part of the program asks the user to select one of the sort algorithms from a list. And then whether they would like to sort from a file of numbers or select a list of random numbers. I have it set up (I think)...
[ "use raw_input()\ndef fileOrRandom():\n return raw_input(\"Would you like to read from file or random list? (A or B): \")\n\nyour while loop should look like this (after fixing the indentation)\nwhile True :\n choice=raw_input(\"Your choice: \")\n for i in range(2):\n if choice==i+1 and fileOrRandom()==\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002144630_python.txt
Q: Python C interoperability I wish to wrap an existing C (pure C that is. No C++) library into Python so that I can call it from Python scripts. Which approach among the various available (C Api, SWIG etc.) would be the most suitable? A: go with Ctypes, it is part of standard distribution and works very well. basi...
Python C interoperability
I wish to wrap an existing C (pure C that is. No C++) library into Python so that I can call it from Python scripts. Which approach among the various available (C Api, SWIG etc.) would be the most suitable?
[ "go with Ctypes, it is part of standard distribution and works very well.\nbasically you can wrap C structures and types in python classes, as well as functions. Some types and functionality is already provided by library. \nctypes\ncouple caveats though: passing triple pointers to C routines is not obvious (if you...
[ 8, 4, 0 ]
[]
[]
[ "c", "interop", "python" ]
stackoverflow_0002144542_c_interop_python.txt
Q: sqlite python insert with where condition from this post sqlite python insert I learned inserting into tables but now I need to use where something like cursor.execute("insert into table1(id) values (?) where ip=? and address=?",(id,),(ip,),(addr,)); A: INSERT does not have a WHERE clause. I think you mean UPDAT...
sqlite python insert with where condition
from this post sqlite python insert I learned inserting into tables but now I need to use where something like cursor.execute("insert into table1(id) values (?) where ip=? and address=?",(id,),(ip,),(addr,));
[ "INSERT does not have a WHERE clause. I think you mean UPDATE.\n", "You can't use a WHERE clause in an INSERT. If you want to specify the values for particular fields to insert, put them in the values clause:\ncursor.execute(\"INSERT INTO table1(id, ip, address) VALUES (?, ?, ?)\", (id, ip, addr))\n\n" ]
[ 4, 0 ]
[]
[]
[ "insert", "python", "sqlite" ]
stackoverflow_0002144840_insert_python_sqlite.txt
Q: Creating very large images using Python Image Library I'm trying to create a very large image (25000x25000) by pasting together many smaller images. Upon calling Image.new() with such large dimensions, python runs out of memory and I get a MemoryError. Is there a way to write out an image like this incrementally, ...
Creating very large images using Python Image Library
I'm trying to create a very large image (25000x25000) by pasting together many smaller images. Upon calling Image.new() with such large dimensions, python runs out of memory and I get a MemoryError. Is there a way to write out an image like this incrementally, without having the whole thing resident in RAM? EDIT: Usin...
[ "You may try to use GDAL library. It provides bindings to Python. Here is combined tutorial presenting how to read and write images using C++, C and Python APIs\nDepending on GDAL operations and functions being used, GDAL can handle very large images and process images which are too large to be held in RAM.\n", "...
[ 3, 2, 2, 0, 0 ]
[ "Use numpy.memmap and the png module.\n" ]
[ -1 ]
[ "python", "python_imaging_library" ]
stackoverflow_0002109109_python_python_imaging_library.txt
Q: Python: multiple calls to __init__() on the same instance The __init__() function gets called when object is created. Is it ok to call an object __init__() function again, after its been created? instance = cls(p1=1, p2=2) # some code instance.__init__(p1=123, p2=234) # some more code instance.__init__(p1=23, p2=2...
Python: multiple calls to __init__() on the same instance
The __init__() function gets called when object is created. Is it ok to call an object __init__() function again, after its been created? instance = cls(p1=1, p2=2) # some code instance.__init__(p1=123, p2=234) # some more code instance.__init__(p1=23, p2=24) why would anyone wanna call __init__() on an object that is...
[ "It's fine to call __init__ more than once on an object, as long as __init__ is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code __init__ appropriately!-) is when your class's __new__ method returns an instance of the class: that does cause __in...
[ 15, 6, 1 ]
[]
[]
[ "initialization", "python" ]
stackoverflow_0002144988_initialization_python.txt
Q: Archiving (tar and compress) with metadata (user id, and ctime) in Python I am in the process of backing up a filesystem and I need to make sure that the metadata is conserved (the file owner and creation time). The tarfile module in Python is really helpful, and I use it extensively in my solution. However, I ca...
Archiving (tar and compress) with metadata (user id, and ctime) in Python
I am in the process of backing up a filesystem and I need to make sure that the metadata is conserved (the file owner and creation time). The tarfile module in Python is really helpful, and I use it extensively in my solution. However, I cannot create the tar file with files conserving their metadata (presumably becau...
[ "\"Presumably\"? You mean you don't know? Have you tried? That said, as far as I know, tarfiles doesn't preserve ctime, and there would be little point in it, as ctime should be reset when you unpack. mtime is preserved, though, and the tarfile module handles mtime.\nThe python tarfile module uses TarInfo objects w...
[ 2 ]
[]
[]
[ "archiving", "backup", "metadata", "python", "tar" ]
stackoverflow_0002145182_archiving_backup_metadata_python_tar.txt
Q: Have a Python CGI call a Perl CGI, passing original info (to limit searching private Mailman archives to logged-in users) I need to have a Python CGI script do some stuff (a little bit of security checking), and then end up calling a Perl CGI script, passing anything it received (e.g., POST info) onto the Perl scr...
Have a Python CGI call a Perl CGI, passing original info (to limit searching private Mailman archives to logged-in users)
I need to have a Python CGI script do some stuff (a little bit of security checking), and then end up calling a Perl CGI script, passing anything it received (e.g., POST info) onto the Perl script. For background, my reason for doing this is that I'm trying to integrate Swish searching with Mailman list archives. Swish...
[ "I'm just going to state the obvious here because I don't have any detailed knowledge about your specific environment.\nIf your python script is a genuine CGI and not a mod_python script or similar then it is just a regular process spawned to handle the one request. You can use os.execv to replace it with another p...
[ 1 ]
[]
[]
[ "cgi", "mailman", "python" ]
stackoverflow_0002145097_cgi_mailman_python.txt
Q: Can Moblin run (and compile) Python scripts? I want to develop an app for Moblin for a competition. The development environment needed by Moblin is too complicated to setup. It uses Anjuta as its IDE, but I could never make sense of the entire compilation toolchain. However, I would like to know if Moblin could co...
Can Moblin run (and compile) Python scripts?
I want to develop an app for Moblin for a competition. The development environment needed by Moblin is too complicated to setup. It uses Anjuta as its IDE, but I could never make sense of the entire compilation toolchain. However, I would like to know if Moblin could compile and run Python scripts. If I could write the...
[ "It does not need to compile them, as it contains a Python interpreter already.\n" ]
[ 0 ]
[]
[]
[ "development_environment", "python" ]
stackoverflow_0002145334_development_environment_python.txt
Q: Python / Django: Is it wise to use "Item" as a class name in Python (in Django in this case)? I'm creating this: # models.py class Item(models.Model): sku = models.CharField(max_length=20) class Attribute(models.Model): item = models.ForeignKey(Item, related_name='items') Is that going to cause naming c...
Python / Django: Is it wise to use "Item" as a class name in Python (in Django in this case)?
I'm creating this: # models.py class Item(models.Model): sku = models.CharField(max_length=20) class Attribute(models.Model): item = models.ForeignKey(Item, related_name='items') Is that going to cause naming collisions in Python? Like: # views.py some_object.items.create(sku='123abc') # Is there a place /...
[ "It does seem a bit generic, but no more so than \"Attribute\". I would give it a prefix based on the app if possible.\n", "It's really not a problem. If you have some random object and feel 'items' is a suitable name for a method, then go ahead. It is not going to cause any collisions with names that happen to b...
[ 3, 2, 2, 1 ]
[]
[]
[ "django", "naming", "naming_conventions", "python" ]
stackoverflow_0002145282_django_naming_naming_conventions_python.txt
Q: How can I set up Celery to call a custom initialization function before running my tasks? I have a Django project and I'm trying to use Celery to submit tasks for background processing ( http://ask.github.com/celery/introduction.html ). Celery integrates well with Django and I've been able to submit my custom task...
How can I set up Celery to call a custom initialization function before running my tasks?
I have a Django project and I'm trying to use Celery to submit tasks for background processing ( http://ask.github.com/celery/introduction.html ). Celery integrates well with Django and I've been able to submit my custom tasks and get back results. The only problem is that I can't find a sane way of performing custom i...
[ "You can either write a custom loader, or use the signals.\nLoaders have the on_task_init method, which is called when a task is about to be executed,\nand on_worker_init which is called by the celery+celerybeat main process.\nUsing signals is probably the easiest, the signals available are:\n0.8.x:\n\ntask_prerun(...
[ 21 ]
[]
[]
[ "amqp", "celery", "daemon", "django", "python" ]
stackoverflow_0002129820_amqp_celery_daemon_django_python.txt
Q: Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library I use Google App Engine and cannot use any C/C++ extension, just pure & pythonic library to do conversion of Unicode/UTF-8 strings to lower/upper case. str.lower() and string.lowercase() don't. A: str encoded in UTF-8 and unicode are ...
Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library
I use Google App Engine and cannot use any C/C++ extension, just pure & pythonic library to do conversion of Unicode/UTF-8 strings to lower/upper case. str.lower() and string.lowercase() don't.
[ "str encoded in UTF-8 and unicode are two different types. Don't use string, use the appropriate method on the unicode object:\n>>> print u'ĉ'.upper()\nĈ\n\nDecode str to unicode before using:\n>>> print 'ĉ'.decode('utf-8').upper()\nĈ\n\n" ]
[ 26 ]
[]
[]
[ "case_conversion", "google_app_engine", "python" ]
stackoverflow_0002145826_case_conversion_google_app_engine_python.txt
Q: Escape @ from python line command I don't know if this is a problem with python or with the shell (zsh on linux), I've an argument like this: "@xyz" that starts with a "@" python the_script.py first_argument @second_argument third_arg I tried to escape @ with \ or \\, or use "" but the program doesn't start. If I ...
Escape @ from python line command
I don't know if this is a problem with python or with the shell (zsh on linux), I've an argument like this: "@xyz" that starts with a "@" python the_script.py first_argument @second_argument third_arg I tried to escape @ with \ or \\, or use "" but the program doesn't start. If I leave the @ from @second_arguments ever...
[ "\nPerhaps the \"@\" is a glob character in zsh, expanding to all symbolic links in the current directory. Try escaping it with \"@@\"?\nTry running the argument list with echo, i.e:\necho the_script.py first_argument @second_argument third_arg\n\nThat way, you can figure out if it was expanded or passed as-is to t...
[ 2 ]
[]
[]
[ "python", "zsh" ]
stackoverflow_0002145901_python_zsh.txt
Q: __cmp__ method is this not working as expected in Python 2.x? class x: def __init__(self,name): self.name=name def __str__(self): return self.name def __cmp__(self,other): print("cmp method called with self="+str(self)+",other="+str(other)) return self.name==other.name...
__cmp__ method is this not working as expected in Python 2.x?
class x: def __init__(self,name): self.name=name def __str__(self): return self.name def __cmp__(self,other): print("cmp method called with self="+str(self)+",other="+str(other)) return self.name==other.name # return False instance1=x("hello") instance2=x("there") ...
[ "__cmp__(x,y) should return a negative number (e.g. -1) if x < y, a positive number (e.g. 1) if x > y and 0 if x == y. You should never return a boolean with it.\nWhat you're overloading is __eq__(x, y).\n", "the __cmp__ method should return -1, 0 or 1, when self < other, self == other, self > other respectvelly....
[ 10, 5, 4, 2, 0 ]
[]
[]
[ "cmp", "python", "python_2.x" ]
stackoverflow_0002146225_cmp_python_python_2.x.txt
Q: Python image processing of picture directly from the web I am writing python code to take an image from the web and calculate the standard deviation, ... and do other image processing with it. I have the following code: from scipy import ndimage from urllib2 import urlopen from urllib import urlretrieve imp...
Python image processing of picture directly from the web
I am writing python code to take an image from the web and calculate the standard deviation, ... and do other image processing with it. I have the following code: from scipy import ndimage from urllib2 import urlopen from urllib import urlretrieve import urllib2 import Image import ImageFilter def imagesd...
[ "PIL (Python Imaging Library) methods \"fromstring\" and \"frombuffer\" expect the image data in a raw, uncompacted, format. \nWhen you do page1.read() you get the binary file data. In order to have PIL understanding it, you have to make this data mimick a file, and pass it to the \"Image.open\" method, which unde...
[ 4 ]
[]
[]
[ "image", "image_processing", "python", "urllib2" ]
stackoverflow_0002145955_image_image_processing_python_urllib2.txt
Q: Help parsing a page with python I would like to parse a webpage to can get the url of the video download. I use python and firebug but I cant get the url link. Example: The url where I have to get the video link is: hxxp://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.sht...
Help parsing a page with python
I would like to parse a webpage to can get the url of the video download. I use python and firebug but I cant get the url link. Example: The url where I have to get the video link is: hxxp://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtml" The video is hxxp://www.rtve.es/r...
[ "Use BeautifulSoup or lxml.\n", "import re \nfrom urllib2 import urlopen\ntext = urlopen('http://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtm').read()\nreg = re.compile(r'http://www\\.rtv.*flv')\nreg.findall(text)\n\nNormallly you can use this one. But there is no ...
[ 5, 0, 0 ]
[]
[]
[ "parsing", "python", "screen_scraping" ]
stackoverflow_0002146110_parsing_python_screen_scraping.txt
Q: Leading and Trailing '0' gives error random.randint(50,9) or random.randint(5,09) give errors, although just random.randint(5,9) ..works! Leading and trailing zero's aren't allowed in python without converting it to string or using x.f formatting? A: oh, dear. "Trailing" zero gives error because first argumen...
Leading and Trailing '0' gives error
random.randint(50,9) or random.randint(5,09) give errors, although just random.randint(5,9) ..works! Leading and trailing zero's aren't allowed in python without converting it to string or using x.f formatting?
[ "oh, dear. \"Trailing\" zero gives error because first argument to randint should be smaller than the second.\nLeading zeros are used to represent octal numbers in python-2.x as in many other languages.\n", "A leading 0 means that the value is an octal literal, but 09 is not a valid octal number.\n", "09 is not...
[ 6, 0, 0 ]
[]
[]
[ "integer", "octal", "python" ]
stackoverflow_0002146381_integer_octal_python.txt
Q: Python globals, locals, and UnboundLocalError I ran across this case of UnboundLocalError recently, which seems strange: import pprint def main(): if 'pprint' in globals(): print 'pprint is in globals()' pprint.pprint('Spam') from pprint import pprint pprint('Eggs') if __name__ == '__main__': mai...
Python globals, locals, and UnboundLocalError
I ran across this case of UnboundLocalError recently, which seems strange: import pprint def main(): if 'pprint' in globals(): print 'pprint is in globals()' pprint.pprint('Spam') from pprint import pprint pprint('Eggs') if __name__ == '__main__': main() Which produces: pprint is in globals() Traceba...
[ "Where's the surprise? Any variable global to a scope that you reassign within that scope is marked local to that scope by the compiler. \nIf imports would be handled differently, that would be surprising imho.\nIt may make a case for not naming modules after symbols used therein, or vice versa, though.\n", "Well...
[ 6, 5, 4, 4 ]
[]
[]
[ "binding", "identifier", "python", "scope" ]
stackoverflow_0000404534_binding_identifier_python_scope.txt
Q: Can I use WSGI with a URI that has spaces? I wrote a small WSGI App: def foo(environ, start_response): bar = 'Your request is %s' % environ['PATH_INFO'] status = '200 OK' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(bar)))] ...
Can I use WSGI with a URI that has spaces?
I wrote a small WSGI App: def foo(environ, start_response): bar = 'Your request is %s' % environ['PATH_INFO'] status = '200 OK' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(bar)))] start_response(status, response_headers) ...
[ "From http://www.ietf.org/rfc/rfc2396.txt\nThe space character is excluded because significant spaces may\n disappear and insignificant spaces may be introduced when URI are\n transcribed or typeset or subjected to the treatment of word-\n processing programs. Whitespace is also used to delimit URI in many\n...
[ 1, 0, 0 ]
[ "You should use \"%20\" in URL's to encode spaces into then -- but don't do that manually:\nuse urllib.quote function, like:\n\n\n\nimport urllib\n base = \"http://localhost:8000/\"\n path = urllib.quote(\"foo bar\")\n checkURL = base + path\n\n\n\n(there is also the \"unquote\" function for you to ...
[ -1 ]
[ "python", "spaces", "wsgi" ]
stackoverflow_0002139613_python_spaces_wsgi.txt
Q: Should a class or method which processes a file close the file as a side effect? I'm wondering which is the more 'Pythonic' / better way to write methods which process files. Should the method which processes the file close that file as a side effect? Should the concept of the data being a 'file' be completely abs...
Should a class or method which processes a file close the file as a side effect?
I'm wondering which is the more 'Pythonic' / better way to write methods which process files. Should the method which processes the file close that file as a side effect? Should the concept of the data being a 'file' be completely abstracted from the method which is processing the data, meaning it should expect some 's...
[ "Generally, it is better practice for the opener of a file to close the file. In your question, the second example is better.\nThis is to prevent possible confusion and invalid operations.\n\nEdit: If your real code isn't any more complex than your example code, then it might be better just to have process() open a...
[ 4, 4, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002147153_file_io_python.txt
Q: csv.reader turning commas into periods throwing errors Here is a sample of the first row: link,Title,Description,Keywords It is made from an excel workbook, I tried saving in all CSV formats (window, ms-dos, and comma delimited list) I even tried saving in 2 txt file formats (window, ms-dos) k... here is the cod...
csv.reader turning commas into periods throwing errors
Here is a sample of the first row: link,Title,Description,Keywords It is made from an excel workbook, I tried saving in all CSV formats (window, ms-dos, and comma delimited list) I even tried saving in 2 txt file formats (window, ms-dos) k... here is the code: csvReader = csv.reader(file('files/my_file.csv', "rU"), d...
[ "Dalkes comment above dropped the coin for me:\nYou are reading from a CSV file, and taking that data and inserting in an SQL database, evidently, although you did not say so. You have a syntax error in your SQL-statement.\nNote that most SQL databases have CSV imports, so you don't need to write them.\nAlso note t...
[ 3, 1, 0 ]
[]
[]
[ "csv", "period", "python", "syntax_error" ]
stackoverflow_0002143371_csv_period_python_syntax_error.txt
Q: Connecting to a Multicast Server in Python This is my code for connecting to a multicast server, is this the best way of handling the exception. What I would like to do is to retry to connect if an exception occurs def initialiseMulticastTrackerComms(): try: sock = socket.socket(socket.AF_INET, socket.SOCK_D...
Connecting to a Multicast Server in Python
This is my code for connecting to a multicast server, is this the best way of handling the exception. What I would like to do is to retry to connect if an exception occurs def initialiseMulticastTrackerComms(): try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.IPPROTO_IP, so...
[ "The simplest solution would be to wrap your try-except-else block in a loop.\nSomething like this\ndef initSock():\n message = \"\"\n for i in range(MAX_TRIES):\n try:\n #...socket opening code\n except socket.error, (value, message):\n message = message\n else:\n ...
[ 1 ]
[]
[]
[ "exception", "multicast", "python", "sockets" ]
stackoverflow_0002147501_exception_multicast_python_sockets.txt
Q: Raising an exception vs printing? Whats the difference between raising an exception and simply printing an error. For example, whats the benefit of using the following: if size < 0: raise ValueError('number must be non-negative') instead of simply: if size < 0: print 'number must be non-negative'...
Raising an exception vs printing?
Whats the difference between raising an exception and simply printing an error. For example, whats the benefit of using the following: if size < 0: raise ValueError('number must be non-negative') instead of simply: if size < 0: print 'number must be non-negative' I'm a newbie, please take it easy on ...
[ "Raising an error halts the entire program at that point (unless the exception is caught), whereas printing the message just writes something to stdout -- the output might be piped to another tool, or someone might not be running your application from the command line, and the print output may never be seen.\nFor e...
[ 11, 6, 3, 2 ]
[]
[]
[ "exception", "printing", "python" ]
stackoverflow_0002146618_exception_printing_python.txt
Q: Qt: Python tcp client sends data over socket. How to read these bytes with Qt? Situation: I have tcp client made with Python and tcp server made with Qt. I try to send bytes with my client but I can't get Qt server to read these bytes. Using Python made client and server, everything works fine. Also I can get my ...
Qt: Python tcp client sends data over socket. How to read these bytes with Qt?
Situation: I have tcp client made with Python and tcp server made with Qt. I try to send bytes with my client but I can't get Qt server to read these bytes. Using Python made client and server, everything works fine. Also I can get my Python client work with C# server with no problems. Code for Python client: import s...
[ "You need to arrange for your code to read when there is data available. From your description, there is not data available yet when startRead() runs.\nI assume you called QTcpServer::nextPendingConnection to get your tcpSocket in startRead()? If not, you need to do so.\nJust connect the readyRead signal from your ...
[ 1, 0 ]
[]
[]
[ "debugging", "python", "qt", "sockets", "tcp" ]
stackoverflow_0002130757_debugging_python_qt_sockets_tcp.txt
Q: Open a PyGTK program but do not activate it I have a PyGTK program which is hidden most of the time, but with a keypress it shall come up as a popup. Therefore I want the program not to be activated when its opened. I tried several options to to that, with no success: self.window.show() self.window.set_focus(None...
Open a PyGTK program but do not activate it
I have a PyGTK program which is hidden most of the time, but with a keypress it shall come up as a popup. Therefore I want the program not to be activated when its opened. I tried several options to to that, with no success: self.window.show() self.window.set_focus(None) Activates the program, but sets no focus. se...
[ "Build the window but don't call show() on it until it is ready to be activated. Then use self.window.present().\nEDIT:\nIf you never want the window to be activated, why not try a notification popup? You need libnotify for this. There are Python bindings. Here is an example: http://roscidus.com/desktop/node/336\nI...
[ 1, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002143152_gtk_pygtk_python.txt
Q: How to retrieve the values for only one table field in Django If I have following database fields: id, name, emp_id. How do I make a query in Django to get the values of column name only with a where clause. Thanks... A: Model.objects.filter(...).values('name') A: In addition to the answer provided by Ignacio ...
How to retrieve the values for only one table field in Django
If I have following database fields: id, name, emp_id. How do I make a query in Django to get the values of column name only with a where clause. Thanks...
[ "Model.objects.filter(...).values('name')\n\n", "In addition to the answer provided by Ignacio Vazquez-Abrams, you could also use values_list to get the names in a flat list (instead of a dictionary). \nModel.objects.filter(...).values_list('name', flat=True)\n\nSee the documentation for values_list.\n" ]
[ 7, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002147882_django_python.txt
Q: How to avoid gcc warning in Python C extension when using Py_BEGIN_ALLOW_THREADS The simplest way to manipulate the GIL in Python C extensions is to use the macros provided: my_awesome_C_function() { blah; Py_BEGIN_ALLOW_THREADS // do stuff that doesn't need the GIL if (should_i_call_back) { ...
How to avoid gcc warning in Python C extension when using Py_BEGIN_ALLOW_THREADS
The simplest way to manipulate the GIL in Python C extensions is to use the macros provided: my_awesome_C_function() { blah; Py_BEGIN_ALLOW_THREADS // do stuff that doesn't need the GIL if (should_i_call_back) { Py_BLOCK_THREADS // do stuff that needs the GIL Py_UNBLOCK_THREA...
[ "\nYes, it is possible to suppress uninitialized warnings using the -Wno- prefix. \n\n-Wall -Wno-uninitialized\nIf you want to remove just this warning, you could simply initialize _save to a null pointer so that it doesn't rely on a function return value... that one line of code and a comment makes sense to me:\nP...
[ 3, 1, 0 ]
[]
[]
[ "cextension", "gcc", "gil", "python" ]
stackoverflow_0002147029_cextension_gcc_gil_python.txt
Q: Virtualenv problem I have created a new environement in virtualenv with --no-site-packages and executed activate file. So, shouldn't my current Django app show any error? Environement doesn't have Django installed. I think, my site is using my old python with Django. How can I change it? Maybe it's because my .hta...
Virtualenv problem
I have created a new environement in virtualenv with --no-site-packages and executed activate file. So, shouldn't my current Django app show any error? Environement doesn't have Django installed. I think, my site is using my old python with Django. How can I change it? Maybe it's because my .htaccess file, here it is: ...
[ "With mod_wsgi, you can set WSGIPythonHome to where your virtualenv is. mod_python doesn't let you set the interpreter easily, however (there may be a way involving setting PYTHONEXECUTABLE at apache startup).\nSee what bin/python (next to bin/activate) does to sys.path, and mimick it in the PythonPath directive. W...
[ 4 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0002148213_django_python_virtualenv.txt
Q: Using getcwd when running in Eclipse When running a project in eclipse the eclipse saves a copy of the .py file inside the workspace defined in project creation. But the file that imported to project can be in other location. If using os.getcwd() and running the script from the command line, the return value would...
Using getcwd when running in Eclipse
When running a project in eclipse the eclipse saves a copy of the .py file inside the workspace defined in project creation. But the file that imported to project can be in other location. If using os.getcwd() and running the script from the command line, the return value would be the real path of the script file, but ...
[ "os.getcwd() returns the current working directory.\nWhen running a Python program from Eclipse you can specify what the working directory should be on the Arguments tab of the Run Configuration. This will let you override the value from the project folder (or whatever the default might be.)\n\n" ]
[ 1 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0002147575_eclipse_python.txt
Q: Python: Rar Brute Forcer I am trying to brute force a RAR archive which is protected by a password with 3 characters: import os Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for a in range(0,26): for b in range(0,26): for c in range(0,26): Brute = Alphabets[a] + Alphabets[b] + Alphabets[c] os.popen4("Rar.exe x...
Python: Rar Brute Forcer
I am trying to brute force a RAR archive which is protected by a password with 3 characters: import os Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for a in range(0,26): for b in range(0,26): for c in range(0,26): Brute = Alphabets[a] + Alphabets[b] + Alphabets[c] os.popen4("Rar.exe x -p" + Brute + " Protected.rar...
[ "You could use (or learn from) rarcrack. It is written in C and compiles without problems on Linux (Windows with lots of changes).\nIn general, opening a process for every single tested password is very expensive. You should try and open the archive yourself, and then test against all passwords. Anyway you need to ...
[ 9, 6, 4, 1, 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0002148393_performance_python.txt
Q: I'm using Hadoop for data processing with python, what file format should be used? I'm using Hadoop for data processing with python, what file format should be used? I have project with a substantial amount of text pages. Each text file has some header information that I need to preserve during the processing; how...
I'm using Hadoop for data processing with python, what file format should be used?
I'm using Hadoop for data processing with python, what file format should be used? I have project with a substantial amount of text pages. Each text file has some header information that I need to preserve during the processing; however, I don't want the headers to interfere with the clustering algorithms. I'm using py...
[ "1) Files\nIf you use Hadoop Streaming, you have to use line-based text-files, data up to the first tab is passed to your mapper as key.\nJust look at the documentation for streaming.\nYou can also put you input-files into HDFS, which would be recommendable for big files. Just look at the \"Large Files\"-section in...
[ 4, 1 ]
[]
[]
[ "hadoop", "python" ]
stackoverflow_0002144171_hadoop_python.txt
Q: What's the difference between OneToOne and Subclassing a model in Django For example: class Subdomain(Site): #fields here and class Subdomain(models.Model): site = models.OneToOne(Site) #fields here A: Models with a OneToOne have an independent PK; submodels always use the PK of their supermodel.
What's the difference between OneToOne and Subclassing a model in Django
For example: class Subdomain(Site): #fields here and class Subdomain(models.Model): site = models.OneToOne(Site) #fields here
[ "Models with a OneToOne have an independent PK; submodels always use the PK of their supermodel.\n" ]
[ 6 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002149567_django_django_models_python.txt
Q: py2exe and win32com Can py2exe create standalone executables even ones requiring the win32com package? I've googled / searched SO to no avail. A: I've used py2exe for a project that depended on win32com as well as pysvn. It worked fine, no hassles. That was using Python 2.5 and later 2.6. Note that py2exe doesn'...
py2exe and win32com
Can py2exe create standalone executables even ones requiring the win32com package? I've googled / searched SO to no avail.
[ "I've used py2exe for a project that depended on win32com as well as pysvn. It worked fine, no hassles.\nThat was using Python 2.5 and later 2.6. Note that py2exe doesn't support Python 3.x.\n", "Yes, it can. But you may need to add a refereneces to DLL that your application needs.\nCheck the bottom of http://www...
[ 4, 3 ]
[]
[]
[ "py2exe", "python", "win32com" ]
stackoverflow_0002113863_py2exe_python_win32com.txt
Q: Python-MySQLdb problem: wrong ELF class: ELFCLASS32 As part of trying out django CMS (http://www.django-cms.org/), I'm struggling with getting Python-MySQLdb to work (http://pypi.python.org/pypi/MySQL-python/). I have installed Django CMS and all of its dependencies (Python 2.5, Django, django-south, MySQL server...
Python-MySQLdb problem: wrong ELF class: ELFCLASS32
As part of trying out django CMS (http://www.django-cms.org/), I'm struggling with getting Python-MySQLdb to work (http://pypi.python.org/pypi/MySQL-python/). I have installed Django CMS and all of its dependencies (Python 2.5, Django, django-south, MySQL server) I'm trying out the example code within Django CMS code ...
[ "Yes, the bit difference is what's causing this. Find or build a 64-bit version of MySQLdb.\nELF is the Executable and Linkable Format. ELFCLASS32 means that it's a 32-bit ELF file.\n" ]
[ 8 ]
[]
[]
[ "django", "django_cms", "linux", "mysql", "python" ]
stackoverflow_0002149782_django_django_cms_linux_mysql_python.txt
Q: Django and fcgi - logging question I have a site running in Django. Frontend is lighttpd and is using fcgi to host django. I start my fcgi processes as follows: python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid For logging, I have a RotatingFileHandler defined as follo...
Django and fcgi - logging question
I have a site running in Django. Frontend is lighttpd and is using fcgi to host django. I start my fcgi processes as follows: python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid For logging, I have a RotatingFileHandler defined as follows: file_handler = RotatingFileHandler(f...
[ "As Alex stated, logging is thread-safe, but the standard handlers cannot be safely used to log from multiple processes into a single file.\nConcurrentLogHandler uses file locking to allow for logging from within multiple processes.\n", "In your shoes I'd switch to a TimedRotatingFileHandler -- I'm surprised that...
[ 6, 2, 0 ]
[]
[]
[ "django", "fastcgi", "lighttpd", "logging", "python" ]
stackoverflow_0001203896_django_fastcgi_lighttpd_logging_python.txt
Q: "NOTICE AUTH" notifications when connecting to IRC server As a learning exercise, I'm writing a Python program to connect to a channel on an IRC network, so I can output messages in the channel to stdout. I'm using asynchat and manually sending the protocol messages, rather than using something like Twisted or exi...
"NOTICE AUTH" notifications when connecting to IRC server
As a learning exercise, I'm writing a Python program to connect to a channel on an IRC network, so I can output messages in the channel to stdout. I'm using asynchat and manually sending the protocol messages, rather than using something like Twisted or existing bot code from the net - again, it's a more useful learnin...
[ "There's no RFC requirement to do this, it's just a common thing that servers in the wild do. Observe that they're plain old NOTICE commands (i.e. just messages). Just treat them as messages sent to a psuedo-user \"AUTH\" (since the server doesn't have a better name for you yet). You're not required to wait for the...
[ 4 ]
[]
[]
[ "irc", "python", "rfc" ]
stackoverflow_0002149895_irc_python_rfc.txt
Q: Python: How does regex re.compile(r'^[-\w]+$') search? Or, how does regex work in this context? By reading the documentation here it seems to me that re.compile(r'^[-\w]+$') would just search whether there was any character that is alphanumeric, an underscore, or a hyphen. But really this returns a match only if ...
Python: How does regex re.compile(r'^[-\w]+$') search? Or, how does regex work in this context?
By reading the documentation here it seems to me that re.compile(r'^[-\w]+$') would just search whether there was any character that is alphanumeric, an underscore, or a hyphen. But really this returns a match only if all the characters fit that description (ie, it fails if there is a space or a dollar sign or asteris...
[ "The two characters ^ and $ mark the start and the end of the string respectively. So ^[-\\w]+$ will only match if there are only one or more word characters or a hyphen ([-\\w]+) between the start (^) and the end of the string ($).\n", "The ^ and $ anchor the regex at the beginning and ending of the string, ther...
[ 4, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002149898_python_regex.txt
Q: How to download a file behind a HTTPS login? How would you go about downloading a webpage file behind an HTTPS login via a language such as python? More specifically I am talking about the page behind the login from http://www.cnbtn.com. A: https will not matter. HTTPS just says that the data going over the wire...
How to download a file behind a HTTPS login?
How would you go about downloading a webpage file behind an HTTPS login via a language such as python? More specifically I am talking about the page behind the login from http://www.cnbtn.com.
[ "https will not matter. HTTPS just says that the data going over the wire is securely encrypted. Rather you need to learn more about how the login actually works. For instance is it Basic Auth (where a popup shows up for user/pass)? you can then make a request like https://user:pass@foo.com/my_file.gif\nMore likely...
[ 2 ]
[]
[]
[ "https", "python" ]
stackoverflow_0002149980_https_python.txt
Q: Alpha masks with OpenGL I want to use an alpha mask in OpenGL so that white(1)=visible and black(0)=hidden. So what I do is I write something in the alpha component of the framebuffer using glColorMask(False, False, False, True) (I'm using python, you see) and then draw some geometry above it using blending. But i...
Alpha masks with OpenGL
I want to use an alpha mask in OpenGL so that white(1)=visible and black(0)=hidden. So what I do is I write something in the alpha component of the framebuffer using glColorMask(False, False, False, True) (I'm using python, you see) and then draw some geometry above it using blending. But it isn't working: I tried fill...
[ "Try asking for an alpha buffer when you create your GL context, if you aren't already.\n", "Use glAlphaFunc( GL_GREATER, 0.5 );\n" ]
[ 3, 0 ]
[]
[]
[ "alpha", "blending", "opengl", "python" ]
stackoverflow_0002134970_alpha_blending_opengl_python.txt
Q: Database for web crawler in python? Hi im writing a web crawler in python to extract news articles from news websites like nytimes.com. i want to know what would be a good db to use as a backend for this project? Thanks in advance! A: This could be a great project to use a document database like CouchDB, MongoDB...
Database for web crawler in python?
Hi im writing a web crawler in python to extract news articles from news websites like nytimes.com. i want to know what would be a good db to use as a backend for this project? Thanks in advance!
[ "This could be a great project to use a document database like CouchDB, MongoDB, or SimpleDB.\nMongoDB has a hosted solution: http://mongohq.com. There is also a binding for Python (Pymongo).\nSimpleDB is a great choice if you are hosting this on Amazon Web Services\nCouchDB is an open source package from the Apach...
[ 7, 3, 1, 0 ]
[]
[]
[ "database", "python", "web_crawler" ]
stackoverflow_0002143702_database_python_web_crawler.txt
Q: Parsing All Mail from Mailbox File in Python Maybe I'm going about this the wrong way, but I want to parse a single "catch all" email inbox via Python. I see the email module and I can make it parse an individual email, but what I want to do is open (for example) /var/spool/mail/catchall and parse all of the indiv...
Parsing All Mail from Mailbox File in Python
Maybe I'm going about this the wrong way, but I want to parse a single "catch all" email inbox via Python. I see the email module and I can make it parse an individual email, but what I want to do is open (for example) /var/spool/mail/catchall and parse all of the individual messages inside it. Opening that file and ru...
[ "You'll want to use mailbox to actually go through the mailbox.\n" ]
[ 2 ]
[]
[]
[ "email", "parsing", "python" ]
stackoverflow_0002150177_email_parsing_python.txt
Q: best way to build time series server using python I'm interested to build a fast server that serves queries on time series. For example, say I have 1000 time series identified by category name x. The server will take a query submitted by a client process and immediately return the last value associated with a part...
best way to build time series server using python
I'm interested to build a fast server that serves queries on time series. For example, say I have 1000 time series identified by category name x. The server will take a query submitted by a client process and immediately return the last value associated with a particular timestamp. For example on the client script, som...
[ "As far as communication goes, do you have a protocol in mind? HTTP? raw TCP?\nI would personally recommend an HTTP server using http://docs.python.org/library/wsgiref.html , although there's a chance that even that is not fast enough.\nYou could also use an SQL server.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002150095_python.txt
Q: Customary To Inherit Metaclasses From type? I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass like def metacls(clsName, bases, atts): .... return type(clsName, ...
Customary To Inherit Metaclasses From type?
I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass like def metacls(clsName, bases, atts): .... return type(clsName, bases, atts) However, I have seen a lot of peopl...
[ "There are subtle differences, mostly relating to inheritance. When using a\nfunction as a metaclass, the resulting class is really an instance of type,\nand can be inherited from without restriction; however, the metaclass function\nwill never be called for such subclasses. When using a subclass of type as a\nme...
[ 46 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0002149846_metaclass_python.txt
Q: Emptying the datastore in GAE I know what you're thinking, 'O not that again!', but here we are since Google have not yet provided a simpler method. I have been using a queue based solution which worked fine: import datetime from models import * DELETABLE_MODELS = [Alpha, Beta, AlphaBeta] def initiate_purge(): ...
Emptying the datastore in GAE
I know what you're thinking, 'O not that again!', but here we are since Google have not yet provided a simpler method. I have been using a queue based solution which worked fine: import datetime from models import * DELETABLE_MODELS = [Alpha, Beta, AlphaBeta] def initiate_purge(): for e in config.DELETABLE_MODELS:...
[ "I don't believe that trying to delete an entity that has references to still-existing entities is really a problem, but you can always rules this out be re-writing your task to delete the entities serially instead of in parallel:\ndef initiate_purge():\n deferred.defer(delete_entities, Alpha, _queue = 'purging'...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002147787_google_app_engine_google_cloud_datastore_python.txt
Q: Can somebody explain a money regex that just checks if the value matches some pattern? There are multiple posts on here that capture value, but I'm just looking to check to see if the value is something. More vaguely put; I'm looking to understand the difference between checking a value, and "capturing" a value. I...
Can somebody explain a money regex that just checks if the value matches some pattern?
There are multiple posts on here that capture value, but I'm just looking to check to see if the value is something. More vaguely put; I'm looking to understand the difference between checking a value, and "capturing" a value. In the current case the value would be the following acceptable money formats: Here is a post...
[ "Assuming you want to allow $5. but not 5., the following will accept your language:\nmoney = re.compile('|'.join([\n r'^\\$?(\\d*\\.\\d{1,2})$', # e.g., $.50, .50, $1.50, $.5, .5\n r'^\\$?(\\d+)$', # e.g., $500, $5, 500, 5\n r'^\\$(\\d+\\.?)$', # e.g., $5.\n]))\n\nImportant pieces to understa...
[ 17, 8, 4, 3 ]
[]
[]
[ "currency", "python", "regex" ]
stackoverflow_0002150205_currency_python_regex.txt
Q: Finding Signed Angle Between Vectors How would you find the signed angle theta from vector a to b? And yes, I know that theta = arccos((a.b)/(|a||b|)). However, this does not contain a sign (i.e. it doesn't distinguish between a clockwise or counterclockwise rotation). I need something that can tell me the minimum...
Finding Signed Angle Between Vectors
How would you find the signed angle theta from vector a to b? And yes, I know that theta = arccos((a.b)/(|a||b|)). However, this does not contain a sign (i.e. it doesn't distinguish between a clockwise or counterclockwise rotation). I need something that can tell me the minimum angle to rotate from a to b. A positive s...
[ "What you want to use is often called the “perp dot product”, that is, find the vector perpendicular to one of the vectors, and then find the dot product with the other vector.\nif(a.x*b.y - a.y*b.x < 0)\n angle = -angle;\n\nYou can also do this:\nangle = atan2( a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y );\n\n", "I...
[ 71, 38 ]
[]
[]
[ "angle", "java", "math", "python", "trigonometry" ]
stackoverflow_0002150050_angle_java_math_python_trigonometry.txt
Q: django - inlineformset_factory with more than one ForeignKey Im trying to do a formset with the following models (boost is the primary): class boost(models.Model): creator = models.ForeignKey(userInfo) game = models.ForeignKey(gameInfo) name = models.CharField(max_length=200) desc = models.CharFiel...
django - inlineformset_factory with more than one ForeignKey
Im trying to do a formset with the following models (boost is the primary): class boost(models.Model): creator = models.ForeignKey(userInfo) game = models.ForeignKey(gameInfo) name = models.CharField(max_length=200) desc = models.CharField(max_length=500) rules = models.CharField(max_length=500) s...
[ "If I understand you correctly:\nTo change what is displayed set the model's __unicode__ function\nclass userInfo(models.Model):\n #model fields\n\n def __unicode__(self):\n return self.auth.username\n\n" ]
[ 11 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002149697_django_python.txt
Q: Is PHP the only choice re: massive and rapid uptake of a re-deployable, extensible web application? My own answer to this question is YES, but I'd like to hear from others. Put another way the question could be: Would the success of 1-click-install WordPress (not WordPress.com, which is SaaS) be possible if it we...
Is PHP the only choice re: massive and rapid uptake of a re-deployable, extensible web application?
My own answer to this question is YES, but I'd like to hear from others. Put another way the question could be: Would the success of 1-click-install WordPress (not WordPress.com, which is SaaS) be possible if it weren't written in PHP, all other things being equal? The critical associated requirements I believe suppor...
[ "As far as points #1 and #2 go, you are probably right. No other platform is so widely, easily and cheaply available in terms of hosting companies and packages like the LAMP stack. Plus, most incompatibilities that can occur when deploying an application to a completely unknown web space are well documented, their ...
[ 3 ]
[]
[]
[ "deployment", "hosting", "php", "python", "wordpress" ]
stackoverflow_0002150947_deployment_hosting_php_python_wordpress.txt
Q: How do you create flash images on the fly at the server side? The question just came up! I have seen in web apps we get flash images generated on the fly how is it achieved? Any api for programming languages (Java Python)? PS: It's adobe flash movie / image or swf A: If by Flash images you mean JPG, PNG and GIF...
How do you create flash images on the fly at the server side?
The question just came up! I have seen in web apps we get flash images generated on the fly how is it achieved? Any api for programming languages (Java Python)? PS: It's adobe flash movie / image or swf
[ "If by Flash images you mean JPG, PNG and GIF files then you use any of the standard server side software packages or language specific libraries that utilize these packages.\nHere are the two most popular:\nImageMagick\nGD\nPython has PIL (Python Imaging Library) \nIf you are referring to generating swfs then upda...
[ 1, 0 ]
[]
[]
[ "flash", "java", "python" ]
stackoverflow_0002075432_flash_java_python.txt
Q: replacing node text using lxml.objectify while preserving attributes Using lxml.objectify like so: from lxml import objectify o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>") o.b = 'newtext' results in <a><b>newtext</b></a>, losing the node attribute. It seems to be directly replacing the element...
replacing node text using lxml.objectify while preserving attributes
Using lxml.objectify like so: from lxml import objectify o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>") o.b = 'newtext' results in <a><b>newtext</b></a>, losing the node attribute. It seems to be directly replacing the element with a newly created one, rather than simply replacing the text of the el...
[ ">>> type(o.b)\n<type 'lxml.objectify.StringElement'>\n\nYou are replacing an element with a plain string. You need to replace it with a new string element.\n>>> o.b = objectify.E.b('newtext', atr='someatr')\n\nFor some reason you can't just do:\n>>> o.b.text = 'newtext'\n\nHowever, this seems to work:\n>>> o.b._se...
[ 10 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0002150838_lxml_python_xml.txt
Q: Reduce strings in python to a specific point I have strings in my python application that look this way: test1/test2/foo/ Everytime I get such a string, I want to reduce it, beginning from the tail and reduced until the fist "/" is reached. test1/test2/ More examples: foo/foo/foo/foo/foo/ => foo/foo/foo/foo/ te...
Reduce strings in python to a specific point
I have strings in my python application that look this way: test1/test2/foo/ Everytime I get such a string, I want to reduce it, beginning from the tail and reduced until the fist "/" is reached. test1/test2/ More examples: foo/foo/foo/foo/foo/ => foo/foo/foo/foo/ test/test/ => test/ how/to/implement/this...
[ "It sounds like the os.path.dirname function might be what you're looking for. You may need to call it more than once:\n>>> import os.path\n>>> os.path.dirname(\"test1/test2/\")\n'test1/test2'\n>>> os.path.dirname(\"test1/test2\")\n'test1'\n\n", "str.rsplit() with the maxsplit argument. Or if this is a path, look...
[ 6, 5, 5, 1, 0, 0, 0 ]
[]
[]
[ "path", "python", "string" ]
stackoverflow_0002145371_path_python_string.txt
Q: How can I use BeautifulSoup to find all the links in a page pointing to a specific domain? How can I use BeautifulSoup to find all the links in a page pointing to a specific domain? A: Use SoupStrainer, from BeautifulSoup import BeautifulSoup, SoupStrainer import re # Find all links links = SoupStrainer('a') [t...
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
[ "Use SoupStrainer,\nfrom BeautifulSoup import BeautifulSoup, SoupStrainer\nimport re\n\n# Find all links\nlinks = SoupStrainer('a')\n[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]\n\nlinkstodomain = SoupStrainer('a', href=re.compile('example.com/'))\n\nEdit: Modified example from official doc.\n" ]
[ 8 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002151365_beautifulsoup_python.txt
Q: Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call? function ajaxCall(query){ $.ajax({ method:"get", url:"/main/", data:"q="+query, beforeSend:function() {}, success:function(html){ $("#main").html(html); } }); }; This is the entire code that will populate #...
Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call?
function ajaxCall(query){ $.ajax({ method:"get", url:"/main/", data:"q="+query, beforeSend:function() {}, success:function(html){ $("#main").html(html); } }); }; This is the entire code that will populate #main: <p>{{ num_results }}, you just searched for {{ query }}</p> Suppose I ...
[ "One option is to return json with the data you need for each area.\n$.ajax({\n method:\"get\",\n url:\"/main/\",\n dataType: \"json\",\n data:\"q=\"+query,\n beforeSend:function() {},\n success:function(json){\n $(\"#main\").html(json.main);\n $(\"#secondary\").html(json.secondary);...
[ 6, 1, 0, 0 ]
[]
[]
[ "ajax", "django", "javascript", "jquery", "python" ]
stackoverflow_0002151490_ajax_django_javascript_jquery_python.txt
Q: Depth-First search in Python Okay so basically I'm trying to do a depth-first search for a mini-peg solitaire game. For those unfamiliar with the game it's pretty simple. There's a board with 10 holes and 9 pegs, a peg is represented by a 1 and an empty spot by a 0. You can move a peg backwards or forwards two h...
Depth-First search in Python
Okay so basically I'm trying to do a depth-first search for a mini-peg solitaire game. For those unfamiliar with the game it's pretty simple. There's a board with 10 holes and 9 pegs, a peg is represented by a 1 and an empty spot by a 0. You can move a peg backwards or forwards two holes at a time (but you can only m...
[ "Since you are allowed to jump over empty holes, you'll have to keep track of any nodes you have already visited. Otherwise you will have an infinite loop.\nYou also need to not shortcircuit the for loop unless you have found a goal\ntested_nodes=set()\ndef solve_board(dfs_obj, node):\n if goal(node): # only 1 ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002151354_python.txt
Q: What to put for a commonName when making an OpenSSL key? I have an application application framework that works in a peer-to-peer manner between unnamed hosts on a network. I want to have the traffic be encrypted, so I've implemented a setup with M2Crypto, but I've run into a snag. I have no idea what to put down ...
What to put for a commonName when making an OpenSSL key?
I have an application application framework that works in a peer-to-peer manner between unnamed hosts on a network. I want to have the traffic be encrypted, so I've implemented a setup with M2Crypto, but I've run into a snag. I have no idea what to put down for 'commonName' when creating the cert. It seems to want a do...
[ "In your use case the default host name checking is not appropriate. You might want to try just doing certificate fingerprint checking. First, get the fingerprints of each certificate (openssl x509 -fingerprint). Let's say you have peer A and peer B, with fingerprint A and fingerprint B, respectively.\nOn peer A si...
[ 1, 1 ]
[]
[]
[ "m2crypto", "python", "ssl" ]
stackoverflow_0002150048_m2crypto_python_ssl.txt
Q: How can I make Sphinx's inheritance_diagram readable? Similar to this chap's post, I'm seeing Sphinx generate unreadable graphviz output: How can I generate readable output? Nothing happens if I add -Gfontsize=140 If I tell it to use neato instead of dot it produces readable output, but the graphs aren't tree...
How can I make Sphinx's inheritance_diagram readable?
Similar to this chap's post, I'm seeing Sphinx generate unreadable graphviz output: How can I generate readable output? Nothing happens if I add -Gfontsize=140 If I tell it to use neato instead of dot it produces readable output, but the graphs aren't tree-like.
[ "I figured out the answer from this thread. In the graphviz.py code, they have a default value for the size of the graph at 8.0x12.0. If you want to allow Graphviz to determine the size you need to put this in conf.py so the Sphinx graphviz extension uses your empty string instead of its default:\ninheritance_gra...
[ 7 ]
[]
[]
[ "graphviz", "python", "python_sphinx" ]
stackoverflow_0002151711_graphviz_python_python_sphinx.txt
Q: Approaching refactoring I have a very data-centric application, written in Python / PyQt. I'm planning to do some refactoring to really separate the UI from the core, mainly because there aren't any real tests in place yet, and that clearly has to change. There is some separation already, and I think I've done qui...
Approaching refactoring
I have a very data-centric application, written in Python / PyQt. I'm planning to do some refactoring to really separate the UI from the core, mainly because there aren't any real tests in place yet, and that clearly has to change. There is some separation already, and I think I've done quite a few things the right way...
[ "If you have not done so already, read \"Working Effectively with Legacy Code\" by Michael Feathers - it deals with exactly this sort of situation, and offers a wealth of techniques for dealing with it. \nOne key point he makes is to try and get some tests in place before refactoring. Since it is not suitable for...
[ 7, 2, 1, 1 ]
[]
[]
[ "python", "qt", "refactoring", "separation_of_concerns", "unit_testing" ]
stackoverflow_0002081745_python_qt_refactoring_separation_of_concerns_unit_testing.txt
Q: possible in sqlalchemy to join table based on a column value? I am trying to create a table to hold user actions on my web app. Take a simple case where a user adds a new story, and comments on it. This will add two entries to the user_action table. In the user_action table I would like to store the module name as...
possible in sqlalchemy to join table based on a column value?
I am trying to create a table to hold user actions on my web app. Take a simple case where a user adds a new story, and comments on it. This will add two entries to the user_action table. In the user_action table I would like to store the module name associated with each action and the items id. In this cause I would s...
[ "What you want are polymorphic models. Read SQLAlchemy docs about this topic or Google them.\n" ]
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002149659_python_sqlalchemy.txt
Q: Making a Python/GTK CheckMenuItem, when clicked, not close the menu Using Python and PyGTK I've got a GtkMenu with various GtkCheckMenuItems in it. When the user clicks one of the checkboxes the menu closes. I'd like for the user to be able to check a series of checkboxes without the menu closing each time. I've ...
Making a Python/GTK CheckMenuItem, when clicked, not close the menu
Using Python and PyGTK I've got a GtkMenu with various GtkCheckMenuItems in it. When the user clicks one of the checkboxes the menu closes. I'd like for the user to be able to check a series of checkboxes without the menu closing each time. I've looked at using the activate callback to show the menu but this doesn't s...
[ "I see the problem here, the \"activate\" signal does not allow you to return a boolean as to whether you wish the signal to propagate onwards. It sounds like you may need to poke around the gtk.CheckMenuItem internals, fire a signal that \"reopens\" the menu at the current position to be processed immediately afte...
[ 2 ]
[ "Try digging into source and it's documentation. I have found this to be the easiest way and best shortcut.\n" ]
[ -1 ]
[ "gtk", "menu", "pygtk", "python" ]
stackoverflow_0002150899_gtk_menu_pygtk_python.txt
Q: Deleting erroneous ReferenceProperty properties in AppEngine Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error. The one exception (no pun intended) is ReferenceProperty. I...
Deleting erroneous ReferenceProperty properties in AppEngine
Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error. The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful ab...
[ "I'm having similar difficulties for my project. As I code the beta version of my application, I do create a lot of dead link and its trully a pain to untangle things afterward. Ideally, this tool would have to also report of the offending reference so that you could pin-point problems in the code.\n", "You could...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "model", "python", "referenceproperty" ]
stackoverflow_0000367029_google_app_engine_model_python_referenceproperty.txt
Q: Returning an instance of a class from a file in python In my program I have a package filled with various .py files each containing a class definition. I want to make a list where each entry is an instance of one of those classes. In addition, my program doesn't know how many files are in the package or what the...
Returning an instance of a class from a file in python
In my program I have a package filled with various .py files each containing a class definition. I want to make a list where each entry is an instance of one of those classes. In addition, my program doesn't know how many files are in the package or what the files or classes are called, so I can't just import each fi...
[ "This sounds like a bit of a bad design. It would probably be better if you elaborate on the problem and we can help you to solve it some other way. However, what you want isn't hard:\nimport types\nimport my_package\n\nmy_package_members = [getattr(my_package, i) for i in dir(my_package)]\nmy_modules = [i for i in...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002151499_python.txt
Q: How can I run Python code on a windows system? I am used to using PHP and it is easy to set up, I can just run an exe package like Xampp and have apache and PHP running in 5 minutes on my windows system. Is there something similar to Python? A: Unlike PHP, Python's primary purpose is a general-purpose tool for ...
How can I run Python code on a windows system?
I am used to using PHP and it is easy to set up, I can just run an exe package like Xampp and have apache and PHP running in 5 minutes on my windows system. Is there something similar to Python?
[ "Unlike PHP, Python's primary purpose is a general-purpose tool for running on the desktop/server, not necessarily as a web application. It has bindings to many powerful GUI toolkits (Qt and wx are two examples of free and popular toolkits that work great on Windows), and so on. Therefore you just download it (eith...
[ 6, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002145232_python_windows.txt
Q: Running a Django test server under twisted web As I'm writing an application which uses twisted web for serving async requests and Django for normal content delivery, I thought it would have been nice to have both run under the same twisted reactor through the WSGI interface of Django. I also wanted to test my app...
Running a Django test server under twisted web
As I'm writing an application which uses twisted web for serving async requests and Django for normal content delivery, I thought it would have been nice to have both run under the same twisted reactor through the WSGI interface of Django. I also wanted to test my app using the nice test server facility that Django off...
[ "This might be exactly what you are looking for: http://github.com/clemesha/twisted-wsgi-django\n" ]
[ 2 ]
[]
[]
[ "asynchronous", "django", "integration", "python", "twisted" ]
stackoverflow_0002148890_asynchronous_django_integration_python_twisted.txt
Q: Python: Obtain edge end points of the graph I need the edge end points from a graph. I have installed networkx. I have some idea how to proceed. networkx.Graph.edges_iter() returns all the edges in the graph [e for e in G.edges_iter()] [(0, 1), (1, 2), (2, 3)] What I want is a list [0,1,1,2,2,3] How do I get this...
Python: Obtain edge end points of the graph
I need the edge end points from a graph. I have installed networkx. I have some idea how to proceed. networkx.Graph.edges_iter() returns all the edges in the graph [e for e in G.edges_iter()] [(0, 1), (1, 2), (2, 3)] What I want is a list [0,1,1,2,2,3] How do I get this from the above data?
[ ">>> import itertools\n>>> list(itertools.chain(*[(0, 1), (1, 2), (2, 3)]))\n[0, 1, 1, 2, 2, 3]\n\nYou may not need list(...) because its already iterable.\nAnd you may also try itertools.chain(G.edges_iter()) directly\n", "edgeList = []\nfor (a,b) in G.edges_iter():\n edgeList.append(a)\n edgeList.append(b...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002152325_python.txt
Q: Displaying dictionary value in django template All, I have the following in my views.py def getgradeform(request): id1=request.user.get_pf().id sc=Sc.objects.filter(id=id1) logging.debug(sc) logging.debug("++++") dict={} dict.update({'sc': sc}) return render_to_response('content/add.html',dict...
Displaying dictionary value in django template
All, I have the following in my views.py def getgradeform(request): id1=request.user.get_pf().id sc=Sc.objects.filter(id=id1) logging.debug(sc) logging.debug("++++") dict={} dict.update({'sc': sc}) return render_to_response('content/add.html',dict) Logging.debug gives an output as [<sc: Robert>] M...
[ "If you want any value in a dictionary, you have to do it on the way\ndict.key\n\n(On python you'll write it as dict['key'])\nSo, to present the value stored with key 'name' \n{{ sc.name }}\n\nAnyway, I think this is not you're case. I think you're not seeing a dictionary, but an object defined from models (as is a...
[ 6 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002152652_django_python_templates.txt
Q: Filtering a list of strings based on contents Given the list ['a','ab','abc','bac'], I want to compute a list with strings that have 'ab' in them. I.e. the result is ['ab','abc']. How can this be done in Python? A: This simple filtering can be achieved in many ways with Python. The best approach is to use "list ...
Filtering a list of strings based on contents
Given the list ['a','ab','abc','bac'], I want to compute a list with strings that have 'ab' in them. I.e. the result is ['ab','abc']. How can this be done in Python?
[ "This simple filtering can be achieved in many ways with Python. The best approach is to use \"list comprehensions\" as follows:\n>>> lst = ['a', 'ab', 'abc', 'bac']\n>>> [k for k in lst if 'ab' in k]\n['ab', 'abc']\n\nAnother way is to use the filter function. In Python 2:\n>>> filter(lambda k: 'ab' in k, lst)\n['...
[ 248, 25, 22, 7 ]
[ "mylist = ['a', 'ab', 'abc']\nassert 'ab' in mylist\n\n" ]
[ -3 ]
[ "list", "python" ]
stackoverflow_0002152898_list_python.txt
Q: How can I install Easy_Install for Python 2.6.4 in Mac OSX 10.4.11 I get the following errors, I've placed [my name] for anonymity: >>> python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py File "<stdin>", line 1 python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py ...
How can I install Easy_Install for Python 2.6.4 in Mac OSX 10.4.11
I get the following errors, I've placed [my name] for anonymity: >>> python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py File "<stdin>", line 1 python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py ^ SyntaxError: invalid syntax If you can't see...
[ "The ez_setup.py script may or may not work depending on your environment. If not, follow the instructions here. In particular, from the shell, make sure that the python 2.6 you installed is now invoked by the command python:\n$ python\nPython 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) \n[GCC 4.0.1 (Apple Inc. bui...
[ 4, 2 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0002152463_easy_install_python.txt
Q: how to find time at particular timezone from anywhere I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work. I only need a solution for Linux, but a cross platform solution would be ideal. A: pytz or dat...
how to find time at particular timezone from anywhere
I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work. I only need a solution for Linux, but a cross platform solution would be ideal.
[ "pytz or dateutil.tz is the trick here. Basically it's something like this:\n>>> from pytz import timezone\n>>> mytz = timezone('Europe/Paris')\n>>> yourtz = timezone('US/Eastern')\n\n>>> from datetime import datetime\n>>> now = datetime.now(mytz)\n>>> alsonow = now.astimezone(yourtz)\n\nThe difficulty actually lie...
[ 9, 4, 1 ]
[]
[]
[ "datetime", "linux", "python", "timezone" ]
stackoverflow_0002152471_datetime_linux_python_timezone.txt
Q: Handle 404 throw by code in appengine I manage the "real" 404 errors in this way: application = webapp.WSGIApplication([ ('/', MainPage), #Some others urls ('/.*',Trow404) #I got the 404 page ],debug=False) But in some parts of my code i throw a 404 error self.error(404) and i wanna show the s...
Handle 404 throw by code in appengine
I manage the "real" 404 errors in this way: application = webapp.WSGIApplication([ ('/', MainPage), #Some others urls ('/.*',Trow404) #I got the 404 page ],debug=False) But in some parts of my code i throw a 404 error self.error(404) and i wanna show the same page that mentioned before, ¿there is a...
[ "The easiest way to do this is to override the error() method on your base handler (presuming you have one) to generate the 404 page, and call that from your regular handlers and your 404 handler. For example:\nclass BaseHandler(webapp.RequestHandler):\n def error(self, code):\n super(BaseHandler, self).error(c...
[ 9, 0 ]
[]
[]
[ "google_app_engine", "http_status_code_404", "python" ]
stackoverflow_0002142198_google_app_engine_http_status_code_404_python.txt
Q: Efficient reordering of coordinate pairs (2-tuples) in a list of pairs in Python I am wanting to zip up a list of entities with a new entity to generate a list of coordinates (2-tuples), but I want to assure that for (i, j) that i < j is always true. However, I am not extremely pleased with my current solutions: f...
Efficient reordering of coordinate pairs (2-tuples) in a list of pairs in Python
I am wanting to zip up a list of entities with a new entity to generate a list of coordinates (2-tuples), but I want to assure that for (i, j) that i < j is always true. However, I am not extremely pleased with my current solutions: from itertools import repeat mems = range(1, 10, 2) mem = 8 def ij(i, j): if i < j...
[ "Current version:\n(Fastest at the time of posting with Python 2.6.4 on my machine.)\nUpdate 3: Since we're going all out, let's do a binary search -- in a way which doesn't require injecting m into mems:\ndef binsearch(x, lst):\n low, high = -1, len(lst)\n while low < high: ...
[ 2, 1, 0 ]
[]
[]
[ "python", "sorting", "tuples" ]
stackoverflow_0002153976_python_sorting_tuples.txt
Q: Parsing a range of integers in a list I've just began learning Python and I've ran into a small problem. I need to parse a text file, more specifically an HTML file (but it's syntax is so weird - divs after divs after divs, the result of a Google's 'View as HTML' for a certain PDF i can't seem to extract the text ...
Parsing a range of integers in a list
I've just began learning Python and I've ran into a small problem. I need to parse a text file, more specifically an HTML file (but it's syntax is so weird - divs after divs after divs, the result of a Google's 'View as HTML' for a certain PDF i can't seem to extract the text because it has a messy table done in m$ wor...
[ "Don't use regular expressions to parse HTML. BeautifulSoup will make light work of this.\nAs for your specific problem, it might be that you are missing a colon at the end of the first line:\nfor o in re.finditer('left:102[0-9]\"><nobr>(.*?)</nobr></div>', words[index]):\n out = o.group(1)\n\nIf this isn't the ...
[ 1 ]
[]
[]
[ "parsing", "python", "regex", "syntax_error" ]
stackoverflow_0002154116_parsing_python_regex_syntax_error.txt
Q: How to enter item into Google AppEngine Datastore? I want to check if an email is in my database in Appengine, and if not: then enter it into the datastore. I am new to python. Why is this simple code not working? (Also If there is a better way/more efficient way to write this, please tell me) (I get the error: B...
How to enter item into Google AppEngine Datastore?
I want to check if an email is in my database in Appengine, and if not: then enter it into the datastore. I am new to python. Why is this simple code not working? (Also If there is a better way/more efficient way to write this, please tell me) (I get the error: BadArgumentError: Unused positional arguments [1]) class ...
[ "You don't need to use quotes when binding a parameter to the query:\nquery = db.GqlQuery(\"SELECT * FROM EmailDatabase WHERE emailaddress = :1\", self.request.get('emailaddress'))\n\nOtherwise it will read it as a string and actually only return objects that have :1 as their emailaddress value.\nAlso, make sure yo...
[ 6 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0002154110_google_app_engine_gql_python.txt
Q: Python: Visualization tool for graphs Guys I have asked this question before but did not receive a single comment or answer I want to simulate a search algorithm on a power law graph and want to visually see the algorithm move from one node to another on the graph. How do I do that? A: You can adapt this complet...
Python: Visualization tool for graphs
Guys I have asked this question before but did not receive a single comment or answer I want to simulate a search algorithm on a power law graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
[ "You can adapt this completely different code I happen to have written for Find the most points enclosed in a fixed size circle :)\nThe useful bit is:\nIt uses the basic windowing system tkinter to create a frame containing a canvas; it then does some algorithm, calling it's own 'draw()' to change the canvas and th...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002153878_python.txt
Q: Log onto a Website and select options using Python I am trying to log onto a website using Python. I have written the code to connect to the target but I need to login and select a button on the website and wait for a response. I have looked at the HTTP Protocol in Python and was thinking of using 'HTTPConnection....
Log onto a Website and select options using Python
I am trying to log onto a website using Python. I have written the code to connect to the target but I need to login and select a button on the website and wait for a response. I have looked at the HTTP Protocol in Python and was thinking of using 'HTTPConnection.putrequest'. I am not sure how to do this, I have the co...
[ "Yes, you use mechanize, which a sort of a \"webbrowser\" for Python. With it you can easily open web pages, find forms, fill in form values and submit the forms from Python. I use it (via Zopes testbrowser module) for testing web applications.\n", "Use urllib2 and create a POST request.\nFor more information, re...
[ 4, 1 ]
[]
[]
[ "httplib", "https", "python", "web_services" ]
stackoverflow_0002154095_httplib_https_python_web_services.txt
Q: Reading XML DOCTYPE info with Python I need to parse a version of an XML file as follows. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE twReport [ <!ELEMENT twReport (twHead?, (twWarn | twDebug | twInfo)*, twBody, twSum?, twDebug*, twFoot?, twClientInfo?)> <!ATTLIST twReport version CDATA "10...
Reading XML DOCTYPE info with Python
I need to parse a version of an XML file as follows. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE twReport [ <!ELEMENT twReport (twHead?, (twWarn | twDebug | twInfo)*, twBody, twSum?, twDebug*, twFoot?, twClientInfo?)> <!ATTLIST twReport version CDATA "10,4"> <----- VERSION INFO HERE I use xml.d...
[ "How about xmlproc's DTD api?\nHere's a random snippet of code I wrote years and years ago to do some work with DTDs from Python, which might give you an idea of what it's like to work with this library:\nfrom xml.parsers.xmlproc import dtdparser\n\nattr_separator = '_'\nchild_separator = '_'\n\ndtd = dtdparser.loa...
[ 2, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002147436_python_xml.txt
Q: pygtk: determine key is a modifier I've got key-press-event handler and i need to determine which kind of key was pressed: modifier or not? It's not in event.state, because this field works only when modifier was pressed with something else, but i need this for single key (i.e. simply pressing control or alt, ...)...
pygtk: determine key is a modifier
I've got key-press-event handler and i need to determine which kind of key was pressed: modifier or not? It's not in event.state, because this field works only when modifier was pressed with something else, but i need this for single key (i.e. simply pressing control or alt, ...).
[ "If your version of GTK+/PyGTK is recent enough, key events have a is_modifier attribute. It's not documented in the PyGTK reference, but it's in the GDK API documentation and is exposed through PyGTK. It was added in GDK 2.10.\n", "You'll find what you're looking for in event.keyval. For example, the following c...
[ 4, 2 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0002150159_gtk_pygtk_python_user_interface.txt
Q: python dictionary question All, This is the request from the template that i get u'subjects': [u'7', u'4', u'5', u'3', u'2', u'1'] In my views how to extract the values like 7 4 5 3 2 1 How do i extract the above sequence from new_subjects=request.POST.get('subjects') Thanks. A: Something like the following: ...
python dictionary question
All, This is the request from the template that i get u'subjects': [u'7', u'4', u'5', u'3', u'2', u'1'] In my views how to extract the values like 7 4 5 3 2 1 How do i extract the above sequence from new_subjects=request.POST.get('subjects') Thanks.
[ "Something like the following:\ntry:\n int_subjects = [int(x) for x in new_subjects]\nexcept ValueError:\n #There was an error parsing.\n\n", "request.POST is an instance of QueryDict which have a method named getlist that returns a list of values for the given key.\nExample:\n>>> new_subjects = request.POS...
[ 5, 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002155246_django_python.txt
Q: Basics of string based protocol security I wasn't sure how to phrase this question, so apologies in advance if it's a duplicate of something else. I wanted to sanity check how I've secured my twisted based application and think I've done a good job at it, but it's been over a decade since I've written anything tha...
Basics of string based protocol security
I wasn't sure how to phrase this question, so apologies in advance if it's a duplicate of something else. I wanted to sanity check how I've secured my twisted based application and think I've done a good job at it, but it's been over a decade since I've written anything that uses raw or managed sockets. Authentication ...
[ "The protocol you described addresses one attack, that is the a replay attack. However, you are very vulnerable to MITM attacks. The TCP connection won't drop when the attacker moves in on the protocol. Further more anything transferred over this system can be sniffed. If you are on the wireless at a cafe ever...
[ 6, 1 ]
[]
[]
[ "cryptography", "encryption", "networking", "python", "twisted" ]
stackoverflow_0002155509_cryptography_encryption_networking_python_twisted.txt
Q: How to launch winpdb from a Python script? When I have to deal with bugs in Python code, I often insert breakpoints so during execution I'm being dropped into the debuger when a breakpoint is reached. I've been mostly using pdb (command line) and pudb (ncurses interface). Is it possible to launch winpdb instead in...
How to launch winpdb from a Python script?
When I have to deal with bugs in Python code, I often insert breakpoints so during execution I'm being dropped into the debuger when a breakpoint is reached. I've been mostly using pdb (command line) and pudb (ncurses interface). Is it possible to launch winpdb instead in such situation? What's the breakpoint code I sh...
[ "Winpdb is normally used so that you run the script with winpdb:\n winpdb myscript.py\n\nIf you want to start it from \"inside\" python instead, the documentation on how to do that is here: http://winpdb.org/docs/embedded-debugging/\n" ]
[ 4 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0002155375_debugging_python.txt
Q: Passing multiple arguments to C function within Python Let's say I have a c library that manipulates a world somehow. I want to use this library with python. I want to be able to write simple python scripts that represent different scenarios of world management. I have functions that create and destroy a world: vo...
Passing multiple arguments to C function within Python
Let's say I have a c library that manipulates a world somehow. I want to use this library with python. I want to be able to write simple python scripts that represent different scenarios of world management. I have functions that create and destroy a world: void* create(void); int destroy(void* world); Here is some pyt...
[ "When you do:\ndef create_world():\n return _create\n\nYou don't call _create, so create_world returns the function pointer. If you want the pointer to your world instance you should write instead:\ndef create_world():\n return _create()\n\n" ]
[ 1 ]
[]
[]
[ "arguments", "ctypes", "python" ]
stackoverflow_0002155808_arguments_ctypes_python.txt
Q: Python: Need to replace a series of different substrings in HTML template with additional HTML or database results Situation: I am writing a basic templating system in Python/mod_python that reads in a main HTML template and replaces instances of ":value:" throughout the document with additional HTML or db result...
Python: Need to replace a series of different substrings in HTML template with additional HTML or database results
Situation: I am writing a basic templating system in Python/mod_python that reads in a main HTML template and replaces instances of ":value:" throughout the document with additional HTML or db results and then returns it as a view to the user. I am not trying to replace all instances of 1 substring. Values can vary. ...
[ "There are dozens of templating options that already exist. Consider genshi, mako, jinja2, django templates, or more.\nYou'll find that you're reinventing the wheel with little/no benefit.\n", "If you can't use an existing templating system for whatever reason, your problem seems best tackled with regular express...
[ 4, 1, 1 ]
[]
[]
[ "mod_python", "python", "replace", "substring", "templating" ]
stackoverflow_0002156045_mod_python_python_replace_substring_templating.txt
Q: Downloading a File Protected by NTLM/SSPI Without Prompting For Credentials Using Python on Win32? I need to download a file on a corporate Sharepoint site using CPython. Existing codebase prevents me from using Ironpython without porting the code, so .NET's WebClient library is out. I also want to download the fi...
Downloading a File Protected by NTLM/SSPI Without Prompting For Credentials Using Python on Win32?
I need to download a file on a corporate Sharepoint site using CPython. Existing codebase prevents me from using Ironpython without porting the code, so .NET's WebClient library is out. I also want to download the file without prompting the user to save and without prompting the user for network credentials. I tried ot...
[ "I ended up finding some VB code from a Microsoft support page that uses a function from urlmon.dll I replicated it with a single line of ctypes code and it accomplished exactly what I needed it to do.\nctypes.windll.urlmon.URLDownloadToFileA(0,url,local_file_name,0,0)\n\n\nurl is the location of the resource (in t...
[ 4 ]
[]
[]
[ "curl", "python", "pywin32", "winapi" ]
stackoverflow_0002149496_curl_python_pywin32_winapi.txt
Q: Django thumbnails from urls I have this Wordpress.com site with thumbnails of themes. I thought about creating a similar site with Django. Instead of using the thumbnail images from the Wordpress gallery as in the page above, I want to have thumbnails of actual blogs. Is there a way to display thumbnails from urls...
Django thumbnails from urls
I have this Wordpress.com site with thumbnails of themes. I thought about creating a similar site with Django. Instead of using the thumbnail images from the Wordpress gallery as in the page above, I want to have thumbnails of actual blogs. Is there a way to display thumbnails from urls? Thank you.
[ "There's nothing django-related here, consider this question\nHow can I take a screenshot/image of a website using Python?\n" ]
[ 2 ]
[]
[]
[ "python", "thumbnails" ]
stackoverflow_0002156553_python_thumbnails.txt
Q: Accessing an attribute using a variable in Python How do I reference this_prize.left or this_prize.right using a variable? from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left"...
Accessing an attribute using a variable in Python
How do I reference this_prize.left or this_prize.right using a variable? from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: choice = "right" # retrieve the value of "l...
[ "The expression this_prize.choice is telling the interpreter that you want to access an attribute of this_prize with the name \"choice\". But this attribute does not exist in this_prize.\nWhat you actually want is to return the attribute of this_prize identified by the value of choice. So you just need to change ...
[ 105, 101 ]
[]
[]
[ "python" ]
stackoverflow_0002157035_python.txt
Q: Google App Engine Patch - How to use stylesheets? Struggling with an install of GAE-Patch and using my stylesheets. My settings.py has the following lines included already, but the media generator is not compiling and packaging it properly: 'combined-%(LANGUAGE_DIR)s.css': ( 'global/look.css', ), ...
Google App Engine Patch - How to use stylesheets?
Struggling with an install of GAE-Patch and using my stylesheets. My settings.py has the following lines included already, but the media generator is not compiling and packaging it properly: 'combined-%(LANGUAGE_DIR)s.css': ( 'global/look.css', ), 'combined-%(LANGUAGE_DIR)s.css': ( 'global/b...
[ "You should look at the app.yaml file:\nIt should look like this:\nhandlers:\n- url: /media\n static_dir: _generated_media\n\nThis means that you need to put your css, etc in the _generated_media folder.\n" ]
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002151776_django_google_app_engine_python.txt
Q: Use getControl to control objects other than the name variable I am using the Zope testbrowser which has been recommended in my last question. The problem that I am facing is that I can use the getControl function to control different objects like: password, username etc. I am trying to submit the page to get to t...
Use getControl to control objects other than the name variable
I am using the Zope testbrowser which has been recommended in my last question. The problem that I am facing is that I can use the getControl function to control different objects like: password, username etc. I am trying to submit the page to get to the next page but the submit button has no 'name' variable, just an '...
[ "I assume that, for one reason or another, you can't add a 'name' attribute to your tag, but if it's only a 'name' that you can't add, you can explicitly set a 'value=Submit' (instead of relying on the default one, which is Submit) and then use browser.getControl('Submit')\nFailing that, you can do something along...
[ 0 ]
[]
[]
[ "https", "mechanize", "python", "testing", "zope" ]
stackoverflow_0002155403_https_mechanize_python_testing_zope.txt