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:
how does execfile() work in python?
does the file which is sent as an argument to execfile runs as an independent process / thread or is the code imported and then executed ? . Also i wanted to know how efficient is it compared to running threads / process .
A:
The file is not run in a separate thread or process... | how does execfile() work in python? | does the file which is sent as an argument to execfile runs as an independent process / thread or is the code imported and then executed ? . Also i wanted to know how efficient is it compared to running threads / process .
| [
"The file is not run in a separate thread or process, it runs synchronously with the caller.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004033669_python.txt |
Q:
Simplify this python code
I've written a program to check if my thought about solution on paper is right (and it is).
The task: how many zeros is in the back of multiplication of all numbers from 10 to 200.
It is 48 and it is a simple to calculate manually.
I never write on python seriously and this is what I get:... | Simplify this python code | I've written a program to check if my thought about solution on paper is right (and it is).
The task: how many zeros is in the back of multiplication of all numbers from 10 to 200.
It is 48 and it is a simple to calculate manually.
I never write on python seriously and this is what I get:
mul = 1
for i in range(10, 200... | [
"A straight-forward implementation that doesn't involve calculating the factorial (so that it works with big numbers, ie 2000000!) (edited):\nfives = 0\ntwos = 0\nfor i in range(10, 201):\n while i % 5 == 0:\n fives = fives + 1\n i /= 5\n while i % 2 == 0:\n twos = twos + 1\n i /= 2\nprint(m... | [
11,
6,
4,
3,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004028844_python.txt |
Q:
What do i build my alpha platform on, PHP, Ruby, Python, .NET, etc?
I am developing a social networking website in the facebook/foursquare-ish space. I have gotten such varied feedback on what platform I should develop in. Of course it will be heavily influenced by who I hire, but i was hoping for a little additio... | What do i build my alpha platform on, PHP, Ruby, Python, .NET, etc? | I am developing a social networking website in the facebook/foursquare-ish space. I have gotten such varied feedback on what platform I should develop in. Of course it will be heavily influenced by who I hire, but i was hoping for a little additional feedback from the larger community. Thanks.
| [
"It doesn't matter.\nStackOverflow was written in ASP .NET MVC and it's awesome.\nTwitter was written in Rails and it's super popular.\nFacebook was written in PHP and half a billion people use it. \nIt's not the technology, it's the community. That's the hard part.\nJust pick one and go. Your best bet might act... | [
7,
1
] | [] | [] | [
".net",
"php",
"python",
"ruby_on_rails"
] | stackoverflow_0004033735_.net_php_python_ruby_on_rails.txt |
Q:
Is python a stable platform for facebook development?
I'm trying to build my first facebook app, and it seems that the python facebook (pyfacebook) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.
Are there any mature python frontends for facebook? If not,... | Is python a stable platform for facebook development? | I'm trying to build my first facebook app, and it seems that the python facebook (pyfacebook) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.
Are there any mature python frontends for facebook? If not, what's the best language for facebook development?
| [
"The updated location of pyfacebook is on github. Plus, as arstechnica well explains:\n\nPyFacebook is also very easy to extend\n when new Facebook API methods are\n introduced. Each Facebook API method\n is described in the PyFacebook library\n using a simple data structure that\n specifies the method's name ... | [
13,
11,
4,
3
] | [] | [] | [
"api",
"facebook",
"python"
] | stackoverflow_0001027990_api_facebook_python.txt |
Q:
django site administration (entering fixtures data)
I have a django site. a snippet of myapp/models.py looks like this:
class Continent(models.Model):
name = models.CharField(max_length=128, db_index=True, unique=True)
class GeographicRegion(models.Model):
continent = models.ForeignKey(Continent, null=Fal... | django site administration (entering fixtures data) | I have a django site. a snippet of myapp/models.py looks like this:
class Continent(models.Model):
name = models.CharField(max_length=128, db_index=True, unique=True)
class GeographicRegion(models.Model):
continent = models.ForeignKey(Continent, null=False)
name = models.CharField(max_length=128, null=Fa... | [
"You need to define __unicode__ method in model:\ndef __unicode__(self):\n return self.name\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004034434_django_python.txt |
Q:
Understanding __call__ and list.sort(key)
I have the following code I am trying to understand:
>>> class DistanceFrom(object):
def __init__(self, origin):
self.origin = origin
def __call__(self, x):
return abs(x - self.origin)
>>> nums = [1, 37, 42, 101, 13, 9, -20]
>>> n... | Understanding __call__ and list.sort(key) | I have the following code I am trying to understand:
>>> class DistanceFrom(object):
def __init__(self, origin):
self.origin = origin
def __call__(self, x):
return abs(x - self.origin)
>>> nums = [1, 37, 42, 101, 13, 9, -20]
>>> nums.sort(key=DistanceFrom(10))
>>> nums
[9, 13,... | [
"__call__ in python allows a class to be run as if it's a function. You can try this out manually:\n>>> dis = DistanceFrom(10)\n>>> print dis(10), dis(5), dis(0)\n0 5 10\n>>> \n\nWhat sort does is call that function for every item in your list and uses the returned value as sort key. In this example you'll get a li... | [
8,
7,
4,
1,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0004034455_python_sorting.txt |
Q:
Python: Parsing JSON String List for Each JSON Object
I use the json module and the dumps method to obtain a string which represents a list of json objects :
import json
jsonstring = json.dumps(data)
I would like to iterate over this string to obtain each JSON object as a string.
Any suggestions?
Thanks in advanc... | Python: Parsing JSON String List for Each JSON Object | I use the json module and the dumps method to obtain a string which represents a list of json objects :
import json
jsonstring = json.dumps(data)
I would like to iterate over this string to obtain each JSON object as a string.
Any suggestions?
Thanks in advance.
P.S. I have tried the following:
for jsonobject in json... | [
"for jsonobject in json.loads(jasonstring):\n print jsonobject\n\n",
"You should iterate over your data before you turn it into a string, then turn each element of the data into JSON:\nfor d in data:\n jsonstring = json.dumps(d)\n\n"
] | [
3,
1
] | [] | [] | [
"json",
"list",
"python",
"string"
] | stackoverflow_0004034599_json_list_python_string.txt |
Q:
Tweepy twitter oauth authentication not returning oauth_verifier
I am using a python library called "tweepy" for twitter. When I try to authorize the user, twitter is supposed to redirect to a callback url with auth_token and oauth_verifier. I am getting only auth_token in the url. Anyone else had the same proble... | Tweepy twitter oauth authentication not returning oauth_verifier | I am using a python library called "tweepy" for twitter. When I try to authorize the user, twitter is supposed to redirect to a callback url with auth_token and oauth_verifier. I am getting only auth_token in the url. Anyone else had the same problem?
| [
"Twitter only uses oauth_verifier (PINs) for desktop applications. For web applications, Twitter bypasses this and does not use it. You can re-check your application settings at http://dev.twitter.com/apps\n"
] | [
2
] | [] | [] | [
"api",
"oauth",
"python",
"tweepy",
"twitter"
] | stackoverflow_0004033789_api_oauth_python_tweepy_twitter.txt |
Q:
Roman representation of integers
Possible Duplicate:
How do you find a roman numeral equivalent of an integer
I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number?
string Roman(int Num){...}
For example, Roman(1981) must produce "MCMLXXXI".
A:
... | Roman representation of integers |
Possible Duplicate:
How do you find a roman numeral equivalent of an integer
I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number?
string Roman(int Num){...}
For example, Roman(1981) must produce "MCMLXXXI".
| [
"I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial.\n",
"Here is a lengthy e... | [
3,
1,
1,
1,
0
] | [] | [] | [
"algorithm",
"c++",
"java",
"python",
"roman_numerals"
] | stackoverflow_0004035155_algorithm_c++_java_python_roman_numerals.txt |
Q:
Pylons, cookies not being destroyed
I am trying to remove a cookie called "session" to logout a user.
request.cookies.pop('session', None)
response.set_cookie('session', '', max_age=-100, domain='.example.org')
response.set_cookie('session', '', max_age=-100, domain='www.example.org')
response.delete_cookie('sessi... | Pylons, cookies not being destroyed | I am trying to remove a cookie called "session" to logout a user.
request.cookies.pop('session', None)
response.set_cookie('session', '', max_age=-100, domain='.example.org')
response.set_cookie('session', '', max_age=-100, domain='www.example.org')
response.delete_cookie('session', '', domain='.example.org')
response.... | [
"If you're using Pylons' built-in sessions with Beaker, it is much simpler to use session.invalidate() and session.delete(). \nAre you using Beaker, or are you rolling your own solution for this ?\n"
] | [
0
] | [] | [] | [
"cookies",
"pylons",
"python",
"session_cookies"
] | stackoverflow_0003936798_cookies_pylons_python_session_cookies.txt |
Q:
Python: 'import node.py' raises "No module named py"-error
I have a file main.py like this:
import node.py
[my code...]
and a node.py like this:
[more of my code]
When executing main.py, I get this error:
File "/home/loldrup/repo/trunk/src/src/main.py", line 2, in <module>
import node.py
ImportError: No mo... | Python: 'import node.py' raises "No module named py"-error | I have a file main.py like this:
import node.py
[my code...]
and a node.py like this:
[more of my code]
When executing main.py, I get this error:
File "/home/loldrup/repo/trunk/src/src/main.py", line 2, in <module>
import node.py
ImportError: No module named py
| [
"You should just say import node. The . in the name makes python think you want to load a submodule named py of the packagenode, hence the error. All of this is explained in detail in the Python Tutorial.\n",
"If you have a function named node in a module called node, the clearest thing to do is:\nfrom node impor... | [
9,
0
] | [
"I friend helped me out. It turns out I shall use:\nfrom node import *\n\n"
] | [
-2
] | [
"python",
"python_import"
] | stackoverflow_0004032780_python_python_import.txt |
Q:
How to include annotation in JSON string?
I've got a view that returns a list of shipments encoded as JSON...
def get_new_shipments(request):
# ...
shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
.annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid... | How to include annotation in JSON string? | I've got a view that returns a list of shipments encoded as JSON...
def get_new_shipments(request):
# ...
shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
.annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount'))
return json_response(... | [
"This seems to work:\nreturn HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json')\n\ndef json_formatter(obj):\n if isinstance(obj, datetime.datetime):\n return obj.isoformat()\n elif isinstance(obj, Decimal):\n return u... | [
1
] | [] | [] | [
"django",
"python",
"simplejson"
] | stackoverflow_0004035686_django_python_simplejson.txt |
Q:
Fastest DNS library for python
What library is the fastest to make hundreds of DNS queries in multi-tasking.
I've googled round DNS libraries for python. I found that adns is said to be fastest.
But it's not Windows-compatible. Are there any cross-platform compatible DNS libraries for python?
A:
Twisted's DNS ... | Fastest DNS library for python | What library is the fastest to make hundreds of DNS queries in multi-tasking.
I've googled round DNS libraries for python. I found that adns is said to be fastest.
But it's not Windows-compatible. Are there any cross-platform compatible DNS libraries for python?
| [
"Twisted's DNS library is cross platform. Whether or not it's the \"fastest\" is debateable but Twisted performs very well on the whole. I'd be surprised if it couldn't saturate your I/O link.\nOne point of note though: Twisted uses asynchronous I/O rather than multi-tasking to achieve concurrency. Async I/O is a v... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004034251_python.txt |
Q:
How can "k in d" be False, but "k in d.keys()" be True?
I have some python code that's throwing a KeyError exception. So far I haven't been able to reproduce outside of the operating environment, so I can't post a reduced test case here.
The code that's raising the exception is iterating through a loop like this:... | How can "k in d" be False, but "k in d.keys()" be True? | I have some python code that's throwing a KeyError exception. So far I haven't been able to reproduce outside of the operating environment, so I can't post a reduced test case here.
The code that's raising the exception is iterating through a loop like this:
for k in d.keys():
if condition:
del d[k]
The d... | [
"k in d.keys() will test equality iteratively for each key, while k in d uses __hash__, so your __hash__ may be broken (i.e. it returns different hashes for objects that compare equal).\n",
"Simple example of what's broken, for interest:\n>>> count = 0\n>>> class BrokenHash(object):\n... def __hash__(self):\n... | [
18,
5,
4
] | [
"What you're doing would throw a a concurrent modification exception in Java. d.keys() creates a list of the keys as they exist when you call it, but that list is now static - modifications to d will not change a stored version of d.keys(). So when you iterate over d.keys() but delete items, you end up with the pos... | [
-1
] | [
"dictionary",
"python",
"python_2.x"
] | stackoverflow_0004036114_dictionary_python_python_2.x.txt |
Q:
Subtracting the current and previous item in a list
It is very common to write a loop and remember the previous.
I want a generator that does that for me. Something like:
import operator
def foo(it):
it = iter(it)
f = it.next()
for s in it:
yield f, s
f = s
Now subtract pair-wise.
L =... | Subtracting the current and previous item in a list | It is very common to write a loop and remember the previous.
I want a generator that does that for me. Something like:
import operator
def foo(it):
it = iter(it)
f = it.next()
for s in it:
yield f, s
f = s
Now subtract pair-wise.
L = [0, 3, 4, 10, 2, 3]
print list(foo(L))
print [x[1] - x[... | [
"[y - x for x,y in zip(L,L[1:])]\n\n",
"l = [(0,3), (3,4), (4,10), (10,2), (2,3)]\nprint [(y-x) for (x,y) in l]\n\nOutputs: [3, 1, 6, -8, 1]\n",
"Recipe from iterools:\nfrom itertools import izip, tee\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, N... | [
47,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0004029436_python.txt |
Q:
3rd party applications inside iFrames?
I am about to build a web application and I want to allow other developers extend it with their own applications.
Should I do this with iFrames like Facebook?
Is this a good practice?
Are there other alternatives that let other developers extend my application (that is for th... | 3rd party applications inside iFrames? | I am about to build a web application and I want to allow other developers extend it with their own applications.
Should I do this with iFrames like Facebook?
Is this a good practice?
Are there other alternatives that let other developers extend my application (that is for the user it looks like it's from my applicatio... | [
"If you meant \"embed\" rather than \"extend\" and you just want people to drop a little box on a page and that's it, then an iframe should be fine.\nHowever, if you want two-way communication or mashupability — rather than \"opaque blob of HTML and hope for the best\" communication — then a JavaScript or REST API ... | [
1,
0
] | [] | [] | [
"html",
"javascript",
"python",
"ruby"
] | stackoverflow_0004033325_html_javascript_python_ruby.txt |
Q:
WxPython Incompatible With Snow Leopard?
Recently I upgraded to Snow Leopard, and now I can't run programs built with wxPython. The errors I get are (from Eclipse + PyDev):
import wx
File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks
/Python.framework/Versions/2.6/Extras/lib/
... | WxPython Incompatible With Snow Leopard? | Recently I upgraded to Snow Leopard, and now I can't run programs built with wxPython. The errors I get are (from Eclipse + PyDev):
import wx
File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks
/Python.framework/Versions/2.6/Extras/lib/
python/wx-2.8-mac-unicode/wx/__init__.py", lin... | [
"The problem is that WxPython is only available on the Mac in 32-bit mode; however, by default, Python will start up in 64-bit mode. To fix this problem, create the following shell script named python_32:\n\n#! /bin/bash\nexport VERSIONER_PYTHON_PREFER_32_BIT=yes\n/usr/bin/python \"$@\"\n\nMake the script executabl... | [
25,
15,
2,
1,
1,
0
] | [] | [] | [
"eclipse",
"pydev",
"python",
"wxpython"
] | stackoverflow_0002565201_eclipse_pydev_python_wxpython.txt |
Q:
How to interface a simple keypad with the computer and mobile using PYTHON?
The problem is that i want to interface my mobile phone with my computer using a keypad in between. The interfacing should be done in Python environment as this would help me in my further work.
the things which i need is
inteface my co... | How to interface a simple keypad with the computer and mobile using PYTHON? | The problem is that i want to interface my mobile phone with my computer using a keypad in between. The interfacing should be done in Python environment as this would help me in my further work.
the things which i need is
inteface my computer with the keypad using python
interface the same keypad with a mobile phone... | [
"The most general way to connect your computer to a phone would be over TCP/IP, likely delivered via WiFi to your phone. If using an Android, BlueTooth would be another option, but iOS will not connect to unapproved BT devices.\nProgramming on the handset will likely have to be done in the native language. It's a... | [
0
] | [] | [] | [
"keypad",
"python",
"user_interface"
] | stackoverflow_0004035334_keypad_python_user_interface.txt |
Q:
How to limit program's execution time when using subprocess?
I want to use subprocess to run a program and I need to limit the execution time. For example, I want to kill it if it runs for more than 2 seconds.
For common programs, kill() works well. But if I try to run /usr/bin/time something, kill() can’t really ... | How to limit program's execution time when using subprocess? | I want to use subprocess to run a program and I need to limit the execution time. For example, I want to kill it if it runs for more than 2 seconds.
For common programs, kill() works well. But if I try to run /usr/bin/time something, kill() can’t really kill the program.
My code below seems doesn’t work well. The progr... | [
"If you're using Python 2.6 or later, you can use the multiprocessing module.\nfrom multiprocessing import Process\n\ndef f():\n # Stuff to run your process here\n\np = Process(target=f)\np.start()\np.join(timeout)\nif p.is_alive():\n p.terminate()\n\n\nActually, multiprocessing is the wrong module for this t... | [
9,
3,
0
] | [] | [] | [
"kill",
"python",
"subprocess"
] | stackoverflow_0004033578_kill_python_subprocess.txt |
Q:
Tkinter Canvas Does Not Display
I'm attempting to learn some Python and Tkinter. The sample code below is intended to put two windows on the screen, a few buttons, and a Canvas with an image in it and some lines drawn on it.
The windows and buttons appear just fine, however I'm not seeing either the canvas image ... | Tkinter Canvas Does Not Display | I'm attempting to learn some Python and Tkinter. The sample code below is intended to put two windows on the screen, a few buttons, and a Canvas with an image in it and some lines drawn on it.
The windows and buttons appear just fine, however I'm not seeing either the canvas image or canvas lines. I'd appreciate some... | [
"I solved this problem:\nself.photo = ImageTk.PhotoImage(image)\nself.item = canvas.create_image(0, 0, image=self.photo)\n\nA reference to the ImageTk instance must be stored somewhere, or when your App.__init__() method returns, it will be garbage collected, and the canvas will not be able to display it. (Tkinter... | [
7,
4
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0002223985_python_tkinter_tkinter_canvas.txt |
Q:
Apache Chainsaw with Python and multiple tabs
I am using Apache Chainsaw with python (using the XMLLayout formatter, sending log messages to Chainsaw)
How can I make Chainsaw display multiple log tabs, one for each logging source ?
currently it displays all messages, regardless of which process sent them, to a sin... | Apache Chainsaw with Python and multiple tabs | I am using Apache Chainsaw with python (using the XMLLayout formatter, sending log messages to Chainsaw)
How can I make Chainsaw display multiple log tabs, one for each logging source ?
currently it displays all messages, regardless of which process sent them, to a single tab
| [
"By default, Chainsaw routes events to tabs based by looking at the values of 'hostname' and 'application' properties of each logging event (essentially MDC entries if they exist). \nIf you define those properties in your XML representation of each logging event, Chainsaw will route events to individual tabs based... | [
1
] | [] | [] | [
"log4j",
"logging",
"python"
] | stackoverflow_0004034047_log4j_logging_python.txt |
Q:
Search app in Django
I am building search app using django & sphinx. I got the setup working but when I search I get irrelevant results. Here is what I do -
# this is in my trial_data Model
search = SphinxSearch(
index = 'trial_data trial_datastemmed',
weights = {'name': 10... | Search app in Django | I am building search app using django & sphinx. I got the setup working but when I search I get irrelevant results. Here is what I do -
# this is in my trial_data Model
search = SphinxSearch(
index = 'trial_data trial_datastemmed',
weights = {'name': 100,},
mode ... | [
"As far as i can tell, there are two ways of going about this.\nFirstly, there are sort modes SPH_SORT_RELEVANCE, SPH_SORT_ATTR_DESC, SPH_SORT_ATTR_ASC, SPH_SORT_TIME_SEGMENTS, SPH_SORT_EXTENDED. I assume that keyword in the SphinxSearch constructor would be sortmode, but I couldn't find the docs.\nsearch = Sp... | [
2
] | [] | [] | [
"django",
"django_sphinx",
"python",
"search",
"sphinx"
] | stackoverflow_0004036936_django_django_sphinx_python_search_sphinx.txt |
Q:
A good way to make Django geolocation aware? - Django/Geolocation
I would like to be able to associate various models (Venues, places, landmarks) with a City/Country.
But I am not sure what some good ways of implementing this would be.
I'm following a simple route, I have implemented a Country and City model.
Whe... | A good way to make Django geolocation aware? - Django/Geolocation | I would like to be able to associate various models (Venues, places, landmarks) with a City/Country.
But I am not sure what some good ways of implementing this would be.
I'm following a simple route, I have implemented a Country and City model.
Whenever a new city or country is mentioned it is automatically created.
U... | [
"A good starting places would be to get a location dataset from a service like Geonames. There is also GeoDjango which came up in this question.\nAs you encounter new location names, check them against your larger dataset before adding them. For your 2nd point, you'll need to design this into your object model and ... | [
7,
0
] | [] | [] | [
"django",
"geolocation",
"python"
] | stackoverflow_0004035195_django_geolocation_python.txt |
Q:
how to reference compiled python code in IronPython?
we need to reference .py code from C#. This was solved using IronPython 2.6
The issue arises from the fact that .py code uses 'import customlib' which is a library compiled into customlib.pyc
IronPython gives error: IronPython.Runtime.Exceptions.ImportException:... | how to reference compiled python code in IronPython? | we need to reference .py code from C#. This was solved using IronPython 2.6
The issue arises from the fact that .py code uses 'import customlib' which is a library compiled into customlib.pyc
IronPython gives error: IronPython.Runtime.Exceptions.ImportException: No module named customlib
attempted solution:
in python c... | [
"*.pyc files are CPython specific. You'll have to decompile them or invoke CPython.\nFor decompiling try:\n\nhttp://sourceforge.net/projects/unpyc/\nFree Python decompiler that is not an online service?\n\n"
] | [
2
] | [] | [] | [
"c#",
"ironpython",
"python"
] | stackoverflow_0004037133_c#_ironpython_python.txt |
Q:
Google app engine regular expression
I'm working on a Google appengine project and I've encountered a quandary. The following should (if the regex's are normal) redirect everything which does not contain the word "test" to the MainPage class, and the rest to the TestPage class.
application = webapp.WSGIApplicatio... | Google app engine regular expression | I'm working on a Google appengine project and I've encountered a quandary. The following should (if the regex's are normal) redirect everything which does not contain the word "test" to the MainPage class, and the rest to the TestPage class.
application = webapp.WSGIApplication(
[
... | [
"Actually, it's being interpreted as identical to any rearrangement of the characters aside from the leading caret within the square brackets, such as [^est()]. Standard regular expression syntax includes no straightforward way to specify the complement of the language matched by a particular regex.\nIn this case, ... | [
7,
3,
3
] | [] | [] | [
"google_app_engine",
"python",
"regex"
] | stackoverflow_0004037484_google_app_engine_python_regex.txt |
Q:
Add a python script at runtime
I am beginning python and working on a project, and one thing I would like to be able to do is download and run a script dynamically at runtime.
The general idea is to be able to connect to a server, download a python script on demand, and run that script that was just downloaded wi... | Add a python script at runtime | I am beginning python and working on a project, and one thing I would like to be able to do is download and run a script dynamically at runtime.
The general idea is to be able to connect to a server, download a python script on demand, and run that script that was just downloaded without having to restart the program ... | [
"You can definitely do this. Use urllib to download or generate the script, then import it. It'll work like a charm every time, as long as you download the script to your PYTHONPATH.\nFor example:\nfrom urllib import urlretrieve\nurlretrieve('http://www.mysite.com/myscript.py', '/home/me/script.py')\nimport script\... | [
1,
1,
0
] | [] | [] | [
"dynamic",
"python",
"runtime"
] | stackoverflow_0004037913_dynamic_python_runtime.txt |
Q:
Using multiple memcache servers in a pool
I'm going through the documentation and I'm a little confused as to how memcache does internal load-balancing if multiple servers are specified. For example:
import memcache
mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',])
mc.set("some_key", "Some value")
print mc.g... | Using multiple memcache servers in a pool | I'm going through the documentation and I'm a little confused as to how memcache does internal load-balancing if multiple servers are specified. For example:
import memcache
mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',])
mc.set("some_key", "Some value")
print mc.get("some_key")
Will the setting and retrieval ... | [
"memcached places keys on servers based on a hash of the key. As long as your server setup doesn't change, then a given key will always land on a given server. \n"
] | [
12
] | [] | [] | [
"memcached",
"python"
] | stackoverflow_0004038094_memcached_python.txt |
Q:
How to store a return value in a variable and use print to display the value returned
Modify the main function to call getAction right after the win.getMouse() call inside of the while loop. Store the return value in a variable named action, and use print to display the value returned.
This is my code so far. Wha... | How to store a return value in a variable and use print to display the value returned | Modify the main function to call getAction right after the win.getMouse() call inside of the while loop. Store the return value in a variable named action, and use print to display the value returned.
This is my code so far. What I'm having trouble with is how to return the value in a variable named action, and then u... | [
"You have lots of things (apparently) wrong with your code.\nACTION_PET(win) will give you a TypeError: 'int' object is not callable\nreturn the value in a variable named action What value?\nif inBox(rec1, mouseClick): Where is inBox() defined?\n\nif inBox(rec1, mouseClick):\n drawHappy(win) ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004038018_python.txt |
Q:
Using the ALT key with PyGame
I'm looking to detect the Alt key in PyGame, but every time I press it, it will bring up the menu that you normally get if you click the icon at the upper left of the window (Restore, Maximize, etc).
How do I get PyGame to recognise the keypress, rather than the window?
many thanks
A... | Using the ALT key with PyGame | I'm looking to detect the Alt key in PyGame, but every time I press it, it will bring up the menu that you normally get if you click the icon at the upper left of the window (Restore, Maximize, etc).
How do I get PyGame to recognise the keypress, rather than the window?
many thanks
| [
"The only solution i could think of is pygame.event.set_grab(True) to grab all input.\nhttp://www.pygame.org/docs/ref/event.html (Check the comments for the keycodes)\nI don’t know if this blocks alt+tab and/or multimedia buttons, too, so you should preoceed with caution.\n"
] | [
0
] | [] | [] | [
"pygame",
"python",
"windows"
] | stackoverflow_0004031941_pygame_python_windows.txt |
Q:
wxPython CheckListBox with HTML
I'm using wxPython to create a GUI app. Right now I'm using a wx.CheckListBox to display options with check boxes, but I'd like the text in the CheckListBox to be formatted using HTML. What's the best way to go about this?
A:
Replace wxCheckListBox with wxHtmlWindow and use wxpTag... | wxPython CheckListBox with HTML | I'm using wxPython to create a GUI app. Right now I'm using a wx.CheckListBox to display options with check boxes, but I'd like the text in the CheckListBox to be formatted using HTML. What's the best way to go about this?
| [
"Replace wxCheckListBox with wxHtmlWindow and use wxpTag for the check boxes.\nHere is some code to get you started.\nimport wx\nimport wx.lib.wxpTag\n\n\nclass HtmlCheckListBox(wx.html.HtmlWindow):\n def __init__(self, parent, choices=None):\n wx.html.HtmlWindow.__init__(self, parent)\n\n check_bo... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004037076_python_wxpython.txt |
Q:
Python - How to use underlying object's constructor as class method?
Please forgive the bad title - I had a hard time trying to think of a concise way to explain this.
I have a Python class that will have some underlying objects of other classes. I want to be able to create these underlying objects via a method of... | Python - How to use underlying object's constructor as class method? | Please forgive the bad title - I had a hard time trying to think of a concise way to explain this.
I have a Python class that will have some underlying objects of other classes. I want to be able to create these underlying objects via a method of the original object. Let me try to explain better with an example:
class ... | [
"Sure, no problem: Just pass *args and **kwargs on to Bar:\nclass Foo:\n def __init__(self):\n self.bars = []\n\n def append_bar(self, *args, **kwargs):\n self.bars.append(Bar(*args, **kwargs))\n\nclass Bar:\n def __init__(self, a, b, c, d):\n self.a = a\n self.b = b\n se... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004038258_python.txt |
Q:
Add new keys to a dictionary while incrementing existing values
I am processing a CSV file and counting the unique values of column 4. So far I have coded this three ways. One uses "if key in dictionary", the second traps the KeyError and the third uses "DefaultDictionary". For example (where x[3] is the value fro... | Add new keys to a dictionary while incrementing existing values | I am processing a CSV file and counting the unique values of column 4. So far I have coded this three ways. One uses "if key in dictionary", the second traps the KeyError and the third uses "DefaultDictionary". For example (where x[3] is the value from the file and "a" is a dictionary):
First way:
if x[3] in a:
a[x... | [
"Use collections.Counter. Counter is syntactic sugar for defaultdict(int), but what's cool about it is that it accepts an iterable in the constructor, thus saving an extra step (I assume all of your examples above are wrapped in a for-loop.)\nfrom collections import Counter\ncount = Counter(x[3] for x in my_csv_rea... | [
6,
6,
1,
0,
0
] | [] | [] | [
"dictionary",
"python",
"unique_key"
] | stackoverflow_0004036474_dictionary_python_unique_key.txt |
Q:
How to iterate over two lists?
I am trying to do something in pyGTk where I build a list of HBoxes:
self.keyvalueboxes = []
for keyval in range(1,self.keyvaluelen):
self.keyvalueboxes.append(gtk.HBox(False, 5))
But I then want to run over the list and assign A text entry & a label into each one both of which ... | How to iterate over two lists? | I am trying to do something in pyGTk where I build a list of HBoxes:
self.keyvalueboxes = []
for keyval in range(1,self.keyvaluelen):
self.keyvalueboxes.append(gtk.HBox(False, 5))
But I then want to run over the list and assign A text entry & a label into each one both of which are stored in a list.
| [
"If your list are of equal length use zip\n>>> x = ['a', 'b', 'c', 'd']\n>>> y = [1, 2, 3, 4]\n>>> z = zip(x,y)\n>>> z\n[('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> for l in z: print l[0], l[1]\n... \na 1\nb 2\nc 3\nd 4\n>>> \n\n",
"Check out http://docs.python.org/library/functions.html#zip. It lets you iterate... | [
4,
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004038481_gtk_pygtk_python.txt |
Q:
Search range of int values using djapian
I'm using djapian as my search backend, and I'm looking to search for a range of values. For example:
query = 'comments:(0..10)'
Post.indexer.search(query)
would search for Posts with between 0 and 10 comments. I cannot find a way to do this in djapian, though I have found... | Search range of int values using djapian | I'm using djapian as my search backend, and I'm looking to search for a range of values. For example:
query = 'comments:(0..10)'
Post.indexer.search(query)
would search for Posts with between 0 and 10 comments. I cannot find a way to do this in djapian, though I have found this issue, and patch to implement some kind ... | [
"Ok, I worked it out. I'll leave the answer here for posterity.\nThe first thing to do is to attach a NumberValueRangeProcessor to the QueryParser. You can do this by extending the djapian Indexer._get_query_parser. Note the leading underscore. Below is a code snippet showing how I did it.\nfrom djapian import Inde... | [
0
] | [] | [] | [
"django",
"python",
"search",
"xapian"
] | stackoverflow_0004006502_django_python_search_xapian.txt |
Q:
What's wrong with float("1,000")?
Very rusty with my Python. I have a list of Cost as strings. I'm trying to convert them to floats but when the cost is above $1000, the value is represented with a comma. float("1,000") returns an error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
... | What's wrong with float("1,000")? | Very rusty with my Python. I have a list of Cost as strings. I'm trying to convert them to floats but when the cost is above $1000, the value is represented with a comma. float("1,000") returns an error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
decimal("1,000")
TypeError: 'module' ... | [
"decimal is not float. decimal is a module. That is the reason for the error you get.\nAs for the commas, drop them first:\ns = \"1,000\"\nfloat(s.replace(\",\", \"\")) # = 1000.0\n\n",
"Use re to remove any \",\" formatting before you convert to float.\n>>> import re\n>>> re.sub(\",\", \"\", \"1000,00,00\")\n'10... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004038719_python.txt |
Q:
html 1.13 package installation
I downloaded html 1.13 package from Python site and as per instructions I doubleclicked on install.bat and installed it. I also added the directory C:\Python26\HTML.py-0.04 to PYTHONPATH. But when I try to import the module with
>>> from html import HTML
I still get ImportError: ... | html 1.13 package installation | I downloaded html 1.13 package from Python site and as per instructions I doubleclicked on install.bat and installed it. I also added the directory C:\Python26\HTML.py-0.04 to PYTHONPATH. But when I try to import the module with
>>> from html import HTML
I still get ImportError: No module named html Can someone hel... | [
"Usual installation issues.\n\nIssue\n\nyou don't need to add it to PYTHONPATH if it is installed into standard directory site-packages and it would already be in the path.\ncheck out there should be a html.. folder in default search path : lib\\site-packages\nC:\\Python26\\lib\\site-packages\\\nIf you find the fol... | [
1
] | [] | [] | [
"html",
"python",
"python_module",
"pythonpath"
] | stackoverflow_0004038772_html_python_python_module_pythonpath.txt |
Q:
How do I parse timezones from dates in python
Here's what I have tried so far. I'm just not too sure as to why it outputs as PST instead of GMT. I'm not sure if that's not the correct way to parse it, or to output it. Something seems to be wrong somewhere.
>>> x = time.strptime('Wed, 27 Oct 2010 22:17:00 GMT', '%a... | How do I parse timezones from dates in python | Here's what I have tried so far. I'm just not too sure as to why it outputs as PST instead of GMT. I'm not sure if that's not the correct way to parse it, or to output it. Something seems to be wrong somewhere.
>>> x = time.strptime('Wed, 27 Oct 2010 22:17:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')
>>> time.strftime('%a, %d... | [
"First of all i recommend that you use dateutil\n>>> import dateutil.parser\n\n>>> x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')\ndatetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())\n>>> str(x)\n'2010-10-27 22:17:00+00:00'\n>>> x.strftime('%a, %d %b %Y %H:%M:%S %Z')\n'Wed, 27 Oct 2010 22:17:00 UTC'... | [
2,
1
] | [] | [] | [
"date",
"python",
"timezone"
] | stackoverflow_0004038797_date_python_timezone.txt |
Q:
MySQL syntax error using python to add column to a table
The code i have is:
for key in keys:
cursor.execute("""
ALTER TABLE segment_table ADD %s VARCHAR(40)
""", key)
I get a error telling me my syntax is wrong. When I replace the %s with a actual string the syntax err... | MySQL syntax error using python to add column to a table | The code i have is:
for key in keys:
cursor.execute("""
ALTER TABLE segment_table ADD %s VARCHAR(40)
""", key)
I get a error telling me my syntax is wrong. When I replace the %s with a actual string the syntax error goes away.
for key in keys:
cursor.execute("""
... | [
"There is a bit of confusion going here, for several reasons:\n(1) mySQL uses the % as a parameter marker -- easily confused with the % in Python's string % (data1, data2, etc)\n(2) some people seem not to be aware that parameter markers can be used only where an expression can be used in SQL syntax -- this exclude... | [
5,
3,
2
] | [] | [] | [
"mysql",
"python",
"syntax_error"
] | stackoverflow_0004036067_mysql_python_syntax_error.txt |
Q:
How does logging handler become a str?
I have a logger that functions properly at the start of a script, then breaks in the middle. It looks like its handler is getting overwritten by a str, but I can't figure out where.
At the start of the script, I'm printing the handler and its level. The following code:
prin... | How does logging handler become a str? | I have a logger that functions properly at the start of a script, then breaks in the middle. It looks like its handler is getting overwritten by a str, but I can't figure out where.
At the start of the script, I'm printing the handler and its level. The following code:
print 'Array of handlers', logger.handlers
f... | [
"The contents of the string might give you a clue as to how and why it is going wrong.\nI suggest putting\nprint(repr(self.log.handlers))\n\nright before your call to info:\nself.log.info('%s %s%s%s', method, url, formstr, headerstr)\n\n"
] | [
0
] | [] | [] | [
"freebase",
"handler",
"logging",
"python"
] | stackoverflow_0004039021_freebase_handler_logging_python.txt |
Q:
How to compare parts of flat files?
I have some simple data stored in series of text files. Once line per record, but number and type of fields can vary per record.
The files contain almost the same data.
The exists an "ideal" data file to which these must be compared. Some fields can vary, but some need to matc... | How to compare parts of flat files? | I have some simple data stored in series of text files. Once line per record, but number and type of fields can vary per record.
The files contain almost the same data.
The exists an "ideal" data file to which these must be compared. Some fields can vary, but some need to match. I also need to now if any records are... | [
"I modified the following to simply iterate over every combination of lines from file1 and file2.\nI think the for, else construction works well here.\ndef comparefiles(file1, file2):\n for row in file1:\n for row in file2:\n #check all of your lines, break if condition is met\n else:\n... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004039099_python.txt |
Q:
using `map` to construct multiple named tuples
Suppose I have a namedtuple like
>>> Point = namedtuple('Point','x y')
Why is it that I construct a single object via
>>> Point(3,4)
yet when I want to apply Point via map, I have to call
>>> map(Point._make,[(3,4),(5,6)])
I suspect this has something to do with cl... | using `map` to construct multiple named tuples | Suppose I have a namedtuple like
>>> Point = namedtuple('Point','x y')
Why is it that I construct a single object via
>>> Point(3,4)
yet when I want to apply Point via map, I have to call
>>> map(Point._make,[(3,4),(5,6)])
I suspect this has something to do with classmethods, perhaps, and am hoping that in figuring ... | [
"Point._make takes a tuple as its sole argument. Your map call is equivalent to [Point._make((3, 4)), Point._make((5, 6))].\nUsing a list comprehension makes this more obvious: [Point(*t) for t in [(3, 4), (5, 6)]] achieves the same effect.\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004039245_python.txt |
Q:
Django: Include related models in JSON string?
Building on this question, now I have another problem. Given this,
shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
.annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) \
.select_related('p... | Django: Include related models in JSON string? | Building on this question, now I have another problem. Given this,
shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
.annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) \
.select_related('pickup_address','dropoff_address','billing_address')
... | [
"You can use a list comprehension full of shipment dicts with the related objects filled in. This API gives the client an explicit name for each address. Positional notation makes it too easy to ship to the billing address. Josh Block's \"How to Design a Good API and Why it Matters\" is worth reading.\nshipments = ... | [
1
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0004039019_django_json_python.txt |
Q:
Is it possible to write one-liners in Python?
I was going through the code golf question here on Stack Overflow and saw many Perl one-liner solutions.
Is something like that possible in Python?
A:
python -c 'print("Yes.")'
A:
It's possible to write one liners in Python but it's awkward (Python encourages well ... | Is it possible to write one-liners in Python? | I was going through the code golf question here on Stack Overflow and saw many Perl one-liner solutions.
Is something like that possible in Python?
| [
"python -c 'print(\"Yes.\")'\n",
"It's possible to write one liners in Python but it's awkward (Python encourages well indented code which is somewhat at odds with the \"one-liner\" concept). It's a bit easier in Python 3 because print() is a function and not a statement. Here's one:\npython -c \"fact = lambda x:... | [
23,
17,
10,
4,
2,
0,
0
] | [
"Yes, actually it is very common. I use one-liners when I need to write quick code. It just depends on what you want to do. Here is a small line I just used this evening. It is the creation of a Tkinter button in a single line.\na = Button(root, text=\"Button\", command=com1).pack()\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0004005952_python.txt |
Q:
Are boolean instance variables prepended with "is" in Python?
Is it standard practice or convention in Python to prepend boolean instance variables with is?
For example:
"options.isVerbose"
A:
Mixed-case is less common than underscores: is_verbose, and actually, the is- prefix isn't all that common. I guess the... | Are boolean instance variables prepended with "is" in Python? | Is it standard practice or convention in Python to prepend boolean instance variables with is?
For example:
"options.isVerbose"
| [
"Mixed-case is less common than underscores: is_verbose, and actually, the is- prefix isn't all that common. I guess there isn't a strong convention one way or the other.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004039354_python.txt |
Q:
Django, Python: How do I know if users have closed their browser without click logout?
Django, Python: How do I know if users have closed their browser without click logout?
Really seriously question, because I need to analyse the user activities.
A:
HTTP is a stateless protocol: you can't know at the server if ... | Django, Python: How do I know if users have closed their browser without click logout? | Django, Python: How do I know if users have closed their browser without click logout?
Really seriously question, because I need to analyse the user activities.
| [
"HTTP is a stateless protocol: you can't know at the server if the user has simply closed their browser without informing you.\n",
"it something to not do , but you can do something similar to Gmail (the way that they track if a user is still connected or not) you can do an AJAX request each 10 second or so (max ... | [
4,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004039278_django_python.txt |
Q:
PHP front-end for installing Django
A simple question:
Is this possible?
Is it worth the time looking into it?
A:
You should probably bundle Django with your project - or the parts of it that are needed. Users of your product will need to have python and the necessary libs installed. That is not something that ... | PHP front-end for installing Django | A simple question:
Is this possible?
Is it worth the time looking into it?
| [
"You should probably bundle Django with your project - or the parts of it that are needed. Users of your product will need to have python and the necessary libs installed. That is not something that you can do via PHP. Well, you could, but that would be like Webmin. When making a product for sale or for users to in... | [
1
] | [] | [] | [
"django",
"php",
"python"
] | stackoverflow_0004033492_django_php_python.txt |
Q:
Live video stream on server (PC) from images sent by robot through UDP
Hmm. I found this which seems promising:
http://sourceforge.net/projects/mjpg-streamer/
Ok. I will try to explain what I am trying to do clearly and in much detail.
I have a small humanoid robot with camera and wifi stick (this is the robot). ... | Live video stream on server (PC) from images sent by robot through UDP | Hmm. I found this which seems promising:
http://sourceforge.net/projects/mjpg-streamer/
Ok. I will try to explain what I am trying to do clearly and in much detail.
I have a small humanoid robot with camera and wifi stick (this is the robot). The robot's wifi stick average wifi transfer rate is 1769KB/s. The robot has... | [
"Checking out your first question. Though the solution here uses a non-streaming set of pictures. It might help. The example uses pyMedia.\n\nhttp://pymedia.org/tut/src/make_video.py.html\n\nSome along the lines of what you want. \n\nhttp://code.google.com/p/mjpeg-stream-client/\n\nIf you have a need to edit a bina... | [
1,
1
] | [] | [] | [
"ffmpeg",
"python",
"udp",
"video",
"video_streaming"
] | stackoverflow_0004035365_ffmpeg_python_udp_video_video_streaming.txt |
Q:
Is it possible to open up certain web addresses using the default internet browser with python?
I want python to open up a certain address using the computers default web browser. Is this possible?
A:
Absolutely, use the webbrowser module.
| Is it possible to open up certain web addresses using the default internet browser with python? | I want python to open up a certain address using the computers default web browser. Is this possible?
| [
"Absolutely, use the webbrowser module.\n"
] | [
8
] | [] | [] | [
"python",
"webaddress"
] | stackoverflow_0004039924_python_webaddress.txt |
Q:
Convert CURL command line to Python script
Having way too much trouble making this cmd line curl statement work in python script...help! Attempting to use URLLIB.
curl -X POST "http://api.postmarkapp.com/email" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "X-Postmark-Server-Token: ab... | Convert CURL command line to Python script | Having way too much trouble making this cmd line curl statement work in python script...help! Attempting to use URLLIB.
curl -X POST "http://api.postmarkapp.com/email" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "X-Postmark-Server-Token: abcdef-1234-46cc-b2ab-38e3a208ab2b" \
-v \
-d "{Fr... | [
"Ok so you should probably user urllib2 to submit the actual request but here is the code:\nimport urllib\nimport urllib2\n\nurl = \"http://api.postmarkapp.com/email\"\ndata = \"{From: 'sender@email.com', To: 'recipient@email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}\"\nheaders = { \"... | [
6
] | [] | [] | [
"curl",
"python"
] | stackoverflow_0004039884_curl_python.txt |
Q:
Conditional statements with Python lists
I am trying to learn Python lists. In this code I am trying to add a string s coming from a form to table row as long as the string is the same. When the string is different; the new string is written to the next column.
I could write the string from column 0 to column 1 bu... | Conditional statements with Python lists | I am trying to learn Python lists. In this code I am trying to add a string s coming from a form to table row as long as the string is the same. When the string is different; the new string is written to the next column.
I could write the string from column 0 to column 1 but I had problems adding the same string on col... | [
"If the order of the strings is important, a dictionary will be a problem. You are on the right path using lists, but I think you need more than just that. Honestly, I'm not clear on what your output will look like for different data sets. If I read your question correctly, is the following true?\nInput:\nSenten... | [
2,
0,
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0004011728_if_statement_python.txt |
Q:
Compatibility layer above AWS & GAE?
Has anyone developed an abstraction layer above Amazon Web Services and the Google App Engine? It would be nice to be able to develop a system that could be migrated between either of those two platforms. I am interested in Python.
A:
Look at TyphoonAE or AppScale. Both proj... | Compatibility layer above AWS & GAE? | Has anyone developed an abstraction layer above Amazon Web Services and the Google App Engine? It would be nice to be able to develop a system that could be migrated between either of those two platforms. I am interested in Python.
| [
"Look at TyphoonAE or AppScale. Both projects provide an App Engine like environment. I have successfully ran Python applications, with no modifications, built using webapp on TyphoonAE.\nYou can also look at django-nonrel or web2py for frameworks with features designed to make moving between GAE + bigtable and o... | [
4,
1
] | [] | [] | [
"amazon_web_services",
"google_app_engine",
"python"
] | stackoverflow_0004039685_amazon_web_services_google_app_engine_python.txt |
Q:
How to make Xcode Python friendly?
I have started using Xcode as my main code editor. How might I make Xcode do things like using # instead of // for comments, and otherwise making the IDE friendlier?
A:
From what I can see it already gets the syntax highlighting right, so I think you're talking about the Cmd-/ ... | How to make Xcode Python friendly? | I have started using Xcode as my main code editor. How might I make Xcode do things like using # instead of // for comments, and otherwise making the IDE friendlier?
| [
"From what I can see it already gets the syntax highlighting right, so I think you're talking about the Cmd-/ script that comments a region out. If you select the Edit User Scripts option from the scripts menu you'll set that it's just a perl script. Find the line that tests the shebang in the file for what comment... | [
2
] | [] | [] | [
"python",
"xcode"
] | stackoverflow_0004040060_python_xcode.txt |
Q:
How to create a form in django using ChoiceField in foms.py
I have to build a form where I want a drop down menu list, what will be the procedure.
If u can then plz do tell me the stepwise procedur coz I am a beginner in python. example, what code to be written in views.py, forms.py and urls.py etc.
Thanks in adva... | How to create a form in django using ChoiceField in foms.py | I have to build a form where I want a drop down menu list, what will be the procedure.
If u can then plz do tell me the stepwise procedur coz I am a beginner in python. example, what code to be written in views.py, forms.py and urls.py etc.
Thanks in advance................Byeee
| [
"Choices are easy to specify manually (or, for that matter, programatically) in Django.\nThis depicts a model, which will in turn have a dropdown selector in a ModelForm:\nhttp://docs.djangoproject.com/en/dev/ref/models/fields/#choices\nYou can do the same thing in a regular form.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004039897_django_python.txt |
Q:
Cant determine whats causing an regex error, and would like some input on the efficiency of my program
Nearing what I would like to think is completion on a tool I've been working on. What I've got going on is some code that does essentially this:
open several files and urls which consist of known malware/phishin... | Cant determine whats causing an regex error, and would like some input on the efficiency of my program | Nearing what I would like to think is completion on a tool I've been working on. What I've got going on is some code that does essentially this:
open several files and urls which consist of known malware/phishing related websites/domains and create a list for each, Parse the html of a url passed when the method is cal... | [
"It seems like your problem is that some of the URLs contain special regex characters, such as ? and +; for instance, the string ++ is really quite likely. The other problem is that you keep overwriting the regex you're using to test. If you just need to check if one string is contained in another, there's no nee... | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004040147_python_regex.txt |
Q:
Help with a Python Sudoku Verifier with Loops
Im working on a a sudoku program for python and i need some help. The program will ask input from the user for 9 rows of numbers that hopefully contain the digits 1-9. Once they input all 9 rows the program should then go through each row and verify and see if it satis... | Help with a Python Sudoku Verifier with Loops | Im working on a a sudoku program for python and i need some help. The program will ask input from the user for 9 rows of numbers that hopefully contain the digits 1-9. Once they input all 9 rows the program should then go through each row and verify and see if it satisfies the conditions of a sudoku game. If it doesnt ... | [
"You can check the rows by converting them to sets\nif set(row) == set(range(1,10)):\n # ok\n ...\n\nyou'll need to convert the row to a str first though\n",
"Ok, I can see room for two loops in this scenario.\nLoopA a loop that gets the input and LoopB a loop that checks the output an example here:\nfrom a... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004040304_python.txt |
Q:
Python OLS calculation
Is there any good library to calculate linear least squares OLS (Ordinary Least Squares) in python?
Thanks.
Edit:
Thanks for the SciKits and Scipy.
@ars: Can X be a matrix? An example:
y(1) = a(1)*x(11) + a(2)*x(12) + a(3)*x(13)
y(2) = a(1)*x(21) + a(2)*x(22) + a(3)*x(23)
..................... | Python OLS calculation | Is there any good library to calculate linear least squares OLS (Ordinary Least Squares) in python?
Thanks.
Edit:
Thanks for the SciKits and Scipy.
@ars: Can X be a matrix? An example:
y(1) = a(1)*x(11) + a(2)*x(12) + a(3)*x(13)
y(2) = a(1)*x(21) + a(2)*x(22) + a(3)*x(23)
...........................................
y(... | [
"Try the statsmodels package. Here's a quick example:\nimport pylab\nimport numpy as np\nimport statsmodels.api as sm\n\nx = np.arange(-10, 10)\ny = 2*x + np.random.normal(size=len(x))\n\n# model matrix with intercept\nX = sm.add_constant(x)\n\n# least squares fit\nmodel = sm.OLS(y, X)\nfit = model.fit()\n\nprint ... | [
9,
4
] | [] | [] | [
"python"
] | stackoverflow_0004040322_python.txt |
Q:
wxPython and StaticBox(Sizer) issue
Recently I've been having an issue with the code shown below and it's been bugging me for a while now. I don't know why it's happening, the only thing I know is that the python code brings up a segfault on the line noted and gdb brings up something about memory. Am I doing somet... | wxPython and StaticBox(Sizer) issue | Recently I've been having an issue with the code shown below and it's been bugging me for a while now. I don't know why it's happening, the only thing I know is that the python code brings up a segfault on the line noted and gdb brings up something about memory. Am I doing something wrong or is this a bug? I'd really l... | [
"On the python side, the Add method has the following arguments:\nAdd(self, item, int proportion=0, int flag=0, int border=0, userData=None)\n\nproportion is not an id (but that silently passes because they are both integers) and flag is not a string.\nCompared to the C++ version a working line would be:\nfgszr.Add... | [
0
] | [] | [] | [
"c++",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0004039372_c++_python_wxpython_wxwidgets.txt |
Q:
Why does this SQLAlchemy example commit changes to the DB?
This example illustrates a mystery I encountered in an application I am building. The application needs to support an option allowing the user to exercise the code without actually committing changes to the DB. However, when I added this option, I discover... | Why does this SQLAlchemy example commit changes to the DB? | This example illustrates a mystery I encountered in an application I am building. The application needs to support an option allowing the user to exercise the code without actually committing changes to the DB. However, when I added this option, I discovered that changes were persisted to the DB even when I did not cal... | [
"tl;dr - The updates are not actually committed to the database-- they are part of an uncommitted transaction in progress.\n\nI made 2 separate changes to your call to create_engine(). (Other than this one line, I'm using your code exactly as posted.)\nThe first was \nengine = create_engine('sqlite://', echo = True... | [
5,
1,
1,
0,
0
] | [] | [] | [
"commit",
"python",
"session",
"sqlalchemy"
] | stackoverflow_0003998546_commit_python_session_sqlalchemy.txt |
Q:
wx.ProgressDialog using a counter instead of a timer
I need to include a progress bar in my wxpython application, but the examples I found use a timer counting down from a fixed time length. Since I have no idea how long it will take a given computer to run my process, I want the progress bar to simply update whe... | wx.ProgressDialog using a counter instead of a timer | I need to include a progress bar in my wxpython application, but the examples I found use a timer counting down from a fixed time length. Since I have no idea how long it will take a given computer to run my process, I want the progress bar to simply update whenever each specific step is completed.
I modified some sam... | [
"Your progressMax is 7 and the loop loops while count is less than 8, but you increment count on the first line of the loop so you have an iteration where count is 8 and that is an illegal value for the progress bar.\nEither change the while condition to count < 7 (conveniently count < progressMax) or move the coun... | [
1
] | [] | [] | [
"progress_bar",
"progressdialog",
"python",
"wxpython"
] | stackoverflow_0004038281_progress_bar_progressdialog_python_wxpython.txt |
Q:
Django: tracking all the database changes with values
I have to implement an application in django which will track all the changes in the database with the previous values,current value,action,date,time, user(who performed the changes) etc.
Is there any application/module available in python or django which can ... | Django: tracking all the database changes with values | I have to implement an application in django which will track all the changes in the database with the previous values,current value,action,date,time, user(who performed the changes) etc.
Is there any application/module available in python or django which can perform these actions with may be after some changes. I hav... | [
"Django-reversion http://github.com/etianen/django-reversion could be an alternative.\n",
"fullhistory seems to do most of what you want - what part of the requirement does it not fulfil? It might be easier to enhance fullhistory.\nAnother option is to do it at the database level, if your database supports loggin... | [
4,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004040656_django_django_models_python.txt |
Q:
signed bitwise arithmetic in Python
I got stuck with the following Python code
>>> a = 0xff
>>> b = 1 << 8
>>> ~a & ~b
-512
Why is it -512? In binary notation it should look like this:
a 0 1111 1111 -> 255
b 01 0000 0000 -> 256
~a 1 0000 0000 -> -256
~b 10 1111 1111 -> -257
~a... | signed bitwise arithmetic in Python | I got stuck with the following Python code
>>> a = 0xff
>>> b = 1 << 8
>>> ~a & ~b
-512
Why is it -512? In binary notation it should look like this:
a 0 1111 1111 -> 255
b 01 0000 0000 -> 256
~a 1 0000 0000 -> -256
~b 10 1111 1111 -> -257
~a&~b 00 0000 0000 -> 0
I expected 0 as ... | [
"Assuming 16-bit integers for convenience (the principle doesn't change for 32 or 64 bit):\na = 0xff = 0000 0000 1111 1111\n~a = -256 = 1111 1111 0000 0000\n\nb = 1<<8 = 0000 0001 0000 0000\n~b = -257 = 1111 1110 1111 1111\n\n-256 = 1111 1111 0000 0000\n-257 = 1111 1110 1111 1111\n-------------------------- &\n-... | [
4
] | [] | [] | [
"bit_manipulation",
"math",
"python"
] | stackoverflow_0004041170_bit_manipulation_math_python.txt |
Q:
A question about Django and Google Apps
Just wondering about this, is it possible to use Django with the Google Apps API's? I have a small organization that uses Google Apps Education Edition. I was thinking about making a small intranet using Django, and I would love if the first page they saw when they logged in... | A question about Django and Google Apps | Just wondering about this, is it possible to use Django with the Google Apps API's? I have a small organization that uses Google Apps Education Edition. I was thinking about making a small intranet using Django, and I would love if the first page they saw when they logged in had a few widgets with their email, calendar... | [
"Yes, it is possible. This is not a question about Django and GAE in particular; you may have more luck searching for tutorials on using Django with generic web APIs.\nHere's one I found almost immediately; it uses the del.icio.us API but the idea is the same.\n",
"Yes, it is. See this help topic.\n"
] | [
0,
0
] | [] | [] | [
"django",
"google_apps",
"python"
] | stackoverflow_0004036321_django_google_apps_python.txt |
Q:
BeautifulSoup is too slow. Can lxml do this?
I've got the following BeautifulSoup code, a bit simplified.
soup = BeautifulSoup(html)
for item in soup.findAll('div',id=compile('^result_')):
q = item.find('a',{'class':'title'})
if q:
...
q = item.find('div',{'class':['one','two']})
if q:
...
I profi... | BeautifulSoup is too slow. Can lxml do this? | I've got the following BeautifulSoup code, a bit simplified.
soup = BeautifulSoup(html)
for item in soup.findAll('div',id=compile('^result_')):
q = item.find('a',{'class':'title'})
if q:
...
q = item.find('div',{'class':['one','two']})
if q:
...
I profiled it, and it's quite slow. I want to try lxml in... | [
"Since lxml supports XPath, I would argue: yes, this is definitely possible.\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"lxml",
"python"
] | stackoverflow_0004041404_beautifulsoup_lxml_python.txt |
Q:
Python verify url goes to a page
I have a list of urls (1000+) which have been stored for over a year now. I want to run through and verify them all to see if they still exist. What is the best / quickest way to check them all and return a list of ones which do not return a site?
A:
this is kind of slow but you... | Python verify url goes to a page | I have a list of urls (1000+) which have been stored for over a year now. I want to run through and verify them all to see if they still exist. What is the best / quickest way to check them all and return a list of ones which do not return a site?
| [
"this is kind of slow but you can use something like this to check if url is a live\nimport urllib2\n\ntry:\n urllib2.urlopen(url)\n return True # URL Exist\nexcept ValueError, ex:\n return False # URL not well formatted\nexcept urllib2.URLError, ex:\n return False # URL don't seem... | [
11,
0
] | [] | [] | [
"python"
] | stackoverflow_0004041443_python.txt |
Q:
Cython problem in Windows XP: "error: Unable to find vcvarsall.bat"
Cython version is 0.13, Python 3.1
I have tried all "solutions" in Cython FAQ, but to no avail. My version of Visual Studio is 7.1 and its directory doesn't contain vcvarsall.bat. Is this problem have a solution?
A:
SO search and you will find a... | Cython problem in Windows XP: "error: Unable to find vcvarsall.bat" | Cython version is 0.13, Python 3.1
I have tried all "solutions" in Cython FAQ, but to no avail. My version of Visual Studio is 7.1 and its directory doesn't contain vcvarsall.bat. Is this problem have a solution?
| [
"SO search and you will find ample discussion on this.\n\nhttps://stackoverflow.com/search?q=vcvarsall.bat\n\n[Edit: based on comment below]\nWhen you run setup.py install on windows, distutils looks for vcvarsall.bat to run.\nAbout vcvarsall.bat\nVCVarsall.bat is Visual Studio Command Prompt tool in Visual Studio.... | [
2
] | [] | [] | [
"cython",
"mingw",
"python"
] | stackoverflow_0004041607_cython_mingw_python.txt |
Q:
Why use def main()?
I've seen some code samples and tutorials that use
def main():
# my code here
if __name__ == "__main__":
main()
But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie
def my_function()
# my code here
def my_function_two... | Why use def main()? | I've seen some code samples and tutorials that use
def main():
# my code here
if __name__ == "__main__":
main()
But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie
def my_function()
# my code here
def my_function_two()
# my code here
# ... | [
"Without the main sentinel, the code would be executed even if the script were imported as a module.\n",
"Everyone else has already answered it, but I think I still have something else to add.\nReasons to have that if statement calling main() (in no particular order):\n\nOther languages (like C and Java) have a m... | [
668,
265,
93,
23,
8
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0004041238_coding_style_python.txt |
Q:
Auto increment of Concatenated alpha-numeric. (Python)
I have defined a function that generates ID. I need to increment the numbers every time I call the function.
So I used max() function to find the last largest value stored in the list.
According to the requirements my ID should also consist of a string in fron... | Auto increment of Concatenated alpha-numeric. (Python) | I have defined a function that generates ID. I need to increment the numbers every time I call the function.
So I used max() function to find the last largest value stored in the list.
According to the requirements my ID should also consist of a string in front of the integers.
So I have concatenated a string with some... | [
"You can strip off the numeric suffix from the string to get a number to increment:\nimport re\n\ndef number_suffix(s):\n \"\"\"Return the number from the end of the string. \"\"\"\n match = re.search(r\"\\d+$\", s)\n if match:\n num = int(match.group(0))\n else:\n num = 0\n return num\... | [
2
] | [] | [] | [
"auto_increment",
"python"
] | stackoverflow_0004041623_auto_increment_python.txt |
Q:
Django: If I added new tables to database, how can I query them?
Django: If I added new tables to database, how can I query them?
Do I need to create the relevant models first? Or django creates it by itself?
More specifically, I installed another django app, it created several database tables in database, and no... | Django: If I added new tables to database, how can I query them? | Django: If I added new tables to database, how can I query them?
Do I need to create the relevant models first? Or django creates it by itself?
More specifically, I installed another django app, it created several database tables in database, and now I want to get some specific data from them? What are the correct app... | [
"I suppose another django app has all model files needed to access those tables, you should just try importing those packages and use this app's models.\n",
"Django doen't follow convention over configuration philosophy. you have to explicitly create the backing model for the table and in the meta tell it about ... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004042286_django_django_admin_django_models_python.txt |
Q:
Django : ORM objects come with nothing in _meta.local_fields
[python 2.6 - django 1.1.1]
Hello.
I'm writing a custom serializer for my django application.
All the objects that I use are proxy objects derived from django model classes and implement special members that I must serialize (hence the custom serializer)... | Django : ORM objects come with nothing in _meta.local_fields | [python 2.6 - django 1.1.1]
Hello.
I'm writing a custom serializer for my django application.
All the objects that I use are proxy objects derived from django model classes and implement special members that I must serialize (hence the custom serializer).
So I've begun to implement a new abstract serializer that inheri... | [
"It seems that proxy objects don't have local_fields set, which would be logical. I've just found something in the existing code (exploiting the django python serializer) that works around the lack of local_fields...\nI think my question is void :-/\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004041543_django_python.txt |
Q:
Why can't nosetests find one the elements in sys.path?
I have a series of unit tests that I'm running with nose. For some of my tests, I'd like to remove a module's path from the sys.path so there is no conflict with what I am testing.
sys.path.remove('/path/to/remove/from/sys/path')
If I run the Python interpre... | Why can't nosetests find one the elements in sys.path? | I have a series of unit tests that I'm running with nose. For some of my tests, I'd like to remove a module's path from the sys.path so there is no conflict with what I am testing.
sys.path.remove('/path/to/remove/from/sys/path')
If I run the Python interpreter and call sys.path, the '/path/to/remove/from/sys/path' i... | [
"Didn't you mean this?\nsys.path.remove('/path/to/remove/from/sys/path')\n\nIf nose can't find it in sys.path then it wasn't there... nose does lots of diddling with sys.path on its own. Why not print sys.path and see what it actually is when run under nose\n",
"Create a script, get_mod_py_path.py, to set the P... | [
1,
0
] | [] | [] | [
"nose",
"nosetests",
"python",
"pythonpath"
] | stackoverflow_0003947464_nose_nosetests_python_pythonpath.txt |
Q:
Where does Python root logger store a log?
I'm using the Freebase Python library. It creates a log before executing:
self.log = logging.getLogger("freebase")
Where is this log in the file system? It's not in the executing directory or tmp.
A:
That call does not store anything. It merely creates a logger objec... | Where does Python root logger store a log? | I'm using the Freebase Python library. It creates a log before executing:
self.log = logging.getLogger("freebase")
Where is this log in the file system? It's not in the executing directory or tmp.
| [
"That call does not store anything. It merely creates a logger object which can be bound and configured however you would like.\nSo if in your Python code, you were to add\nlogging.basicConfig(level=logging.WARNING)\n\nAll warnings and errors would be logged to the standard output (that's what basicConfig does), in... | [
30
] | [] | [] | [
"freebase",
"logging",
"python"
] | stackoverflow_0004042615_freebase_logging_python.txt |
Q:
How can I return the odd numbers of a list, using only recursion in Python?
I do not want to use while or for loops, just want to use recursion to return the odd numbers in a given list. Thanks!
A:
def find_odds(numbers):
if not numbers:
return []
if numbers[0] % 2 == 1:
return [numbers[0]] + find_od... | How can I return the odd numbers of a list, using only recursion in Python? | I do not want to use while or for loops, just want to use recursion to return the odd numbers in a given list. Thanks!
| [
"def find_odds(numbers):\n if not numbers:\n return []\n if numbers[0] % 2 == 1:\n return [numbers[0]] + find_odds(numbers[1:])\n return find_odds(numbers[1:])\n\nNo extra variables or parameters needed.\n",
"def only_odd(L):\n return L[0:L[0]&1]+only_odd(L[1:]) if L else L\n\nThis version is much fas... | [
11,
7,
3,
3,
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0004039374_python_recursion.txt |
Q:
How can I get title & scripts inside a webpage using webkit + gtk?
Here 's my code snippet
import gtk, webkit
window = gtk.Window()
browser = webkit.WebView()
url = "www.google.com"
browser.open(url)
Now I wanna get the web page title, script tags inside. So how can I do that ?
The documentation is not clear at... | How can I get title & scripts inside a webpage using webkit + gtk? |
Here 's my code snippet
import gtk, webkit
window = gtk.Window()
browser = webkit.WebView()
url = "www.google.com"
browser.open(url)
Now I wanna get the web page title, script tags inside. So how can I do that ?
The documentation is not clear at these points and I only found documentation for Objective-C and I am t... | [
"I think the following should work (I can't try it out right now):\ndef title_changed(widget, frame, title):\n print title\n\nbrowser.connect('title-changed', title_changed)\n\nThere is some documentation here and here and two examples in the demo directory from the source tarball.\n",
"It is not bound to the ... | [
1,
0
] | [] | [] | [
"gtk",
"python",
"webkit"
] | stackoverflow_0004038739_gtk_python_webkit.txt |
Q:
Python equivalent to C#'s using statement
Possible Duplicate:
What is the equivalent of the C# “using” block in IronPython?
I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I sup... | Python equivalent to C#'s using statement |
Possible Duplicate:
What is the equivalent of the C# “using” block in IronPython?
I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I suppose there should be checks for None in each o... | [
"Python 2.6 introduced the with statement, which provides for automatic clean up of objects when they leave the with statement. I don't know if the IronPython libraries support it, but it would be a natural fit.\nDup question with authoritative answer: What is the equivalent of the C# \"using\" block in IronPython... | [
9,
2,
0,
0
] | [] | [] | [
"ironpython",
"python",
"using"
] | stackoverflow_0004042995_ironpython_python_using.txt |
Q:
How to interrupt python multithreaded app?
I'm trying to run the following code (it i simplified a bit):
def RunTests(self):
from threading import Thread
import signal
global keep_running
keep_running = True
signal.signal( signal.SIGINT, stop_running )
for i in ran... | How to interrupt python multithreaded app? | I'm trying to run the following code (it i simplified a bit):
def RunTests(self):
from threading import Thread
import signal
global keep_running
keep_running = True
signal.signal( signal.SIGINT, stop_running )
for i in range(0, NumThreads):
thread = Thread(t... | [
"Unlike regular processes, Python doesn't appear to handle signals in a truly asynchronous manner. The 'join()' call is somehow blocking the main thread in a manner that prevents it from responding to the signal. I'm a bit surprised by this since I don't see anything in the documentation indicating that this can/sh... | [
3,
0
] | [] | [] | [
"multithreading",
"python",
"signals"
] | stackoverflow_0004042158_multithreading_python_signals.txt |
Q:
Tkinter window events and properties
I've been searching for information on the following Tkinter window features without success. Platform is Windows, Python 2.7. At the end of this post is code that can be used to explore Tkinter window events.
How can one detect window minimize/maximize events? The event objec... | Tkinter window events and properties | I've been searching for information on the following Tkinter window features without success. Platform is Windows, Python 2.7. At the end of this post is code that can be used to explore Tkinter window events.
How can one detect window minimize/maximize events? The event object returned by binding to a window's <Confi... | [
"Determining window visibility is done with a .winfo_viewable() call. Returns 1 if visible, 0 if not.\nIf you want to prevent the window from resizing, set up your window the way you want, then use\nself.root.minsize(self.root.winfo_reqwidth(), self.root.winfo_reqheight())\nself.root.maxsize(self.root.winfo_reqwidt... | [
2
] | [] | [] | [
"python",
"tkinter",
"user_interface",
"windows"
] | stackoverflow_0004038070_python_tkinter_user_interface_windows.txt |
Q:
Using Python to convert color formats?
I'm working on a Python tool to convert image data into these color formats:
RGB565
RGBA5551
RGBA4444.
What's the simplest way to achieve this?
I've used the Python Imaging Library (PIL) frequently. So I know how to load an image and obtain each pixel value in RGBA8888 form... | Using Python to convert color formats? | I'm working on a Python tool to convert image data into these color formats:
RGB565
RGBA5551
RGBA4444.
What's the simplest way to achieve this?
I've used the Python Imaging Library (PIL) frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversi... | [
"Changing something from 8 to 5 bits is trivial. In 8 bits the value is between 0 and 255, in 5 bits it's between 0 and 31, so all you need to do is divide the value with 8. Or 4 in the case for green in RGB565 mode. Or 16 in RGBA4444 mode as it uses 4 bits per channel, etc.\nEdit: Reading through your question aga... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001119754_python.txt |
Q:
Python How to share a serial port with two different threads (Class A, Class B)
I have a single Python process which is using a serial port (unique resource) which is managed using an instance of a class A. There exists two different threads initialized using instances of classes B and C, which are constantly usin... | Python How to share a serial port with two different threads (Class A, Class B) | I have a single Python process which is using a serial port (unique resource) which is managed using an instance of a class A. There exists two different threads initialized using instances of classes B and C, which are constantly using the serial port resource through the objected already created.
import threading
Cl... | [
"While you could share the serial port using appropriate locking, I wouldn't recommend it. I've written several multi-threaded applications that communicate on the serial port in Python, and in my experience the following approach is better:\n\nHave a single class, in a single thread, manage the actual serial port ... | [
13,
0
] | [] | [] | [
"multithreading",
"python",
"semaphore"
] | stackoverflow_0004043193_multithreading_python_semaphore.txt |
Q:
How do I write text in subscript in the axis labels and the legend?
I have the following axis labels and legend.
plt.ylabel("ratio_2")
plt.xlabel("n_1")
plt.legend(('alpha_1','alpha_2' ), loc = 'best',shadow = True)
A:
Put dollar signs around the formula: plt.xlabel("$n_1$")
A:
The easiest way I know is to ... | How do I write text in subscript in the axis labels and the legend? | I have the following axis labels and legend.
plt.ylabel("ratio_2")
plt.xlabel("n_1")
plt.legend(('alpha_1','alpha_2' ), loc = 'best',shadow = True)
| [
"Put dollar signs around the formula: plt.xlabel(\"$n_1$\")\n",
"The easiest way I know is to enable TeX mode for matplotlib,\nfrom http://www.scipy.org/Cookbook/Matplotlib/UsingTex:\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\n"
] | [
48,
8
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003985827_matplotlib_python.txt |
Q:
HTML table with writable cells?
I've been trying to build a simple GAE app and to be able to manipulate the position of the text on the screen. I asked the same question on several forums; so far with no solution. I apologize if my question has not been clear.
Now I thought of achieving the same functionality wit... | HTML table with writable cells? | I've been trying to build a simple GAE app and to be able to manipulate the position of the text on the screen. I asked the same question on several forums; so far with no solution. I apologize if my question has not been clear.
Now I thought of achieving the same functionality with a grid, like a spreadsheet. Do you ... | [
"There is a jquery plugin called UI Table Edit. That may be a good place to start. Dig around for already implemented grid tools or plugins in javascript that have done most of the work for you. I think Yahoo! has released a nice data grid that allows for editing as well.\n",
"What you are looking for is a dat... | [
2,
1,
0
] | [] | [] | [
"html_table",
"nested_lists",
"python"
] | stackoverflow_0004043844_html_table_nested_lists_python.txt |
Q:
python sockets, what's the best way to handle several connections at once?
What's the best way to handle lots of connections at once in python? The first way I think of is threading, which works but at 10MB of RAM per thread that's rather expensive.
So what other ways are there to handle lots of connections at onc... | python sockets, what's the best way to handle several connections at once? | What's the best way to handle lots of connections at once in python? The first way I think of is threading, which works but at 10MB of RAM per thread that's rather expensive.
So what other ways are there to handle lots of connections at once ?
The only problem I see without using threads is that using the socket.recv()... | [
"A good alternative to threads, if you have a truly large amount of simultaneous connections, is an asychronous/events based approach with callbacks.\nPython already has a very mature and powerful library/framework for this purpose - Twisted. There's also a simpler solution using the standard library asyncore modul... | [
5
] | [] | [] | [
"networking",
"python",
"sockets"
] | stackoverflow_0004044074_networking_python_sockets.txt |
Q:
python: too many parameters provided
could anyone please explain what's wrong with it ? am I doing something wrong ?
>>> class qw:
... def f2x(par1, par2, par3):
... print par1, par2, par3
...
>>> obj = qw()
>>> obj.f2x("123", 13, "wert") Traceback (most recent call last):
File "<stdin>", line... | python: too many parameters provided | could anyone please explain what's wrong with it ? am I doing something wrong ?
>>> class qw:
... def f2x(par1, par2, par3):
... print par1, par2, par3
...
>>> obj = qw()
>>> obj.f2x("123", 13, "wert") Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f2x() takes exa... | [
"You forgot that all member functions get another argument implicitly, which in Python is called self by convention.\nTry:\nclass qw:\n def f2x(self, par1, par2, par3):\n print par1, par2, par3\n\nBut still call it as before:\nobj = qw()\nobj.f2x(\"123\", 13, \"wert\")\n\nIn f2x, self is the object on which the... | [
4,
4,
2
] | [] | [] | [
"class",
"parameter_passing",
"python"
] | stackoverflow_0004044750_class_parameter_passing_python.txt |
Q:
Python: Problem with list editing
Simplified version of my code:
sequence = [['WT_1', 'AAAAAAAA'], ['WT_2', 'BBBBBBB']]
def speciate(sequence):
lineage_1 = []
lineage_2 = []
for i in sequence:
lineage_1.append(i)
for k in sequence:
lineage_2.append(k)
lineage_1[0][0] = 'L1_A'... | Python: Problem with list editing | Simplified version of my code:
sequence = [['WT_1', 'AAAAAAAA'], ['WT_2', 'BBBBBBB']]
def speciate(sequence):
lineage_1 = []
lineage_2 = []
for i in sequence:
lineage_1.append(i)
for k in sequence:
lineage_2.append(k)
lineage_1[0][0] = 'L1_A'
lineage_1[1][0] = 'L1_B'
linea... | [
"You have to make a deep copy (or shallow copy suffices in this case) when you append. Else lineage_1[0][0] and lineage_2[0][0] reference the same object.\nfrom copy import deepcopy\nfor i in sequence:\n lineage_1.append(deepcopy(i))\nfor k in sequence:\n lineage_2.append(deepcopy(k))\n\nSee also: http://docs.p... | [
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004044783_list_python.txt |
Q:
Advice on designing django model with "exclusive" foreign key relationships
I want to design a Task model that can be associated to Project Models, another X model, and other Task models. The obvious choice is a foreign key, but I want any particular instance of that Task model to only be associated to only one of... | Advice on designing django model with "exclusive" foreign key relationships | I want to design a Task model that can be associated to Project Models, another X model, and other Task models. The obvious choice is a foreign key, but I want any particular instance of that Task model to only be associated to only one of those model types, that is, if a Task model has a relationship with a Project mo... | [
"Have a look at Generic relation. It lets you define a foreign key on multiple models. This way your task is only linked to one of your models.\n",
"What I have done is to inherit from a base class on all my models that will be related to tasks. Task models points to that base class on the ForeignKey with unique=... | [
0,
0
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0004035298_django_models_python.txt |
Q:
Python Noob - Silly Question? Works in Python Interpreter, not from CLI
I am hoping this is a simple stupid noob mistake that can be fixed with the addition of a single line of code somewhere.
I'm using pySerial to read in serial data from a USB port and print it out to standard output. I'm running Mac OSX 10.6. I... | Python Noob - Silly Question? Works in Python Interpreter, not from CLI | I am hoping this is a simple stupid noob mistake that can be fixed with the addition of a single line of code somewhere.
I'm using pySerial to read in serial data from a USB port and print it out to standard output. I'm running Mac OSX 10.6. I open terminal and type "python", then the following:
>>> import serial;
>>> ... | [
"In your 1st example, baud rate is an integer but in the 2nd, you don't not convert sys.argv[2] from a string. Try this ser = serial.Serial(serialPort, int(baudRate), timeout=1).\n",
"Is it printing anything? I'd assume it would print:\nlooping...\n<ser.inWaiting() val>\n\nAnd then nothing. Add a print statement... | [
1,
1,
0
] | [] | [] | [
"command_line",
"loops",
"python",
"serial_port"
] | stackoverflow_0004044293_command_line_loops_python_serial_port.txt |
Q:
Get the GMT time given date and UTC offset in python
I have a date string of the following format '%Y%m%d%H%M%S' for example '19981024103115'
and another string of the UTC local offset for example '+0100'
What's the best way in python to convert it to the GMT time
So the result will be '1998-10-24 09:31:15'
A:
Y... | Get the GMT time given date and UTC offset in python | I have a date string of the following format '%Y%m%d%H%M%S' for example '19981024103115'
and another string of the UTC local offset for example '+0100'
What's the best way in python to convert it to the GMT time
So the result will be '1998-10-24 09:31:15'
| [
"You could use dateutil for that:\n>>> from dateutil.parser import parse\n>>> dt = parse('19981024103115+0100')\n>>> dt\ndatetime.datetime(1998, 10, 24, 10, 31, 15, tzinfo=tzoffset(None, 3600))\n>>> dt.utctimetuple()\ntime.struct_time(tm_year=1998, tm_mon=10, tm_mday=24, tm_hour=9, tm_min=31, tm_sec=15, tm_wday=5, ... | [
4,
0
] | [] | [] | [
"datetime",
"gmt",
"python",
"utc"
] | stackoverflow_0004044863_datetime_gmt_python_utc.txt |
Q:
Django - Threading in views without hanging the server
One of my applications in my Django project require each request/visitor to that instance to have their own thread. This might sound confusing, so I'll describe what I'm looking to accomplish in a case based scenario, with steps:
User visits application
Threa... | Django - Threading in views without hanging the server | One of my applications in my Django project require each request/visitor to that instance to have their own thread. This might sound confusing, so I'll describe what I'm looking to accomplish in a case based scenario, with steps:
User visits application
Thread starts
Until the thread finishes, that user's server insta... | [
"But why you need thread? why can't you just do whatever you want to do in django view?\nIf you are using servers like apache with mod-wsgi you should be able to have good control over number of process and threads , so that part shouldn't be your worry or should not be in django views.\n",
"I dread to think why ... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"multithreading",
"python"
] | stackoverflow_0002565484_django_django_models_multithreading_python.txt |
Q:
How do you run a complex sql script within a python program?
I have a large SQL script that creates my database (multiple tables, triggers, and such. Using MySQL), and I need to execute that script from within a python program. My old code did this:
sql_file = open(os.path.join(self.path_to_sql, filename), 'r')
... | How do you run a complex sql script within a python program? | I have a large SQL script that creates my database (multiple tables, triggers, and such. Using MySQL), and I need to execute that script from within a python program. My old code did this:
sql_file = open(os.path.join(self.path_to_sql, filename), 'r')
sql_text = sql_file.read()
sql_stmts = sql_text.split(';')
for s i... | [
"(not a python solution) you can use \n os.system('mysql < etc')\n\nooh, edit (python solution):\nif you have the query broken up by line, you can close and reopen the cursor and execute by line.\nredit: sorry, only skimmed your first paragraph. seems like you were doing this sort of thing at first.\n"
] | [
2
] | [
"This doesn't seem like a very good way to structure a multi-language program. \nBrandon's answer is really the right way to go if all you're doing is just executing a big chunk of sql. \nOn the other hand, if you're doing stuff with the results of queries throughout the process of the job, then you shouldn't try... | [
-1
] | [
"mysql",
"python",
"sql"
] | stackoverflow_0004045332_mysql_python_sql.txt |
Q:
How can I properly read out spin buttons in pyGTK?
For a small timer app I want to write a GTK interface where I can set the desired time. Here is a picture of the interface:
However, I am having trouble reading out the fields of the spin buttons. My envisaged procedure for this is the following:
Read out the bu... | How can I properly read out spin buttons in pyGTK? | For a small timer app I want to write a GTK interface where I can set the desired time. Here is a picture of the interface:
However, I am having trouble reading out the fields of the spin buttons. My envisaged procedure for this is the following:
Read out the buttons using methods for each button
Here is one of the... | [
"You try to pass the attribute self.rHours to the connect method, but at that point the attribute doesn't exist yet (the clicked handlers haven't executed yet).\nNote that even if you fill in self.rHours before calling connect, it will pass the value at the time of connecting, not at the time of the handler executi... | [
2,
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0004044759_pygtk_python.txt |
Q:
Python Tkinter Help Menu
I have a paragraph of help information that I would like to display in a window with an "ok" button at the bottom. My issue is formatting...I want to be able to simply set the paragraph equal to a variable and then send that variable to a message box widget. By default, it formats laterall... | Python Tkinter Help Menu | I have a paragraph of help information that I would like to display in a window with an "ok" button at the bottom. My issue is formatting...I want to be able to simply set the paragraph equal to a variable and then send that variable to a message box widget. By default, it formats laterally and in a very ugly manner. A... | [
"Use a text widget with word wrapping, and either define your string more accurately or do a little post-processing to remove all that extra whitespace. Using the code from this answer makes it easy to use multiple colors, fonts, etc. \nFor example:\nimport Tkinter as tk\nimport re\n\nclass CustomText(tk.Text):\n ... | [
1
] | [] | [] | [
"menu",
"python",
"tkinter"
] | stackoverflow_0004028446_menu_python_tkinter.txt |
Q:
Python: Self is not defined
class a(object):
def __init__(self):
self.b = 1
self.c = 2
This gives the error: NameError: name 'self' is not defined
I looked at a previous post, but the error was for a different reason. Any help with this?
A:
I'm assuming the single space before def __init__(se... | Python: Self is not defined | class a(object):
def __init__(self):
self.b = 1
self.c = 2
This gives the error: NameError: name 'self' is not defined
I looked at a previous post, but the error was for a different reason. Any help with this?
| [
"I'm assuming the single space before def __init__(self): is actually a tab in your file and displayed as four spaces by your editor.\nHowever python interprets a tab as 8 spaces, so the following two lines (which are indented by 8 spaces) are seen by python to be at the same level of indentation as the def.\nThis ... | [
12,
2
] | [] | [] | [
"python"
] | stackoverflow_0004045599_python.txt |
Q:
Scons Hierarchical Builds with Repository directory
I have an SCons project set up as follows:
proj/
SConstruct
src/
c/
h/
app1/SConscript
app2/SConscript
...
All source/header files for each application are located in src/c and src/h.
At first step I created a SConstruct in a... | Scons Hierarchical Builds with Repository directory | I have an SCons project set up as follows:
proj/
SConstruct
src/
c/
h/
app1/SConscript
app2/SConscript
...
All source/header files for each application are located in src/c and src/h.
At first step I created a SConstruct in app1 which use the Repository function.
...
src=Split("... | [
"SCons is looking for your source files in the app1 directory. If you specify the sources like this:\nsrc=Split(\"#main.c #first.c #second.c\")\n\nthen scons will search the Repositories for the source files. \nA couple extra thoughts:\n\nYou may want main.c to be in the app1 directory to avoid conflicts with main.... | [
0
] | [] | [] | [
"python",
"scons"
] | stackoverflow_0004043689_python_scons.txt |
Q:
Is there Python PDF metadata writing library for Windows?
Can someone point me to Python PDF package that can do metadata writing?
I found Python XMP Toolkit, but building Exempi on cygwin is nightmare I want to avoid.
A:
You can modify pdf docinfo metadata, (not xmp metadata) in either of the following ways:
p... | Is there Python PDF metadata writing library for Windows? | Can someone point me to Python PDF package that can do metadata writing?
I found Python XMP Toolkit, but building Exempi on cygwin is nightmare I want to avoid.
| [
"You can modify pdf docinfo metadata, (not xmp metadata) in either of the following ways:\n\npdfrw seems to have some support for this (not a lot of documentation, but looking at the alter.py example, it seems to be possible). \nThis SO question uses pyPdf library to make a new pdf with the desired metadata: Change... | [
3,
0
] | [] | [] | [
"pdf",
"python"
] | stackoverflow_0004003935_pdf_python.txt |
Q:
converting bibtex files to html with python (maybe pybtex?)
Hi I want to parse a bibtex publications file and sort for specific fields (e.g. year) and filter certain content, to then put it on a website. I came across pybtex, which works as far as reading and parsing the bibtex file, but it is basically not docume... | converting bibtex files to html with python (maybe pybtex?) | Hi I want to parse a bibtex publications file and sort for specific fields (e.g. year) and filter certain content, to then put it on a website. I came across pybtex, which works as far as reading and parsing the bibtex file, but it is basically not documented and I can't figure out how to sort the entries.
Is pybtex th... | [
"Found a solution, this sorts the entries in a descending order using pybtex, newest publications go first:\nfrom pybtex.database.input import bibtex\nfrom operator import itemgetter, attrgetter\nimport pprint\nparser = bibtex.Parser()\nbib_data = parser.parse_file('ref.bib')\n\ndef sort_by_year(y, x):\n return ... | [
12
] | [] | [] | [
"bibtex",
"html",
"parsing",
"python",
"text_parsing"
] | stackoverflow_0004038703_bibtex_html_parsing_python_text_parsing.txt |
Q:
Tkinter buttons help
I have a class with a button, it runs the command automatically when the gui is constructed (which i dont want it to do) but then doesnt work again after. What am I doing wrong? Builtin commands such as endcommand work as they should.
relevant excerpts (ignore the indent problem at the very be... | Tkinter buttons help | I have a class with a button, it runs the command automatically when the gui is constructed (which i dont want it to do) but then doesnt work again after. What am I doing wrong? Builtin commands such as endcommand work as they should.
relevant excerpts (ignore the indent problem at the very beginning)
class GuiPart(obj... | [
"When you do this:\ncommand=self.updateValues()\n\nYou are calling the function self.updateValues (because of the ()). The result of that function call is being assigned to the command attribute which is not what you want. You need to remove the () so that the command attribute gets a reference to the method rather... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004046118_python_tkinter.txt |
Q:
What is the best way to serve small static images?
Right now I'm base 64 encoding them and using data uris. The idea was that this will somehow lower the number of requests the browser needs to make. Does this bucket hold any water?
What is the best way of serving images in general? DB, from FS, S3?
I am most inte... | What is the best way to serve small static images? | Right now I'm base 64 encoding them and using data uris. The idea was that this will somehow lower the number of requests the browser needs to make. Does this bucket hold any water?
What is the best way of serving images in general? DB, from FS, S3?
I am most interested in python and java based answers, but all are wel... | [
"I would definitely take a look at CSS Image Sprites, decent write-ups here and here.\nThe concept is pretty simple, combine your images into one, show only the slice you need as a CSS background. This lets you lower the number of HTTP requests from many images into one or more (group your small images in sprite m... | [
13,
3,
2,
1
] | [] | [] | [
"image",
"java",
"javascript",
"python"
] | stackoverflow_0004046242_image_java_javascript_python.txt |
Q:
How do you do string interpolation with a URL that contains formatting characters?
I'm trying to use URLLIB2 to open a URL and read back the contents into an array. The issue seems to be that you cannot use string interpolation in a URL that has formatting characters such as %20 for space, %3C for '<'. The URL in ... | How do you do string interpolation with a URL that contains formatting characters? | I'm trying to use URLLIB2 to open a URL and read back the contents into an array. The issue seems to be that you cannot use string interpolation in a URL that has formatting characters such as %20 for space, %3C for '<'. The URL in question has spaces and a bit of xml in it.
My code is pretty simple, looks something li... | [
"You can double the % signs\nurl = 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%%3Crequest%%20configVersion=%%222%%22%%20guid=%%22{%s}%%22' % (ns, guid)\n\nor you can use .format() method\nurl = 'http://{hostname}/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{i... | [
7,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004044754_python.txt |
Q:
Ignore optparse if value is given
I would like to have the ability to pass an argument w/o having to specify an option for optparse. If I do pass an option, it has to be a known option or else the script will fail.
Rsync the following file to destination
myscript.py filename
Rsync the following folder to destina... | Ignore optparse if value is given | I would like to have the ability to pass an argument w/o having to specify an option for optparse. If I do pass an option, it has to be a known option or else the script will fail.
Rsync the following file to destination
myscript.py filename
Rsync the following folder to destination (all this is figured out in functi... | [
"I am always a fan of being explicit, but you can short circuit optparse.\n# args[0] is always the executable's name\nif len(args) > 1:\n parser.parse_args(args, options)\nelse:\n #open file\n\n",
"Treat -f as an option with no argument and use it to switch the behavior of the positional argument (i.e. fold... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004046162_python.txt |
Q:
good refactoring or bad?
Given the following code:
status = row[COL_STATUS]
if status == "idle":
row[COL_EDITABLE] = True
row[COL_FONTSTYLE] = pango.STYLE_NORMAL
row[COL_WEIGHT] = pango.WEIGHT_NORMAL
elif status == "DCed":
row[COL_EDITABLE] = True
row[COL_FONTST... | good refactoring or bad? | Given the following code:
status = row[COL_STATUS]
if status == "idle":
row[COL_EDITABLE] = True
row[COL_FONTSTYLE] = pango.STYLE_NORMAL
row[COL_WEIGHT] = pango.WEIGHT_NORMAL
elif status == "DCed":
row[COL_EDITABLE] = True
row[COL_FONTSTYLE] = pango.STYLE_ITALIC
... | [
"What about using objects and doing something akin to \"Replace Type Code With Subclasses\"?\nhttp://www.refactoring.com/catalog/replaceTypeCodeWithSubclasses.html\n",
"What you gain in conciseness you lose in readability. In the current example, I can easily tell what goes where. In the new code, I have to think... | [
4,
3
] | [] | [] | [
"coding_style",
"python",
"refactoring"
] | stackoverflow_0004046468_coding_style_python_refactoring.txt |
Q:
Django Paginator not working beyond first page
As mentioned in the title, my paginator doesn't show anything when I click to go to a page beyond the first.
First, let me describe my page in general:
Its function is to get a request input from the user specifying the period interval from which he wants to see a bun... | Django Paginator not working beyond first page | As mentioned in the title, my paginator doesn't show anything when I click to go to a page beyond the first.
First, let me describe my page in general:
Its function is to get a request input from the user specifying the period interval from which he wants to see a bunch of "call records" along with other filters (this ... | [
"\nMy question is how do I get the\n current window URL using django\n templates and not javascript? Thank\n you.\n\nit's not necessary the right way to do it, but you can check this post\nbut i will suggest that you shouldn't mix the filter with the pagination.\nrather that you can use AJAX when doing filtering... | [
1,
1
] | [] | [] | [
"django",
"pagination",
"python"
] | stackoverflow_0004045743_django_pagination_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.