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 to find the url using the referer and the href in Python?
Suppose I have
window_location = 'http://stackoverflow.com/questions/ask'
href = '/users/48465/jader-dias'
I want to obtain
link = 'http://stackoverflow.com/users/48465/jader-dias'
How do I do it in Python?
It have to work just as it works in the brow... | How to find the url using the referer and the href in Python? | Suppose I have
window_location = 'http://stackoverflow.com/questions/ask'
href = '/users/48465/jader-dias'
I want to obtain
link = 'http://stackoverflow.com/users/48465/jader-dias'
How do I do it in Python?
It have to work just as it works in the browser
| [
">>> import urlparse\n>>> urlparse.urljoin('http://stackoverflow.com/questions/ask',\n... '/users/48465/jader-dias')\n'http://stackoverflow.com/users/48465/jader-dias'\n\nFrom the doc page of urlparse.urljoin:\n\nurlparse.urljoin(base, url[,\n allow_fragments])\nConstruct a full (“absolute”) URL b... | [
6
] | [] | [] | [
"href",
"python",
"regex",
"string",
"url"
] | stackoverflow_0001250371_href_python_regex_string_url.txt |
Q:
@Rails users: have you tried web2py? Pros? Cons?
web2py to is a Python framework but shares the "convention over configuration" design that Ruby on Rails has. On the plus side it packages a lot more functionality with its s standard distribution and we claim it is faster and easier to use.
Has any Rails user trie... | @Rails users: have you tried web2py? Pros? Cons? | web2py to is a Python framework but shares the "convention over configuration" design that Ruby on Rails has. On the plus side it packages a lot more functionality with its s standard distribution and we claim it is faster and easier to use.
Has any Rails user tried it? What is your impression?
No rants please. Just t... | [
"c'mon guys... your only argument is \"Technical differences are rather irrelevant.\" and \"it don't matter what web framework you use\"? I disagree. The size of the users base has more to do with marketing and how long a framework has been around. By that argument ASP and PHP are better than Rails.\nHas anybo... | [
11,
1,
0
] | [] | [] | [
"python",
"ruby_on_rails",
"web2py"
] | stackoverflow_0000327101_python_ruby_on_rails_web2py.txt |
Q:
python urllib, how to watch messages?
How can I watch the messages being sent back and for on urllib shttp requests? If it were simple http I would just watch the socket traffic but of course that won't work for https. Is there a debug flag I can set that will do this?
import urllib
params = urllib.urlencode({'s... | python urllib, how to watch messages? | How can I watch the messages being sent back and for on urllib shttp requests? If it were simple http I would just watch the socket traffic but of course that won't work for https. Is there a debug flag I can set that will do this?
import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib... | [
"You can always do a little bit of mokeypatching\nimport httplib\n\n# override the HTTPS request class\n\nclass DebugHTTPS(httplib.HTTPS):\n real_putheader = httplib.HTTPS.putheader\n def putheader(self, *args, **kwargs):\n print 'putheader(%s,%s)' % (args, kwargs)\n result = self.real_putheader... | [
2,
1
] | [] | [] | [
"https",
"python",
"urllib"
] | stackoverflow_0001250965_https_python_urllib.txt |
Q:
Creating alternative login to Google Users for Google app engine
How does one handle logging in and out/creating users, without using Google Users? I'd like a few more options then just email and password. Is it just a case of making a user model with the fields I need? Is that secure enough?
Alternatively, is the... | Creating alternative login to Google Users for Google app engine | How does one handle logging in and out/creating users, without using Google Users? I'd like a few more options then just email and password. Is it just a case of making a user model with the fields I need? Is that secure enough?
Alternatively, is there a way to get the user to log in using the Google ID, but without be... | [
"I recommend using OpenID, see here for more -- just like Stack Overflow does!-)\n",
"If you roll your own user model, you're going to need to do your own session handling as well; the App Engine Users API creates login sessions for you behind the scenes. \nAlso, while this should be obvious, you shouldn't store... | [
8,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"model_view_controller",
"python"
] | stackoverflow_0001250437_google_app_engine_google_cloud_datastore_model_view_controller_python.txt |
Q:
How to store regular expressions in the Google App Engine datastore?
Regular Expressions are usually expressed as strings, but they also have properties (ie. single line, multi line, ignore case). How would you store them? And for compiled regular expressions, how to store it?
Please note that we can write custom ... | How to store regular expressions in the Google App Engine datastore? | Regular Expressions are usually expressed as strings, but they also have properties (ie. single line, multi line, ignore case). How would you store them? And for compiled regular expressions, how to store it?
Please note that we can write custom property classes: http://googleappengine.blogspot.com/2009/07/writing-cust... | [
"I'm not sure if Python supprts it, but in .net regex, you can specify these options within the regex itself:\n(?si)^a.*z$\n\nwould specify single-line, ignore case.\nIndeed, the Python docs describe such a mechanism here: http://docs.python.org/library/re.html\nTo recap: (cut'n'paste from link above)\n(?iLmsux)\n(... | [
3,
3,
2
] | [] | [] | [
"customproperty",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001250313_customproperty_google_app_engine_google_cloud_datastore_python.txt |
Q:
Any reason why socket.send() hangs?
I'm writing an mini FTP server in Python that exposes an underlying database as if it was FTP. The flow is something like this:
sock.send("150 Here's the file you wanted\r\n")
proc = Popen2(...)
for parts in data:
data_sock.send(parts)
proc.kill()
sock.send("226 There's the... | Any reason why socket.send() hangs? | I'm writing an mini FTP server in Python that exposes an underlying database as if it was FTP. The flow is something like this:
sock.send("150 Here's the file you wanted\r\n")
proc = Popen2(...)
for parts in data:
data_sock.send(parts)
proc.kill()
sock.send("226 There's the file you wanted\r\n")
data_sock.shutdown... | [
"Hard to say from this code fragment and not knowing the client, but is it possible that your sending of 150 (indicating a new data channel), not 125 (indicating use of existing data channel) confuses the client and it simply does not start reading the data?\nHave you had a look of pyftpdlib as an alternative for r... | [
1,
0,
0
] | [] | [] | [
"ftp",
"python",
"sockets"
] | stackoverflow_0001250979_ftp_python_sockets.txt |
Q:
Python imports: Will changing a variable in "child" change variable in "parent"/other children?
Suppose you have 3 modules, a.py, b.py, and c.py:
a.py:
v1 = 1
v2 = 2
etc.
b.py:
from a import *
c.py:
from a import *
v1 = 0
Will c.py change v1 in a.py and b.py? If not, is there a way to do it?
A:
All that a sta... | Python imports: Will changing a variable in "child" change variable in "parent"/other children? | Suppose you have 3 modules, a.py, b.py, and c.py:
a.py:
v1 = 1
v2 = 2
etc.
b.py:
from a import *
c.py:
from a import *
v1 = 0
Will c.py change v1 in a.py and b.py? If not, is there a way to do it?
| [
"All that a statement like:\nv1 = 0\n\ncan do is bind the name v1 to the object 0. It can't affect a different module.\nIf I'm using unfamiliar terms there, and I guess I probably am, I strongly recommend you read Fredrik Lundh's excellent article Python Objects: Reset your brain.\n",
"The from ... import * form... | [
5,
2,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0001251611_import_python.txt |
Q:
Python Class vs. Module Attributes
I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then w... | Python Class vs. Module Attributes | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have ... | [
"#4: \nI never use class attributes to initialize default instance attributes (the ones you normally put in __init__). For example:\nclass Obj(object):\n def __init__(self):\n self.users = 0\n\nand never:\nclass Obj(object):\n users = 0\n\nWhy? Because it's inconsistent: it doesn't do what you want w... | [
7,
4,
2,
1
] | [] | [] | [
"attributes",
"class_design",
"module",
"python"
] | stackoverflow_0001250779_attributes_class_design_module_python.txt |
Q:
Django + Jquery, expanding AJAX div
How can I, when a user clicks a link, open a div right underneath the link which loads it's content via AJAX?
Thanks for the help; I cannot find out how to. Just statically filling the div on the server side while loading the page works fine, but it's too much content for that.... | Django + Jquery, expanding AJAX div | How can I, when a user clicks a link, open a div right underneath the link which loads it's content via AJAX?
Thanks for the help; I cannot find out how to. Just statically filling the div on the server side while loading the page works fine, but it's too much content for that.
I'm kind of looking for a specific Djan... | [
"jQuery.load does exactly that:\n$(\"div#my-container\").load(\"/url/to/content/ #content-id\")\n\nthis fetches the content from /url/to/content/, filters it by #content-id and injects the result into div#my-container.\nedit: there's really nothing Django-specific about this, since it's all client-side. But if you ... | [
13,
1
] | [] | [] | [
"django",
"jquery",
"python"
] | stackoverflow_0001252275_django_jquery_python.txt |
Q:
How to check null value for UserProperty in Google App Engine
In Google App Engine, datastore modelling, I would like to ask how can I check for null value of a property with class UserProperty?
for example:
I have this code:
class Entry(db.Model):
title = db.StringProperty()
description = db.StringProperty()
... | How to check null value for UserProperty in Google App Engine | In Google App Engine, datastore modelling, I would like to ask how can I check for null value of a property with class UserProperty?
for example:
I have this code:
class Entry(db.Model):
title = db.StringProperty()
description = db.StringProperty()
author = db.UserProperty()
editor = db.UserProperty()
creatio... | [
"query = db.GqlQuery(\"SELECT * FROM Entry WHERE editor > :1\",None)\n\nHowever, you can't ORDER BY one column and have an inequality condition on another column: that's a well-known GAE limitation and has nothing to do with the property being a UserProperty nor with the inequality check you're doing being with Non... | [
13
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001252196_google_app_engine_google_cloud_datastore_python.txt |
Q:
Controlling getter and setter for a python's class
Consider the following class :
class Token:
def __init__(self):
self.d_dict = {}
def __setattr__(self, s_name, value):
self.d_dict[s_name] = value
def __getattr__(self, s_name):
if s_name in self.d_dict.keys():
ret... | Controlling getter and setter for a python's class | Consider the following class :
class Token:
def __init__(self):
self.d_dict = {}
def __setattr__(self, s_name, value):
self.d_dict[s_name] = value
def __getattr__(self, s_name):
if s_name in self.d_dict.keys():
return self.d_dict[s_name]
else:
raise ... | [
"You need to special-case d_dict.\nAlthough of course, in the above code, all you do is replicate what any object does with __dict__ already, so it's pretty pointless. Do I guess correctly if you intended to special case some attributes and actally use methods for those?\nIn that case, you can use properties.\nclas... | [
3,
3,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001241703_python.txt |
Q:
new django app's from 1.1 causing 500 error
i'm running on wsgi on centos 5...
i've recently updated locally from 1.0 to 1.1
I updated the server using svn update
now when I apply a new app developed locally to the server it returns with a 500 error.
all i'm doing is python manage.py startapp appname
adding the ... | new django app's from 1.1 causing 500 error | i'm running on wsgi on centos 5...
i've recently updated locally from 1.0 to 1.1
I updated the server using svn update
now when I apply a new app developed locally to the server it returns with a 500 error.
all i'm doing is python manage.py startapp appname
adding the app into installed_apps in the settings file and ... | [
"Check also the list at http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges.\n",
"Didn't we solve this for you in IRC the other day? If not, there was someone with the same OS and vague problem description.\nTurned out to be a third-party app causing the problem, not the newly added one (which a revie... | [
1,
0
] | [] | [] | [
"centos",
"django",
"python"
] | stackoverflow_0001235777_centos_django_python.txt |
Q:
Portable command execution syntax implemented in Python
Python is not a pretty good language in defining a set of commands to run. Bash is. But Bash does not run naively on Windows.
Background: I am trying to build a set of programs - with established dependency relationships between them - on mac/win/linux. Somet... | Portable command execution syntax implemented in Python | Python is not a pretty good language in defining a set of commands to run. Bash is. But Bash does not run naively on Windows.
Background: I am trying to build a set of programs - with established dependency relationships between them - on mac/win/linux. Something like macports but should work on all the three platforms... | [
"Sounds like you need some combination of PyParsing and Python Subprocess.\nI find subprocess a little confusing, despite the MOTW about it, so I use this kind of wrapper code a lot.\nfrom subprocess import Popen, PIPE\n\ndef shell(args, input=None):\n p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n s... | [
2,
1,
0
] | [] | [] | [
"command",
"cross_platform",
"python",
"shell"
] | stackoverflow_0001249165_command_cross_platform_python_shell.txt |
Q:
sort dictionary by another dictionary
I've been having a problem with making sorted lists from dictionaries.
I have this list
list = [
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'},
d = {'file_name':'thatfile.fl... | sort dictionary by another dictionary | I've been having a problem with making sorted lists from dictionaries.
I have this list
list = [
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'},
d = {'file_name':'thatfile.flt', 'item_name':'teapot', 'item_height':'6.... | [
"The first code box has invalid Python syntax (I suspect the d = parts are extraneous...?) as well as unwisely trampling on the built-in name list.\nAnyway, given for example:\nd = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', \n 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'r... | [
11
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0001252481_dictionary_python_sorting.txt |
Q:
Python: Zope's BTree OOSet, IISet, etc... Effective for this requirement?
I asked another question:
https://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python
where I was trying to determine the best approach for sorting 1 million records. In my case I need to be able to add additional ite... | Python: Zope's BTree OOSet, IISet, etc... Effective for this requirement? | I asked another question:
https://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python
where I was trying to determine the best approach for sorting 1 million records. In my case I need to be able to add additional items to the collection and have them resorted. It was suggested that I try using... | [
"I don't think BTrees or other traditional sorted data structures (red-black trees, etc) will help you, because they keep order by key, not by corresponding value -- in other words, the field they guarantee as unique is the same one they order by. Your requirements are different, because you want uniqueness along o... | [
1,
1
] | [] | [] | [
"python",
"zope"
] | stackoverflow_0001183428_python_zope.txt |
Q:
How to make translucent sprites in pygame
I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame... | How to make translucent sprites in pygame | I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame code, but Google is of no help to me.
| [
"After loading the image, you will need to enable an alpha channel on the Surface. that will look a little like this:\nbackground = pygame.Display.set_mode()\nmyimage = pygame.image.load(\"path/to/image.bmp\").convert_alpha(background)\n\nThis will load the image and immediately convert it to a pixel format suitab... | [
4,
2,
2,
1
] | [] | [] | [
"graphics",
"pygame",
"python",
"sprite"
] | stackoverflow_0001247921_graphics_pygame_python_sprite.txt |
Q:
Writing Windows GUI applications with embedded Python scripts
What would be the optimal way to develop a basic graphical application for Windows based on a Python console script? It would be great if the solution could be distributed as a standalone directory, containing the .exe file.
A:
As far as I understand ... | Writing Windows GUI applications with embedded Python scripts | What would be the optimal way to develop a basic graphical application for Windows based on a Python console script? It would be great if the solution could be distributed as a standalone directory, containing the .exe file.
| [
"As far as I understand your question, you want to write a graphical windows application in Python, to do this I suggest using wxPython and then py2exe to create a standalone exe that can run on any machine without requiring python to be installed\nThe following tutorial shows everything step by step: Quickly Creat... | [
8,
3,
2
] | [] | [] | [
"python",
"user_interface",
"windows"
] | stackoverflow_0001251260_python_user_interface_windows.txt |
Q:
Is it possible to update an entry on Google App Engine datastore through the object's dictionary?
I tried the following code and it didn't work:
class SourceUpdate(webapp.RequestHandler):
def post(self):
id = int(self.request.get('id'))
source = Source.get_by_id(id)
for property in self.request.argum... | Is it possible to update an entry on Google App Engine datastore through the object's dictionary? | I tried the following code and it didn't work:
class SourceUpdate(webapp.RequestHandler):
def post(self):
id = int(self.request.get('id'))
source = Source.get_by_id(id)
for property in self.request.arguments():
if property != 'id':
source.__dict__[property] = self.request.get(property)
s... | [
"You're bypassing the __setattr__-like functionality that the models' metaclass (type(type(source))) is normally using to deal with attribute-setting properly. Change your inner loop to:\nfor property in self.request.arguments():\n if property != 'id':\n setattr(source, property, self.request.get(property))\n\... | [
2,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001252092_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python leaking memory while using PyQt and matplotlib
I've created a small PyQt based utility in Python that creates PNG graphs using matplotlib when a user clicks a button. Everything works well during the first few clicks, however each time an image is created, the application's memory footprint grows about 120 ... | Python leaking memory while using PyQt and matplotlib | I've created a small PyQt based utility in Python that creates PNG graphs using matplotlib when a user clicks a button. Everything works well during the first few clicks, however each time an image is created, the application's memory footprint grows about 120 MB, eventually crashing Python altogether.
How can I recove... | [
"It seems that some backends are leaking memory. Try setting your backend explicitly, e.g.\nimport matplotlib\nmatplotlib.use('Agg') # before import pylab\nimport pylab\n\n",
"The pyplot interface is meant for easy interactive use, but for embedding in an application the object-oriented API is better. For example... | [
7,
6
] | [] | [] | [
"matplotlib",
"memory_leaks",
"pyqt",
"python"
] | stackoverflow_0001249182_matplotlib_memory_leaks_pyqt_python.txt |
Q:
Avoid program exit on I/O error
I have a Python script using shutil.copy2 extensively. Since I use it to copy files over the network, I get too frequent I/O errors, which lead to the abortion of my program's execution:
Traceback (most recent call last):
File "run_model.py", line 46, in <module>
main()
File... | Avoid program exit on I/O error | I have a Python script using shutil.copy2 extensively. Since I use it to copy files over the network, I get too frequent I/O errors, which lead to the abortion of my program's execution:
Traceback (most recent call last):
File "run_model.py", line 46, in <module>
main()
File "run_model.py", line 41, in main
... | [
"Which block is giving the error? Just wrap a try/except around it:\ndef check_file(file, size=0):\n try:\n if not os.path.exists(file):\n return False\n if (size != 0 and os.path.getsize(file) != size):\n return False\n return True\n except IOError:\n return... | [
8,
6
] | [] | [] | [
"python",
"shutil"
] | stackoverflow_0001254292_python_shutil.txt |
Q:
string quoting issues in doctests
When I run doctests on different Python versions (2.5 vs 2.6) and different plattforms (FreeBSD vs Mac OS) strings get quoted differently:
Failed example:
decode('{"created_by":"test","guid":123,"num":5.00}')
Expected:
{'guid': 123, 'num': Decimal("5.00"), 'created_by': 't... | string quoting issues in doctests | When I run doctests on different Python versions (2.5 vs 2.6) and different plattforms (FreeBSD vs Mac OS) strings get quoted differently:
Failed example:
decode('{"created_by":"test","guid":123,"num":5.00}')
Expected:
{'guid': 123, 'num': Decimal("5.00"), 'created_by': 'test'}
Got:
{'guid': 123, 'num': Dec... | [
"This is actually because the decimal module's source code has changed: In python 2.4 and python2.5 the decimal.Decimal.__repr__ function contains:\nreturn 'Decimal(\"%s\")' % str(self)\n\nwhereas in python2.6 it contains:\nreturn \"Decimal('%s')\" % str(self)\n\nSo in this case the best thing to do is just to prin... | [
4,
0
] | [] | [] | [
"doctest",
"python",
"testing"
] | stackoverflow_0001254187_doctest_python_testing.txt |
Q:
Python API to fetch PGP public key from key server?
Is there any Python API which can fetch a PGP public key from the public key server?
A:
You can use HTTP (urllib2 and beautiful soup would be my choice) if you're querying the MIT PGP keyserver.
http://pgp.mit.edu/extracthelp.html
| Python API to fetch PGP public key from key server? | Is there any Python API which can fetch a PGP public key from the public key server?
| [
"You can use HTTP (urllib2 and beautiful soup would be my choice) if you're querying the MIT PGP keyserver.\nhttp://pgp.mit.edu/extracthelp.html\n"
] | [
3
] | [] | [] | [
"pgp",
"python"
] | stackoverflow_0001254425_pgp_python.txt |
Q:
Python and web-tags regex
i have need webpage-content. I need to get some data from it. It looks like:
< div class="deg">DATA< /div>
As i understand, i have to use regex, but i can't choose one.
I tried the code below but had no any results. Please, correct me:
regexHandler = re.compile('(<div class="deg">(?P<di... | Python and web-tags regex | i have need webpage-content. I need to get some data from it. It looks like:
< div class="deg">DATA< /div>
As i understand, i have to use regex, but i can't choose one.
I tried the code below but had no any results. Please, correct me:
regexHandler = re.compile('(<div class="deg">(?P<div class="deg">.*?)</div>)')
res... | [
"I suggest using a good HTML parser (such as BeautifulSoup -- but for your purposes, i.e. with well-formed HTML as input, the ones that come with the Python standard library, such as HTMLParser, should also work well) rather than raw REs to parse HTML.\nIf you want to persist with the raw RE approach, the pattern:\... | [
6,
3,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001252316_python_regex.txt |
Q:
Non-editable text box in wxPython
How to create a non-editable text box with no cursor in wxPython to dump text in?
A:
wx.StaticText
You could also use a regular TextCtrl with the style TE_READONLY but that shows a cursor and the text looks editable, but it isn't.
| Non-editable text box in wxPython | How to create a non-editable text box with no cursor in wxPython to dump text in?
| [
"wx.StaticText\nYou could also use a regular TextCtrl with the style TE_READONLY but that shows a cursor and the text looks editable, but it isn't.\n"
] | [
7
] | [] | [] | [
"python",
"textbox",
"wxpython",
"wxwidgets"
] | stackoverflow_0001254819_python_textbox_wxpython_wxwidgets.txt |
Q:
Coroutines for game design?
I've heard that coroutines are a good way to structure games (e.g., PEP 342: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.
I see from this article that coro... | Coroutines for game design? | I've heard that coroutines are a good way to structure games (e.g., PEP 342: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.
I see from this article that coroutines can represent states in a ... | [
"Coroutines allow for creating large amounts of very-lightweight \"microthreads\" with cooperative multitasking (i.e. microthreads suspending themselves willfully to allow other microthreads to run). Read up in Dave Beazley's article on this subject.\nNow, it's obvious how such microthreads can be useful for game p... | [
10,
10,
7,
2,
1
] | [] | [] | [
"coroutine",
"python"
] | stackoverflow_0001247894_coroutine_python.txt |
Q:
Python: using threads to call subprocess.Popen multiple times
I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they should run. If they should, they get added to a thread_pool (l... | Python: using threads to call subprocess.Popen multiple times | I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they should run. If they should, they get added to a thread_pool (list) and then every item in the thread_pool gets the start() method... | [
"I think the key code is:\n self.lock.acquire()\n print \"\\nSubprocess started\"\n p = subprocess.Popen( # etc\n stdout_value = proc.communicate('through stdin to stdout')[0]\n self.lock.release()\n\nthe explicit calls to acquire and release should guarantee serialization -- don't you observe serial... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001255449_python.txt |
Q:
Catching uncaught exceptions through django development server
I am looking for some way in django's development server that will make the server to stop at any uncaught exception automatically, as it is done with pdb mode in ipython console.
I know to put import pdb; pdb.set_trace() lines into the code to make ap... | Catching uncaught exceptions through django development server | I am looking for some way in django's development server that will make the server to stop at any uncaught exception automatically, as it is done with pdb mode in ipython console.
I know to put import pdb; pdb.set_trace() lines into the code to make application stop. But this doesn't help me, because the line where the... | [
"You can set sys.excepthook to a function that does import pdb; pdb.pm(), as per this recipe.\n"
] | [
2
] | [] | [] | [
"debugging",
"django",
"python"
] | stackoverflow_0001255467_debugging_django_python.txt |
Q:
Has anyone succeeded in using Google App Engine with Python version 2.6?
Since Python 2.6 is backward compatible to 2.52 , did anyone succeeded in using it with Google app Engine ( which supports 2.52 officially ).
I know i should try it myself. But i am a python and web-apps new bee and for me installation and c... | Has anyone succeeded in using Google App Engine with Python version 2.6? | Since Python 2.6 is backward compatible to 2.52 , did anyone succeeded in using it with Google app Engine ( which supports 2.52 officially ).
I know i should try it myself. But i am a python and web-apps new bee and for me installation and configuration is the hardest part while getting started with something new in t... | [
"I suppose logging module crashes if you try to start the dev environment. See the issue and a workaround.\nAfter doing that change my code worked in 2.6 without any problems. I suggest using 2.5.x though so there are no other incompatibilities introduced in your code which would make your app fail on the live serv... | [
11,
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001254028_google_app_engine_python.txt |
Q:
How can you ensure registered atexit function will run with AppHelper.runEventLoop() in PyObjC?
I'm just wondering why I my registered an atexit function... e.g.
import atexit
atexit.register(somefunc)
...
AppHelper.runEventLoop()
Of course I know when will atexit won't work. When I comment out AppHelper.runEvent... | How can you ensure registered atexit function will run with AppHelper.runEventLoop() in PyObjC? | I'm just wondering why I my registered an atexit function... e.g.
import atexit
atexit.register(somefunc)
...
AppHelper.runEventLoop()
Of course I know when will atexit won't work. When I comment out AppHelper.runEventLoop() the atexit function gets called. I also browsed my pyobjc egg, and I saw under __init__.py und... | [
"I believe you do need delegates, because otherwise the event loop can exit the process rather abruptly (kind of like os._exit) and therefore not give the Python runtime a chance to run termination code such as finally clauses, atexit functions, etc etc.\n"
] | [
1
] | [] | [] | [
"atexit",
"pyobjc",
"python"
] | stackoverflow_0001255025_atexit_pyobjc_python.txt |
Q:
python tab completion in windows
I'm writing a cross-platform shell like program in python and I'd like to add custom tab-completion actions. On Unix systems I can use the built-in readline module and use code like the following to specify a list of possible completions when I hit the TAB key:
import readline
read... | python tab completion in windows | I'm writing a cross-platform shell like program in python and I'd like to add custom tab-completion actions. On Unix systems I can use the built-in readline module and use code like the following to specify a list of possible completions when I hit the TAB key:
import readline
readline.parse_and_bind( 'tab: complete' )... | [
"Do u have a look at PyReadline: a ctypes-based readline for Windows? Although 3rd-party packages is NOT your option, maybe it's useful for build one's own, isn't it:).\n",
"you could look at how ipython does it with pyreadline as well, maybe \n",
"Another possibility to check out is readline.py.\n"
] | [
2,
0,
0
] | [] | [] | [
"python",
"readline",
"tab_completion",
"windows"
] | stackoverflow_0001081405_python_readline_tab_completion_windows.txt |
Q:
Suggestion Needed - Networking in Python - A good idea?
I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as ofte... | Suggestion Needed - Networking in Python - A good idea? | I am considering programming the network related features of my application in Python instead of the C/C++ API. The intended use of networking is to pass text messages between two instances of my application, similar to a game passing player positions as often as possible over the network.
Although the python socket mo... | [
"Check out Twisted, a Python engine for Networking. Has built-in support for TCP, UDP, SSL/TLS, multicast, Unix sockets, a large number of protocols (including HTTP, NNTP, IMAP, SSH, IRC, FTP, and others)\n",
"Python is a mature language that can do almost anything that you can do in C/C++ (even direct memory ac... | [
9,
3,
1,
1
] | [] | [] | [
"network_programming",
"python"
] | stackoverflow_0001253905_network_programming_python.txt |
Q:
text file format from array
I have no: of arrays, and i like to take it to text file in specific format, for eg.,
'present form'
a= [1 2 3 4 5 ]
b= [ 1 2 3 4 5 6 7 8 ]
c= [ 8 9 10 12 23 43 45 56 76 78]
d= [ 1 2 3 4 5 6 7 8 45 56 76 78 12 23 43 ]
The 'required format' in a txt file,
a '\t' b '\t'... | text file format from array | I have no: of arrays, and i like to take it to text file in specific format, for eg.,
'present form'
a= [1 2 3 4 5 ]
b= [ 1 2 3 4 5 6 7 8 ]
c= [ 8 9 10 12 23 43 45 56 76 78]
d= [ 1 2 3 4 5 6 7 8 45 56 76 78 12 23 43 ]
The 'required format' in a txt file,
a '\t' b '\t' d '\t' c
1 '\t' ... | [
"from __future__ import with_statement\nimport csv\nimport itertools\n\n\n\na= [1, 2, 3, 4, 5]\nb= [1, 2, 3, 4, 5, 6, 7, 8]\nc= [8, 9, 10, 12, 23, 43, 45, 56, 76, 78]\nd= [1, 2, 3, 4, 5, 6, 7, 8, 45, 56, 76, 78, 12, 23, 43]\n\nwith open('destination.txt', 'w') as f:\n cf = csv.writer(f, delimiter='\\t')\n cf.... | [
6,
1,
-1
] | [] | [] | [
"python"
] | stackoverflow_0001255688_python.txt |
Q:
How to read String in java that was written using python's struct.pack method
I have written information to a file in python using struct.pack
eg.
out.write( struct.pack(">f", 1.1) );
out.write( struct.pack(">i", 12) );
out.write( struct.pack(">3s", "abc") );
Then I read it in java using DataInputStream and readI... | How to read String in java that was written using python's struct.pack method | I have written information to a file in python using struct.pack
eg.
out.write( struct.pack(">f", 1.1) );
out.write( struct.pack(">i", 12) );
out.write( struct.pack(">3s", "abc") );
Then I read it in java using DataInputStream and readInt, readFloat and readUTF.
Reading the numbers works but as soon as I call readUTF(... | [
"The format expected by readUTF(), is documented here. In short, it expects a 16-bit, big-endian length followed by the bytes of the string. So, I think you could modify your pack call to look something like this:\ns = \"abc\"\nout.write( struct.pack(\">H\", len(s) ))\nout.write( struct.pack(\">%ds\" % len(s), s ))... | [
4
] | [] | [] | [
"java",
"python"
] | stackoverflow_0001255918_java_python.txt |
Q:
Checking whether a command produced output
I am using the following call for executing the 'aspell' command on some strings in Python:
r,w,e = popen2.popen3("echo " +str(m[i]) + " | aspell -l")
I want to test the success of the function looking at the stdout File Object r. If there is no output the command is suc... | Checking whether a command produced output | I am using the following call for executing the 'aspell' command on some strings in Python:
r,w,e = popen2.popen3("echo " +str(m[i]) + " | aspell -l")
I want to test the success of the function looking at the stdout File Object r. If there is no output the command is successful.
What is the best way to test that in Py... | [
"Best is to use the subprocess module of the standard Python library, see here -- popen2 is old and not recommended.\nAnyway, in your code, if r.read(1): is a fast way to test if there's any content in r (if you don't care about what that content might specifically be).\n",
"Why don't you use aspell -a?\nYou coul... | [
2,
2
] | [] | [] | [
"python",
"scripting",
"unix"
] | stackoverflow_0001256424_python_scripting_unix.txt |
Q:
Finding Functions Defined in a with: Block
Here's some code from Richard Jones' Blog:
with gui.vertical:
text = gui.label('hello!')
items = gui.selection(['one', 'two', 'three'])
with gui.button('click me!'):
def on_click():
text.value = items.value
text.foreground = red... | Finding Functions Defined in a with: Block | Here's some code from Richard Jones' Blog:
with gui.vertical:
text = gui.label('hello!')
items = gui.selection(['one', 'two', 'three'])
with gui.button('click me!'):
def on_click():
text.value = items.value
text.foreground = red
My question is: how the heck did he do this? ... | [
"Here's one way:\nfrom __future__ import with_statement\nimport inspect\n\nclass button(object):\n def __enter__(self):\n # keep track of all that's already defined BEFORE the `with`\n f = inspect.currentframe(1)\n self.mustignore = dict(f.f_locals)\n\n def __exit__(self, exc_type, exc_value, traceback):... | [
14,
2
] | [] | [] | [
"contextmanager",
"python",
"scope",
"with_statement"
] | stackoverflow_0001255914_contextmanager_python_scope_with_statement.txt |
Q:
Call PHP code from Python
I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by mod_php5 and Python through mod_wsgi, usually.
Now I wonder what's the best way to call this PHP ad ma... | Call PHP code from Python | I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by mod_php5 and Python through mod_wsgi, usually.
Now I wonder what's the best way to call this PHP ad management code from within my Py... | [
"How about using AJAX from the browser to load the ads?\nFor instance (using JQuery):\n$(document).ready(function() { $(\"#apageelement\").load(\"/phpapp/getads.php\"); })\n\nThis allows you to keep you app almost completely separate from the PHP app.\n",
"Best solution is to use server side includes. Most webser... | [
4,
2,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0001254802_php_python.txt |
Q:
PHP - Print all statements that are executed in a PHP command line script?
In python, one can trace all the statements that are executed by a command line script using the trace module. In bash you can do the same with set -x. We have a PHP script that we're running from the command line, like a normal bash / pyth... | PHP - Print all statements that are executed in a PHP command line script? | In python, one can trace all the statements that are executed by a command line script using the trace module. In bash you can do the same with set -x. We have a PHP script that we're running from the command line, like a normal bash / python / perl / etc script. Nothing web-y is going on.
Is there anyway to get a trac... | [
"There is a PECL extension, apd, that will generate a trace file. \n",
"Not in pure-PHP, no -- as far as i know.\nBut you can use a debugger ; a nice way to do that is with \n\nThe extension Xdebug, which can be used as a debugger\nand some graphical IDE that integrates some debugging tools, like Eclipse PDT\n\nB... | [
2,
1
] | [
"I'm kinda blind here but I guess one way you could do it is to write all the relevant code inside custom functions and call debug_backtrace(). debug_print_backtrace may also be useful.\nI hope it helps.\n"
] | [
-1
] | [
"command_line",
"debugging",
"php",
"python"
] | stackoverflow_0001254215_command_line_debugging_php_python.txt |
Q:
Selecting related objects in django
I have following problem:
My application have 2 models:
1)
class ActiveList(models.Model):
user = models.ForeignKey(User, unique=True)
updatedOn = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.user.username
'''
GameClaim class, to st... | Selecting related objects in django | I have following problem:
My application have 2 models:
1)
class ActiveList(models.Model):
user = models.ForeignKey(User, unique=True)
updatedOn = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.user.username
'''
GameClaim class, to store game requests.
'''
class GameClaim(mo... | [
"What you are looking at doing belongs more properly in the view than the template. I think you want something like:\nclaimer = User.objects.get(name='test')\nclaimed_opponents = User.objects.filter(gameclaim_opponent__me__user=claimer)\n\nThen you can pass those into your template, and operate on them directly. ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001256387_django_python.txt |
Q:
Need help in refactoring my python script
I have a python script which process a file line by line, if the line
matches a regex, it calls a function to handle it.
My question is is there a better write to refactor my script. The
script works, but as it is, i need to keep indent to the right of the
editor as I add ... | Need help in refactoring my python script | I have a python script which process a file line by line, if the line
matches a regex, it calls a function to handle it.
My question is is there a better write to refactor my script. The
script works, but as it is, i need to keep indent to the right of the
editor as I add more and more regex for my file.
Thank you for ... | [
"I'd switch to using a data structure mapping regexes to functions. Something like:\nmap = { reg1: handleReg1, reg2: handleReg2, etc }\n\nThen you just loop through them:\nfor reg, handler in map.items():\n result = reg.match(line)\n if result:\n handler(result)\n break\n\nIf you need the matches... | [
12,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001256704_python.txt |
Q:
Why would traceback.extract_stack() return [] when there is definitely a call stack?
I have a class that calls
traceback.extract_stack()
in its __init__(), but whenever I do that, the value of traceback.extract_stack() is [].
What are some reasons that this could be the case?
Is there another way to get a traceba... | Why would traceback.extract_stack() return [] when there is definitely a call stack? | I have a class that calls
traceback.extract_stack()
in its __init__(), but whenever I do that, the value of traceback.extract_stack() is [].
What are some reasons that this could be the case?
Is there another way to get a traceback that will be more reliable?
I think the problem is that the code is running in Pylons. ... | [
"Following shows traceback.extract_stack() working when called from a class's __init__ method. Please post your code showing that it doesn't work. Include the Python version. Don't type from memory; use copy/paste as I have done.\nPython 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32... | [
1,
0,
0
] | [] | [] | [
"python",
"stack_trace"
] | stackoverflow_0001252823_python_stack_trace.txt |
Q:
Loading and saving data from m2m relationships in Textarea widgets with ModelForm
I have a Model that looks something like this:
class Business(models.Model):
name = models.CharField('business name', max_length=100)
# ... some other fields
emails = models.ManyToManyField(Email, null=True)
phone_num... | Loading and saving data from m2m relationships in Textarea widgets with ModelForm | I have a Model that looks something like this:
class Business(models.Model):
name = models.CharField('business name', max_length=100)
# ... some other fields
emails = models.ManyToManyField(Email, null=True)
phone_numbers = models.ManyToManyField(PhoneNumber, null=True)
urls = models.ManyToManyField... | [
"This is not directly an answer to your question. It is more a suggestion to re-think your data model.\nIt looks like your BusinessContactForm presents textarea widgets to insert multiple rows into the database. I would not use a Textarea widget for multiple items of more restricted type: I'd enter phone numbers wi... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0001257062_django_django_forms_django_models_python.txt |
Q:
How to update the twisted framework
I can see from the latest 8.2 (almost 1200 lines of code) twisted that I am missing something:
http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py
My copy (697 lines from 3 years ago) is in:
/System/Library/Frameworks/Python.framework/Versions... | How to update the twisted framework | I can see from the latest 8.2 (almost 1200 lines of code) twisted that I am missing something:
http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/jabber/xmlstream.py
My copy (697 lines from 3 years ago) is in:
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/prot... | [
"Try using virtualenv and pip (sudo easy_install virtualenv pip), which are great ways to avoid the dependency hell that you are experiencing.\nWith virtualenv you can create isolated Python environments, and then using pip you can directly install new packages into you virtualenvs.\nHere is a complete example:\n\n... | [
17,
1,
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0001117255_python_twisted.txt |
Q:
Access Ruby objects with Python via XML-RPC?
I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:
I have a test Ruby XML-RPC server as follows:
require "xml... | Access Ruby objects with Python via XML-RPC? | I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:
I have a test Ruby XML-RPC server as follows:
require "xmlrpc/server"
class ExampleBar
def bar()
retu... | [
"Your client (s in you Python code) is a ServerProxy object. It only accepts return values of type boolean, integers, floats, arrays, structures, dates or binary data.\nHowever, without you doing the wiring, there is no way for it to return another ServerProxy, which you would need for accessing another class. You ... | [
5,
1,
1
] | [] | [] | [
"interop",
"python",
"ruby",
"xml_rpc"
] | stackoverflow_0000264128_interop_python_ruby_xml_rpc.txt |
Q:
What's Python's equivalent to Java InputStream's available method?
Java's InputStream provides a method named available which returns the number of bytes that can be read without blocking.
How can I achieve this in Python?
A:
You've got to tell us what type of object you're working with. I'm assuming you're ta... | What's Python's equivalent to Java InputStream's available method? | Java's InputStream provides a method named available which returns the number of bytes that can be read without blocking.
How can I achieve this in Python?
| [
"You've got to tell us what type of object you're working with. I'm assuming you're talking about a socket read. Either you read the socket with blocking or you read without blocking. You can measure how you have just read in a non-blocking read, if you are interested in that. However, it sounds like you are tr... | [
3,
1
] | [] | [] | [
"java",
"python",
"sockets"
] | stackoverflow_0001257264_java_python_sockets.txt |
Q:
python: slow timeit() function
When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?
>>> import timeit
>>> t = timeit.Timer("3**4**5")
>>> t.timeit()
16.55522028637718
Using:
Python 3.1 (x86) -
AMD A... | python: slow timeit() function | When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?
>>> import timeit
>>> t = timeit.Timer("3**4**5")
>>> t.timeit()
16.55522028637718
Using:
Python 3.1 (x86) -
AMD Athlon 64 X2 -
WinXP (32 bit)
| [
"The timeit() function runs the code many times (default one million) and takes an average of the timings.\nTo run the code only once, do this:\nt.timeit(1)\n\nbut that will give you skewed results - it repeats for good reason.\nTo get the per-loop time having let it repeat, divide the result by the number of loops... | [
32,
6,
4,
2
] | [] | [] | [
"python",
"timeit",
"timer"
] | stackoverflow_0001257727_python_timeit_timer.txt |
Q:
get_allowed_auths() in paramiko for authentication types
I am trying to get supported authentication types/methods from a running SSH server in Python.
I found this method get_allowed_auths() in the ServerInterface class in Paramiko but I can't understand if it is usable in a simple client-like snippet of code (I ... | get_allowed_auths() in paramiko for authentication types | I am trying to get supported authentication types/methods from a running SSH server in Python.
I found this method get_allowed_auths() in the ServerInterface class in Paramiko but I can't understand if it is usable in a simple client-like snippet of code (I am writing something that accomplish in ONLY this task).
Anyon... | [
"You can try to authenticate using no authentication, which should always fail, but the server will then send back the auth types that can continue. There is an auth_none() method provided by paramiko.Transport to do this.\nimport paramiko\nimport socket\n\ns = socket.socket()\ns.connect(('localhost', 22))\nt = par... | [
4
] | [] | [] | [
"authentication",
"paramiko",
"python",
"ssh"
] | stackoverflow_0001253870_authentication_paramiko_python_ssh.txt |
Q:
create an array from a txt file
I'm new in python and I have a problem.
I have some measured data saved in a txt file.
the data is separated with tabs, it has this structure:
0 0 -11.007001 -14.222319 2.336769
i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2...,299... | create an array from a txt file | I'm new in python and I have a problem.
I have some measured data saved in a txt file.
the data is separated with tabs, it has this structure:
0 0 -11.007001 -14.222319 2.336769
i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2...,299), so the data is sorted at first wit... | [
"you can combine them with zip function, like so:\nfor sim, datapoint, x, y, z in zip(simnum, npts, *xyz):\n # do your thing\n\nor you could avoid list comprehensions altogether and just iterate over the lines of the file:\nfor line in open(fname):\n lst = line.split('\\t')\n sim, datapoint = int(lst[0]), ... | [
2,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"arrays",
"python",
"text"
] | stackoverflow_0001256099_arrays_python_text.txt |
Q:
How do I get omnicompletion for Python external libraries?
I've setup my gVim to have omnicompletion, but only for the standard library atm.. How do I include other libraries (Django, Pygame, etc...)?
Thanks!
A:
Here's a tutorial on using omnicomplete with Django.
| How do I get omnicompletion for Python external libraries? | I've setup my gVim to have omnicompletion, but only for the standard library atm.. How do I include other libraries (Django, Pygame, etc...)?
Thanks!
| [
"Here's a tutorial on using omnicomplete with Django.\n"
] | [
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0001257742_python_vim.txt |
Q:
Problem reading an Integer in java that was written using python’s struct.pack method
First I write the integer using python:
out.write( struct.pack(">i", int(i)) );
I then read the integer using DataInputStream.readInt() in Java.
I works but when it tries to read the number 10, and probably some other numbers too... | Problem reading an Integer in java that was written using python’s struct.pack method | First I write the integer using python:
out.write( struct.pack(">i", int(i)) );
I then read the integer using DataInputStream.readInt() in Java.
I works but when it tries to read the number 10, and probably some other numbers too,
it starts to read garbage.
Reading the numbers:
0, 4, 5, 0, 5, 13, 10, 1, 5, 6
Java reads... | [
"Psychic debugging: You're writing the output in text mode on Windows using code like this:\nf = open(\"output.dat\", \"w\")\nf.write(my_data)\n\nand that's making your 13 (which is a newline) become carriage return / newline (10, 13).\nYou need to write your output in binary mode:\nf = open(\"output.dat\", \"wb\")... | [
7
] | [] | [] | [
"java",
"python"
] | stackoverflow_0001257856_java_python.txt |
Q:
Django: Permalinks for Admin
I know the link template to reach an object is like following:
"{{ domain }}/{{ admin_dir }}/{{ appname }}/{{ modelname }}/{{ pk }}"
Is there a way built-in to get a permalink for an object?
from django.contrib import admin
def get_admin_permalink(instance, admin_site=admin.site):
... | Django: Permalinks for Admin | I know the link template to reach an object is like following:
"{{ domain }}/{{ admin_dir }}/{{ appname }}/{{ modelname }}/{{ pk }}"
Is there a way built-in to get a permalink for an object?
from django.contrib import admin
def get_admin_permalink(instance, admin_site=admin.site):
# returns admin URL for instance... | [
"1.1 is out, the doc is right here: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#admin-reverse-urls\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#url\nI also used it a bit, the admin namespace will have to be specified whenever you are fetching an existing admin url.\n# in urls.py, assumi... | [
1
] | [] | [] | [
"django",
"django_admin",
"permalinks",
"python",
"reverse"
] | stackoverflow_0000690688_django_django_admin_permalinks_python_reverse.txt |
Q:
Generic view 'archive_year' produces blank page
I am using Django's generic views to create a blog site. The
templates I created, entry_archive_day, entry_archive_month,
entry_archive, and entry_detail all work perfectly.
But entry_archive_year does not. Instead, it is simply a valid page with no content (not ... | Generic view 'archive_year' produces blank page | I am using Django's generic views to create a blog site. The
templates I created, entry_archive_day, entry_archive_month,
entry_archive, and entry_detail all work perfectly.
But entry_archive_year does not. Instead, it is simply a valid page with no content (not a 404 or other error. It looks like it sees no objec... | [
"To solve your problem:\nIf you set make_object_list=True when calling archive_year, then the list of objects for that year will be available as object_list.\nAs a quick example, if your url pattern looks like\nurl(r'^(?P<year>\\d{4})/$', 'archive_year', info_dict, name=\"entry_archive_year\")\n\nwhere info_dict is... | [
5
] | [] | [] | [
"django",
"generics",
"python",
"view"
] | stackoverflow_0001257943_django_generics_python_view.txt |
Q:
Hit a URL on other server from google app engine
I want to hit a URL from python in google app engine. Can any one please tell me how can i hit the URL using python in google app engine.
A:
You can use the URLFetch API
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.f... | Hit a URL on other server from google app engine | I want to hit a URL from python in google app engine. Can any one please tell me how can i hit the URL using python in google app engine.
| [
"You can use the URLFetch API\nfrom google.appengine.api import urlfetch\n\nurl = \"http://www.google.com/\"\nresult = urlfetch.fetch(url)\nif result.status_code == 200:\n doSomethingWithResult(result.content)\n\n",
"It always depends on post or get. urllib can post to a form somewhere else, if we want the rathe... | [
6,
0
] | [] | [] | [
"google_app_engine",
"python",
"url"
] | stackoverflow_0001233284_google_app_engine_python_url.txt |
Q:
Starting semantic image recognition
How to recognize (in)appropriate images?
To facilitate, enable and easify photo and image moderation and administration targeting gae, I try get started with basic python image recognition ie basic semantic information what the image looks like to hold back doubtful material unt... | Starting semantic image recognition | How to recognize (in)appropriate images?
To facilitate, enable and easify photo and image moderation and administration targeting gae, I try get started with basic python image recognition ie basic semantic information what the image looks like to hold back doubtful material until human can judge it, and to approve the... | [
"In python you could always:\nimport supreme_court\n\nBecause when it comes to pornography, they know it when they see it.\nMediocre jokes aside, I would develop a bunch of fuzzy image recognizers that match easy things (like how much of the image is made up of a skin color tone?). You could probably come up with a... | [
2,
2
] | [] | [] | [
"computer_vision",
"image",
"image_recognition",
"pattern_recognition",
"python"
] | stackoverflow_0001257933_computer_vision_image_image_recognition_pattern_recognition_python.txt |
Q:
Elixir Entity with a list of tuples in it. ex. Cooking Recipe with list of (ingrediant, quantity) tuple
I'm trying to build an elixir model in which I have a class with a list(of variable size) of tuples.
One example would be a recipe
while I can do something like this:
class Recipe(Entity):
ingrediants = OneT... | Elixir Entity with a list of tuples in it. ex. Cooking Recipe with list of (ingrediant, quantity) tuple | I'm trying to build an elixir model in which I have a class with a list(of variable size) of tuples.
One example would be a recipe
while I can do something like this:
class Recipe(Entity):
ingrediants = OneToMany('IngrediantList')
cooking_time = Field(Integer)
...
class IngrediantList(Entity):
ingredia... | [
"This is the correct way to model composite objects. The only thing I'd change is the name of the IngredientList class. Something like RecipeEntry or IngredientQuantity would be more appropriate. Calling it a tuple is just trying to avoid the need to name the fact that a recipe needs some quantity of some ingredien... | [
0,
0
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0001247343_python_python_elixir_sqlalchemy.txt |
Q:
Google Web Toolkit like application in Django
I'm trying to develop an application that would be perfect for GWT, however I am using this app as a learning example for Django. Is there some precedence for this type of application in Django?
A:
Pyjamas is sort of like GWT which is written with Python. From there ... | Google Web Toolkit like application in Django | I'm trying to develop an application that would be perfect for GWT, however I am using this app as a learning example for Django. Is there some precedence for this type of application in Django?
| [
"Pyjamas is sort of like GWT which is written with Python. From there you can make it work with your django code.\n",
"Lots of people have done this by writing their UI in GWT and having it issue ajax calls back to their python backend. There are basically two ways to go about it. First, you can simply use JSON t... | [
7,
3
] | [] | [] | [
"django",
"gwt",
"python"
] | stackoverflow_0001253056_django_gwt_python.txt |
Q:
Can you get more information about the online file?
I have a online file: http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe ,please donot download it, i want to determine the software version whether is changed, so i want more information about it. for example, using python,i can get this:
import urllib2,urllib
r... | Can you get more information about the online file? | I have a online file: http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe ,please donot download it, i want to determine the software version whether is changed, so i want more information about it. for example, using python,i can get this:
import urllib2,urllib
req = urllib2.Request('http://dl_dir.qq.com/qqfile/tm/TM20... | [
"\nDownload the first thousand bytes or so of the file using the range header.\nUse pefile to parse the PE header and extract version information.\nWith the data, extract useful information such as the time date stamp and other goodies that let you find changes in files without reading the whole thing.\n\n",
"You... | [
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001258280_python.txt |
Q:
How to get webcam info with WMI
Which class that we can obtain webcam info?
Thank
A:
I think you may actually need WIA -- though the URL I'm quoting is all about images, not videos, I'm sure WIA also has video functionality, I just can't find good docs on that!-(
| How to get webcam info with WMI | Which class that we can obtain webcam info?
Thank
| [
"I think you may actually need WIA -- though the URL I'm quoting is all about images, not videos, I'm sure WIA also has video functionality, I just can't find good docs on that!-(\n"
] | [
1
] | [] | [] | [
"python",
"wmi"
] | stackoverflow_0001258455_python_wmi.txt |
Q:
How to make python urllib2 follow redirect and keep post method
I am using urllib2 to post data to a form. The problem is that the form replies with a 302 redirect. According to Python HTTPRedirectHandler the redirect handler will take the request and convert it from POST to GET and follow the 301 or 302. I would ... | How to make python urllib2 follow redirect and keep post method | I am using urllib2 to post data to a form. The problem is that the form replies with a 302 redirect. According to Python HTTPRedirectHandler the redirect handler will take the request and convert it from POST to GET and follow the 301 or 302. I would like to preserve the POST method and the data passed to the opener. I... | [
"This is actually a really bad thing to do the more I thought about it. For instance, if I submit a form to \nhttp://example.com/add (with post data to add a item)\nand the response is a 302 redirect to http://example.com/add and I post the same data that I posted the first time I will end up in an infinite loop. N... | [
6
] | [] | [] | [
"automation",
"python",
"urllib2"
] | stackoverflow_0001258428_automation_python_urllib2.txt |
Q:
storing classmethod reference in tuple does not work as in variable
#!/usr/bin/python
class Bar(object):
@staticmethod
def ruleOn(rule):
if isinstance(rule, tuple):
print rule[0]
print rule[0].__get__(None, Foo)
else:
print rule
class Foo(object):
@classmethod
def callRule(cls... | storing classmethod reference in tuple does not work as in variable | #!/usr/bin/python
class Bar(object):
@staticmethod
def ruleOn(rule):
if isinstance(rule, tuple):
print rule[0]
print rule[0].__get__(None, Foo)
else:
print rule
class Foo(object):
@classmethod
def callRule(cls):
Bar.ruleOn(cls.RULE1)
Bar.ruleOn(cls.RULE2)
@classmethod
... | [
"This is because method are actually functions in Python. They only become bound methods when you look them up on the constructed class instance. See my answer to this question for more details. The non-tuple variant works because it is conceptually the same as accessing a classmethod.\nIf you want to assign bound ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0001258690_python.txt |
Q:
pywikipedia bot with https and http authentication
I'm having trouble getting my bot to login to a MediaWiki install on the intranet. I believe it is due to the http authentication protecting the wiki.
Facts:
The wiki root is: https://local.example.com/mywiki/
When visiting the wiki with a web browser, a popup c... | pywikipedia bot with https and http authentication | I'm having trouble getting my bot to login to a MediaWiki install on the intranet. I believe it is due to the http authentication protecting the wiki.
Facts:
The wiki root is: https://local.example.com/mywiki/
When visiting the wiki with a web browser, a popup comes up asking for enterprise credentials (I assume this... | [
"Well the fact that login.py tries accessing '\\w' instead of your path shows that there is a family configuration issue.\nYour code is indented strangely: is scriptpath a member of the new Family class? as in:\nclass Family(family.Family):\n def __init__(self):\n family.Family.__init__(self)\n sel... | [
4,
0
] | [] | [] | [
"http_authentication",
"https",
"python",
"pywikibot",
"urllib2"
] | stackoverflow_0001256213_http_authentication_https_python_pywikibot_urllib2.txt |
Q:
Python Subprocess - Redirect stdout/err to two places
I have a small python script which invokes an external process using subprocess. I want to redirect stdout and stderr to both a log file and to the terminal.
How can this be done?
A:
You can do this with subprocess.PIPE.
You can find some sample code here.
| Python Subprocess - Redirect stdout/err to two places | I have a small python script which invokes an external process using subprocess. I want to redirect stdout and stderr to both a log file and to the terminal.
How can this be done?
| [
"You can do this with subprocess.PIPE.\nYou can find some sample code here.\n"
] | [
8
] | [] | [] | [
"python",
"redirect",
"stdout",
"subprocess"
] | stackoverflow_0001258863_python_redirect_stdout_subprocess.txt |
Q:
surprising time shift for python call
I'm using the following code in Python 2.5.1 to generate a UTC timestamp from a string representation of a date:
time.mktime(time.strptime("2009-06-16", "%Y-%m-%d"))
The general result is: 1245103200 (16.6.2009 0:00 UTC or 15.6.09 22:00:00, if you're in my time zone).
But n... | surprising time shift for python call | I'm using the following code in Python 2.5.1 to generate a UTC timestamp from a string representation of a date:
time.mktime(time.strptime("2009-06-16", "%Y-%m-%d"))
The general result is: 1245103200 (16.6.2009 0:00 UTC or 15.6.09 22:00:00, if you're in my time zone).
But now, I found that on some computers running ... | [
"Found the answer myself:\nWhen executing the following on the python command line interface, I get the result:\n\ntime.strptime(\"2009-06-16\", \"%Y-%m-%d\")\n time.struct_time(tm_year=2009, tm_mon=6, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=167, tm_isdst=-1) \n\nIf I run the same command in... | [
1,
0
] | [] | [] | [
"python",
"timestamp",
"windows_xp"
] | stackoverflow_0001238648_python_timestamp_windows_xp.txt |
Q:
Locking a custom dictionary
Good day pythonians,
I want to make a custom dictionary with two main features:
All keys are declared on creation
It is impossible to add new keys or modify current ones (values are still modifiable)
Right now code is this:
class pick(dict):
"""This will make delicious toffee when ... | Locking a custom dictionary | Good day pythonians,
I want to make a custom dictionary with two main features:
All keys are declared on creation
It is impossible to add new keys or modify current ones (values are still modifiable)
Right now code is this:
class pick(dict):
"""This will make delicious toffee when finished"""
def __init__(self,... | [
"Override the __setitem__ method with your desired behavior, call dict.__setitem__(self, key, value) to modify the base dictionary without going through your base logic.\nclass ImmutableDict(dict):\n def __setitem__(self, key, value):\n if key not in self:\n raise KeyError(\"Immutable dict\")\... | [
12,
2,
2
] | [] | [] | [
"dictionary",
"locking",
"python"
] | stackoverflow_0001260649_dictionary_locking_python.txt |
Q:
Where is the hidden parameter?
I have this function call here:
import test_hosts
test_hosts.LocalTestHost(mst, port, local_ip, remote_if_mac, remote_if_ip, service_port)
and when I run it, the interpreter fails, and says I'm passing 6 parameters to a function that receives 7 parameters.
LocalTestHost is a class ... | Where is the hidden parameter? | I have this function call here:
import test_hosts
test_hosts.LocalTestHost(mst, port, local_ip, remote_if_mac, remote_if_ip, service_port)
and when I run it, the interpreter fails, and says I'm passing 6 parameters to a function that receives 7 parameters.
LocalTestHost is a class which its constructor takes a self p... | [
"The snippets of code you pasted look fine. As others correctly said, to find the problem you should find the smallest amount of code that still has the bug.\nMy suggestion would be to \n(1) check that module test_hosts is written for your version of Python and that it's indeed the file being imported \n(2) copy th... | [
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001251427_python.txt |
Q:
Python : Assert that variable is instance method?
How can one check if a variable is an instance method or not? I'm using python 2.5.
Something like this:
class Test:
def method(self):
pass
assert is_instance_method(Test().method)
A:
inspect.ismethod is what you want to find out if you definitely ha... | Python : Assert that variable is instance method? | How can one check if a variable is an instance method or not? I'm using python 2.5.
Something like this:
class Test:
def method(self):
pass
assert is_instance_method(Test().method)
| [
"inspect.ismethod is what you want to find out if you definitely have a method, rather than just something you can call.\nimport inspect\n\ndef foo(): pass\n\nclass Test(object):\n def method(self): pass\n\nprint inspect.ismethod(foo) # False\nprint inspect.ismethod(Test) # False\nprint inspect.ismethod(Test.met... | [
53,
8
] | [] | [] | [
"assert",
"instance",
"methods",
"python"
] | stackoverflow_0001259963_assert_instance_methods_python.txt |
Q:
Python: How can I choose which module to import when they are named the same
Lets say I'm in a file called openid.py and I do :
from openid.consumer.discover import discover, DiscoveryFailure
I have the openid module on my pythonpath but the interpreter seems to be trying to use my openid.py file. How can I get t... | Python: How can I choose which module to import when they are named the same | Lets say I'm in a file called openid.py and I do :
from openid.consumer.discover import discover, DiscoveryFailure
I have the openid module on my pythonpath but the interpreter seems to be trying to use my openid.py file. How can I get the library version?
(Of course, something other than the obvious 'rename your file... | [
"Thats the reason absolute imports have been chosen as the new default behaviour. However, they are not yet the default in 2.6 (maybe in 2.7...). You can get their behaviour now by importing them from the future:\nfrom __future__ import absolute_import\n\nYou can find out more about this in the PEP metnioned by Nic... | [
9,
3,
2,
1
] | [
"You could try shuffling sys.path, to move the interesting directories to the front before doing the import.\n"
] | [
-1
] | [
"import",
"namespaces",
"python"
] | stackoverflow_0001259106_import_namespaces_python.txt |
Q:
How to get user input during a while loop without blocking
I'm trying to write a while loop that constantly updates the screen by using os.system("clear") and then printing out a different text message every few seconds. How do I get user input during the loop? raw_input() just pauses and waits, which is not the f... | How to get user input during a while loop without blocking | I'm trying to write a while loop that constantly updates the screen by using os.system("clear") and then printing out a different text message every few seconds. How do I get user input during the loop? raw_input() just pauses and waits, which is not the functionality I want.
import os
import time
string = "the fox ju... | [
"The select module in Python's standard library may be what you're looking for -- standard input has FD 0, though you may also need to put a terminal in \"raw\" (as opposed to \"cooked\") mode, on unix-y systems, to get single keypresses from it as opposed to whole lines complete with line-end. If on Windows, msvcr... | [
9,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0001258566_python.txt |
Q:
Pythonic way of searching for a substring in a list
I have a list of strings - something like
mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']
I want to find the first occurrence of anything that starts with foobar. If I was grepping the... | Pythonic way of searching for a substring in a list | I have a list of strings - something like
mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']
I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution loo... | [
"You can also use a list comprehension : \nmatches = [s for s in mytext if 'foobar' in s]\n\n(and if you were really looking for strings starting with 'foobar' as THC4k noticed, consider the following : \nmatches = [s for s in mytext if s.startswith('foobar')]\n\n",
"If you really want the FIRST occurrence of a s... | [
15,
9,
6,
5,
4
] | [] | [] | [
"list",
"python",
"string",
"substring"
] | stackoverflow_0001260947_list_python_string_substring.txt |
Q:
Serializing a Python Object to XML (Apple .plist)
I need to read and serialize objects from and to XML, Apple's .plist format in particular. What's the most intelligent way to do it in Python? Are there any ready-made solutions?
A:
Check out plistlib.
A:
Assuming you are on a Mac, you can use PyObjC.
Here is a... | Serializing a Python Object to XML (Apple .plist) | I need to read and serialize objects from and to XML, Apple's .plist format in particular. What's the most intelligent way to do it in Python? Are there any ready-made solutions?
| [
"Check out plistlib.\n",
"Assuming you are on a Mac, you can use PyObjC.\nHere is an example of reading from a plist, from Using Python For System Administration, slide 27.\nfrom Cocoa import NSDictionary\n\nmyfile = \"/Library/Preferences/com.apple.SoftwareUpdate.plist\"\nmydict = NSDictionary.dictionaryWithCont... | [
7,
2
] | [] | [] | [
"plist",
"python",
"xml"
] | stackoverflow_0000879212_plist_python_xml.txt |
Q:
Interrupt Python program deadlocked in a DLL
How can I ensure a python program can be interrupted via Ctrl-C, or a similar mechanism, when it is deadlocked in code within a DLL?
A:
Not sure if this is exactly what you are asking, but there are issues when trying to interrupt (via Ctrl-C) a multi-threaded python ... | Interrupt Python program deadlocked in a DLL | How can I ensure a python program can be interrupted via Ctrl-C, or a similar mechanism, when it is deadlocked in code within a DLL?
| [
"Not sure if this is exactly what you are asking, but there are issues when trying to interrupt (via Ctrl-C) a multi-threaded python process. Here is a video of a talk about the python Global Interpreter Lock that also discusses that issue:\nMindblowing Python GIL\n",
"You might want to take a look at this maili... | [
1,
0
] | [] | [] | [
"dll",
"python"
] | stackoverflow_0001260259_dll_python.txt |
Q:
Is it a good idea to use super() in Python?
Or should I just explicitly reference the superclasses whose methods I want to call?
It seems brittle to repeat the names of super classes when referencing their constructors, but this page http://fuhm.net/super-harmful/ makes some good arguments against using super().
... | Is it a good idea to use super() in Python? | Or should I just explicitly reference the superclasses whose methods I want to call?
It seems brittle to repeat the names of super classes when referencing their constructors, but this page http://fuhm.net/super-harmful/ makes some good arguments against using super().
| [
"The book Expert Python Programming has discussed the topic of \"super pitfalls\" in chapter 3. It is worth reading. Below is the book's conclusion:\n\nSuper usage has to be consistent: In a class hierarchy, super should be used everywhere or nowhere. Mixing super and classic calls is a confusing practice. People t... | [
11,
6,
4,
3,
2,
0
] | [] | [] | [
"oop",
"python",
"super"
] | stackoverflow_0001259547_oop_python_super.txt |
Q:
Eclipse+Pydev: "cleanup" functions aren't called when pressing "stop""?
Trying to run this file in eclipse
class Try:
def __init__(self):
pass
def __del__(self):
print 1
a=Try()
raw_input('waiting to finish')
and pressing the stop button without letting the program finish doesn't print "1", i.... | Eclipse+Pydev: "cleanup" functions aren't called when pressing "stop""? | Trying to run this file in eclipse
class Try:
def __init__(self):
pass
def __del__(self):
print 1
a=Try()
raw_input('waiting to finish')
and pressing the stop button without letting the program finish doesn't print "1", i.e the del method is never called. If i try to run the script from the shell a... | [
"Python docs:\n\n__del__(self)\n\nCalled when the instance is about to be destroyed. This is also called a destructor. If a base class has a __del__() method, the derived class's __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. Note that it is possi... | [
4,
2
] | [] | [] | [
"del",
"eclipse",
"pydev",
"python"
] | stackoverflow_0001261597_del_eclipse_pydev_python.txt |
Q:
using setuptools with post-install and python dependencies
This is somewhat related to this question. Let's say I have a package that I want to deploy via rpm because I need to do some file copying on post-install and I have some non-python dependencies I want to declare. But let's also say I have some python de... | using setuptools with post-install and python dependencies | This is somewhat related to this question. Let's say I have a package that I want to deploy via rpm because I need to do some file copying on post-install and I have some non-python dependencies I want to declare. But let's also say I have some python dependencies that are easily available in PyPI. It seems like if ... | [
"I think it would be best if your python dependencies were available as RPMs also, and declared as dependencies in the RPM. If they aren't available elsewhere, create them yourself, and put them in your yum repository.\nRunning PyPI installations as a side effect of RPM installation is evil, as it won't support pro... | [
7
] | [] | [] | [
"packaging",
"python",
"rpm",
"setuptools"
] | stackoverflow_0001262052_packaging_python_rpm_setuptools.txt |
Q:
python "block" library
I'm looking for a library that let's configure/write special python block, something like ruby block and/or C-macros.
A:
Looks like you're looking for metapython.
| python "block" library | I'm looking for a library that let's configure/write special python block, something like ruby block and/or C-macros.
| [
"Looks like you're looking for metapython.\n"
] | [
0
] | [] | [] | [
"programming_languages",
"python"
] | stackoverflow_0001262568_programming_languages_python.txt |
Q:
Creating a new input event dispatcher in Pyglet (infra red input)
I recently asked this question in the pyglet-users group, but got response, so I'm trying here instead.
I would like to extend Pyglet to be able to use an infra red input device supported by lirc. I've used pyLirc before ( http://pylirc.mccabe.nu/ )... | Creating a new input event dispatcher in Pyglet (infra red input) | I recently asked this question in the pyglet-users group, but got response, so I'm trying here instead.
I would like to extend Pyglet to be able to use an infra red input device supported by lirc. I've used pyLirc before ( http://pylirc.mccabe.nu/ ) with PyGame and I want to rewrite my application to use Pyglet instead... | [
"The correct way is whatever works. You can always change it later if you find a better way.\n",
"It's probably too late for the OP, but I'll reply anyway in case it's helpful to anyone else.\nCreating the event dispatcher and using pyglet.clock.schedule_interval to call poll() at regular intervals is a good way ... | [
1,
1
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0001206628_pyglet_python.txt |
Q:
How do I pick 2 random items from a Python set?
I currently have a Python set of n size where n >= 0. Is there a quick 1 or 2 lines Python solution to do it? For example, the set will look like:
fruits = set(['apple', 'orange', 'watermelon', 'grape'])
The goal is to pick 2 random items from the above and it's p... | How do I pick 2 random items from a Python set? | I currently have a Python set of n size where n >= 0. Is there a quick 1 or 2 lines Python solution to do it? For example, the set will look like:
fruits = set(['apple', 'orange', 'watermelon', 'grape'])
The goal is to pick 2 random items from the above and it's possible that the above set can contain 0, 1 or more i... | [
"Use the random module: http://docs.python.org/library/random.html\nimport random\nrandom.sample(set([1, 2, 3, 4, 5, 6]), 2)\n\nThis samples the two values without replacement (so the two values are different).\n"
] | [
335
] | [] | [] | [
"python",
"random"
] | stackoverflow_0001262955_python_random.txt |
Q:
Reverse mapping class attributes to classes in Python
I have some code in Python where I'll have a bunch of classes, each of which will have an attribute _internal_attribute. I would like to be able to generate a mapping of those attributes to the original class. Essentially I would like to be able to do this:
cla... | Reverse mapping class attributes to classes in Python | I have some code in Python where I'll have a bunch of classes, each of which will have an attribute _internal_attribute. I would like to be able to generate a mapping of those attributes to the original class. Essentially I would like to be able to do this:
class A(object):
_internal_attribute = 'A attribute'
class... | [
"You can use a meta class to automatically register your classes in magic_reverse_mapping:\nmagic_reverse_mapping = {}\n\nclass MagicRegister(type):\n def __new__(meta, name, bases, dict):\n cls = type.__new__(meta, name, bases, dict)\n magic_reverse_mapping[dict['_internal_attribute']] = cls\n ret... | [
5,
3
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0001263479_metaclass_python.txt |
Q:
How to catch errors elegantly and keep methods clean?
I am in the process of writing a small(er) Python script to automate a semi-frequent, long, and error-prone task. This script is responsible for making various system calls - either though os.system or through os.(mkdir|chdir|etc).
Here is an example of my code... | How to catch errors elegantly and keep methods clean? | I am in the process of writing a small(er) Python script to automate a semi-frequent, long, and error-prone task. This script is responsible for making various system calls - either though os.system or through os.(mkdir|chdir|etc).
Here is an example of my code right now:
class AClass:
def __init__(self, foo, bar,... | [
"How to clean up your verbose output\nMove the verbose/quiet logic into a single function, and then call that function for all of your output. If you make it something nice and short it keeps your mainline code quite tidy.\ndef P(s):\n if (verbose):\n print s\n\nI have a package that does this in our int... | [
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0001264150_python.txt |
Q:
Mechanize and BeautifulSoup for PHP?
I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP?
A:
SimpleTest provides you with similar functionality:
http://www.simpletest.org/en/browser_documentation.html
A:
I don't know how powerful BeautifulSoup is, so maybe this won't be as gre... | Mechanize and BeautifulSoup for PHP? | I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP?
| [
"SimpleTest provides you with similar functionality:\nhttp://www.simpletest.org/en/browser_documentation.html\n",
"I don't know how powerful BeautifulSoup is, so maybe this won't be as great ; but you could try using DOMDocument::loadHTML :\n\nThe function parses the HTML contained\n in the string source . Unlik... | [
8,
8
] | [] | [] | [
"beautifulsoup",
"mechanize",
"php",
"python"
] | stackoverflow_0001263800_beautifulsoup_mechanize_php_python.txt |
Q:
Django saving objects - works, but values of objects seem to be cached until I restart server
I'm writing an app for tagging photos. One of the views handles adding new tags and without boilerplate for POST/GET and handling field errors it does this:
tagName = request.cleaned_attributes['tagName']
t = Tag.objects.... | Django saving objects - works, but values of objects seem to be cached until I restart server | I'm writing an app for tagging photos. One of the views handles adding new tags and without boilerplate for POST/GET and handling field errors it does this:
tagName = request.cleaned_attributes['tagName']
t = Tag.objects.create(name = tagName)
t.save()
Now in a view for another request to retrieve all tags I have:
tag... | [
"Tag.objects.all() is a QuerySet. These do not hit the database until you do something to evaluate them. So, how exactly are you using it in your view? If you are using a generic view and passing the queryset through extra_context, for example, it wouldn't be re-evaluated. \nAlso, as an aside, Tag.objects.create... | [
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001264246_django_django_models_python.txt |
Q:
Plone navigation with one-language-per-folder site
I am developing a multi-lingual site with Plone. I want to have one language per folder but the Plone navigation UI is causing problems.
I have several different folders in my root, such as en, de, nl, etcetera. Inside those folders is the actual content, such as ... | Plone navigation with one-language-per-folder site | I am developing a multi-lingual site with Plone. I want to have one language per folder but the Plone navigation UI is causing problems.
I have several different folders in my root, such as en, de, nl, etcetera. Inside those folders is the actual content, such as en/news, nl/nieuw, de/nachrichten, etcetera. I have set ... | [
"Each language folder should implement INavigationRoot.\nYou can set that up by going to the ZMI, finding the folder, and going to the Interfaces tab. There you will find plone.app.layout.navigation.interfaces.INavigationRoot. Click it, and navigation will treat it as the root of the tree.\n(Note that in Plone 3.3 ... | [
4
] | [] | [] | [
"linguaplone",
"localization",
"multilingual",
"plone",
"python"
] | stackoverflow_0001264421_linguaplone_localization_multilingual_plone_python.txt |
Q:
Is there a class library diagram for django?
I'm looking for a way to find out the class structure at a glance for django. Is there a link to an overview of it?
A:
In the app django_extensions on google code.
There is GraphModels command
A:
A class diagram of most of django's class structure is really not v... | Is there a class library diagram for django? | I'm looking for a way to find out the class structure at a glance for django. Is there a link to an overview of it?
| [
"In the app django_extensions on google code.\nThere is GraphModels command\n",
"A class diagram of most of django's class structure is really not very interesting or useful for that matter. The problem is that most classes you use for development with django are standalone in the sense that they don't branch out... | [
8,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001263677_django_python.txt |
Q:
Error with time.strptime() and python-twitter
I use python-twitter to get the date of a tweet and try to parse it with the time.strptime() function. When I do it interactively, everything works fine. When I call the program from my bash, I get a ValueError saying (for example):
time data u'Wed Aug 12 08:43:35 +000... | Error with time.strptime() and python-twitter | I use python-twitter to get the date of a tweet and try to parse it with the time.strptime() function. When I do it interactively, everything works fine. When I call the program from my bash, I get a ValueError saying (for example):
time data u'Wed Aug 12 08:43:35 +0000 2009' does not match
format '%a %b %d ... | [
"Things to try:\n(1) Is it possible that your interactive session and your \"bash\" are using different locales? Put print time.strftime(some known struct_time) into your script and see if the day and month come out in a different language.\n(2) Put print repr(date) in your script to show unambiguously what you are... | [
2
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0001265064_python_twitter.txt |
Q:
xmpp with python: xmpp.protocol.InvalidFrom: (u'invalid-from', '')
cl = xmpp.Client('myserver.com')
if not cl.connect(server=('mysefver.com',5223)):
raise IOError('cannot connect to server')
cl.RegisterHandler('message',messageHandler)
cl.auth('myemail@myserver.com', 'mypassword', 'statusbot')
cl.sendInitPrese... | xmpp with python: xmpp.protocol.InvalidFrom: (u'invalid-from', '') | cl = xmpp.Client('myserver.com')
if not cl.connect(server=('mysefver.com',5223)):
raise IOError('cannot connect to server')
cl.RegisterHandler('message',messageHandler)
cl.auth('myemail@myserver.com', 'mypassword', 'statusbot')
cl.sendInitPresence()
msgtext = formatToDo(cal, 'text')
message = xmpp.Message('another... | [
"From the XMPP protocol specification:\n\nIf the value of the 'from'\n address does not match the hostname represented by the Receiving\n Server when opening the TCP connection (or any validated domain\n thereof, such as a validated subdomain of the Receiving Server's\n hostname or another validated domain host... | [
4
] | [] | [] | [
"bots",
"python",
"xmpp"
] | stackoverflow_0001265146_bots_python_xmpp.txt |
Q:
Django Forms, Display Error on ModelMultipleChoiceField
I'm having an issue getting validation error messages to display for a particular field in a Django form, where the field in question is a ModelMultipleChoiceField.
In the clean(self) method for the Form, I try to add the error message to the field like so:
m... | Django Forms, Display Error on ModelMultipleChoiceField | I'm having an issue getting validation error messages to display for a particular field in a Django form, where the field in question is a ModelMultipleChoiceField.
In the clean(self) method for the Form, I try to add the error message to the field like so:
msg = 'error'
self._errors['field_name'] = ErrorList([msg])
ra... | [
"Yeah, it sounds like you're doing it wrong.\nYou should be using the clean_ method instead. Read through that whole document, in fact - it's very informative.\n",
"Why are you instantiating an ErrorList and writing to self._errors directly? Calling \"raise forms.ValidationError(msg)\" takes care of all that alre... | [
2,
0
] | [] | [] | [
"django",
"forms",
"python",
"validation"
] | stackoverflow_0000265888_django_forms_python_validation.txt |
Q:
How do I do database transactions with psycopg2/python db api?
Im fiddling with psycopg2 , and while there's a .commit() and .rollback() there's no .begin() or similar to start a transaction , or so it seems ?
I'd expect to be able to do
db.begin() # possible even set the isolation level here
curs = db.cursor()
c... | How do I do database transactions with psycopg2/python db api? | Im fiddling with psycopg2 , and while there's a .commit() and .rollback() there's no .begin() or similar to start a transaction , or so it seems ?
I'd expect to be able to do
db.begin() # possible even set the isolation level here
curs = db.cursor()
cursor.execute('select etc... for update')
...
cursor.execute('update... | [
"Use db.set_isolation_level(n), assuming db is your connection object. As Federico wrote here, the meaning of n is:\n0 -> autocommit\n1 -> read committed\n2 -> serialized (but not officially supported by pg)\n3 -> serialized\n\nAs documented here, psycopg2.extensions gives you symbolic constants for the purpose:\nS... | [
34,
18,
9
] | [] | [] | [
"database",
"postgresql",
"python"
] | stackoverflow_0001219326_database_postgresql_python.txt |
Q:
System standard sound in Python
How play standard system sounds from a Python script?
I'm writing a GUI program in wxPython that needs to beep on events to attract user's attention, maybe there are functions in wxPython I can utilize?
A:
on windows you could use winsound and I suppose curses.beep on Unix.
A:
f... | System standard sound in Python | How play standard system sounds from a Python script?
I'm writing a GUI program in wxPython that needs to beep on events to attract user's attention, maybe there are functions in wxPython I can utilize?
| [
"on windows you could use winsound and I suppose curses.beep on Unix.\n",
"from the documentation, you could use wx.Bell() function (not tested though)\n",
"From the documentation:\n\nwxTopLevelWindow::RequestUserAttention\nvoid RequestUserAttention(int flags =\n wxUSER_ATTENTION_INFO)\nUse a system-dependent ... | [
3,
2,
1
] | [] | [] | [
"audio",
"python",
"system_sounds",
"wxpython"
] | stackoverflow_0001265599_audio_python_system_sounds_wxpython.txt |
Q:
Changing height of an object in wxPython
How to change only hight of an object in wxPython, leaving its width automatic? In my case it's a TextCtrl.
How to make the height of the window available for change and lock the width?
A:
For the width or height to be automatically determined based on context you use for... | Changing height of an object in wxPython |
How to change only hight of an object in wxPython, leaving its width automatic? In my case it's a TextCtrl.
How to make the height of the window available for change and lock the width?
| [
"For the width or height to be automatically determined based on context you use for it the value of -1, for example (-1, 100) for a height of 100 and automatic width.\nThe default size for controls is usually (-1, -1).\nIf a width or height is specified and the sizer item for the control doesn't have wx.EXPAND fla... | [
6
] | [] | [] | [
"python",
"size",
"wxpython"
] | stackoverflow_0001265821_python_size_wxpython.txt |
Q:
Python non-trivial C++ Extension
I have fairly large C++ library with several sub-libraries that support it, and I need to turn the whole thing into a python extension. I'm using distutils because it needs to be cross-platform, but if there's a better tool I'm open to suggestions.
Is there a way to make distutils... | Python non-trivial C++ Extension | I have fairly large C++ library with several sub-libraries that support it, and I need to turn the whole thing into a python extension. I'm using distutils because it needs to be cross-platform, but if there's a better tool I'm open to suggestions.
Is there a way to make distutils first compile the sub-libraries, and ... | [
"I do just this with a massive C++ library in our product. There are several tools out there that can help you automate the task of writing bindings: the most popular is SWIG, which has been around a while, is used in lots of projects, and generally works very well. \nThe biggest thing against SWIG (in my opinio... | [
10
] | [] | [] | [
"c++",
"distutils",
"py++",
"python",
"swig"
] | stackoverflow_0001266570_c++_distutils_py++_python_swig.txt |
Q:
How to show hidden autofield in django formset
A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?
At the moment, the model is declared as,
class MyModel:
locid = models.AutoField(primary_key=True)
...
When this is rendered using Django formsets,
c... | How to show hidden autofield in django formset | A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?
At the moment, the model is declared as,
class MyModel:
locid = models.AutoField(primary_key=True)
...
When this is rendered using Django formsets,
class MyModelForm(ModelForm):
class Meta:
model... | [
"Try changing the default field type:\nfrom django import forms\nclass MyModelForm(ModelForm):\n locid = forms.IntegerField(min_value=1, required=True)\n class Meta:\n model = MyModel\n fields = ('locid', 'name')\n\nEDIT: Tested and works...\n",
"As you say, you are not using the custom form you have defi... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"formset",
"python"
] | stackoverflow_0000896153_django_formset_python.txt |
Q:
substituting in a file
I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.
i wrote a program to do the above,
from scipy import *
import numpy
from numpy import asarray
from string import Template
def Dat(Par):
Par = numpy.asarray(Par)
Par[0] = a1... | substituting in a file | I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.
i wrote a program to do the above,
from scipy import *
import numpy
from numpy import asarray
from string import Template
def Dat(Par):
Par = numpy.asarray(Par)
Par[0] = a1
Par[1] = a2
Par[2] = ... | [
"The error is here:\nInit = numpy.asarray [(10.0, 200.0, 500.0, 10.0)]\n\nwhich was probably meant to be\nInit = numpy.asarray ([10.0, 200.0, 500.0, 10.0])\n\n(note the swapped braces/parens). Since python found a \"[\" after \"asarray\" (which is a function), it throws an error, because you cannot subscribe (i.e. ... | [
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001261578_python.txt |
Q:
Combining two QMainWindows
Good day pythonistas and the rest of the coding crowd,
I have two QMainWindows designed and coded separately. I need to:
display first
on a button-press close the first window
construct and display the second window using the arguments from the first
I have tried to design a third clas... | Combining two QMainWindows | Good day pythonistas and the rest of the coding crowd,
I have two QMainWindows designed and coded separately. I need to:
display first
on a button-press close the first window
construct and display the second window using the arguments from the first
I have tried to design a third class to control the flow but it doe... | [
"Answer:\nI had some trouble with connecting signals recently. I found that it worked when I removed the parentheses from the QtCore.SIGNAL.\ntry changing this:\nQtCore.SIGNAL(\"destroyed()\")\n\nto this:\nQtCore.SIGNAL(\"destroyed\")\n\nReference:\nThis is because your are using the \"old style\" signals/slots ac... | [
1,
0
] | [] | [] | [
"pyqt",
"python",
"signals_slots"
] | stackoverflow_0001265646_pyqt_python_signals_slots.txt |
Q:
How do I calculate the numeric value of a string with unicode components in python?
Along the lines of my previous question, How do I convert unicode characters to floats in Python? , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.
For example... | How do I calculate the numeric value of a string with unicode components in python? | Along the lines of my previous question, How do I convert unicode characters to floats in Python? , I would like to find a more elegant solution to calculating the value of a string that contains unicode numeric values.
For example, take the strings "1⅕" and "1 ⅕". I would like these to resolve to 1.2
I know that I ca... | [
"I think this is what you want...\nimport unicodedata\ndef eval_unicode(s):\n #sum all the unicode fractions\n u = sum(map(unicodedata.numeric, filter(lambda x: unicodedata.category(x)==\"No\",s)))\n #eval the regular digits (with optional dot) as a float, or default to 0\n n = float(\"\".join(filter(la... | [
2,
1,
0
] | [
"I think you'll need a regular expression, explicitly listing the characters that you want to support. Not all numerical characters are suitable for the kind of composition that you envision - for example, what should be the numerical value of\nu\"4\\N{CIRCLED NUMBER FORTY TWO}2\\N{SUPERSCRIPT SIX}\"\n\n???\nDo \nf... | [
-1
] | [
"floating_point",
"python",
"string",
"unicode"
] | stackoverflow_0001267314_floating_point_python_string_unicode.txt |
Q:
What is Python's "built-in method acquire"? How can I speed it up?
I'm writing a Python program with a lot of file access. It's running surprisingly slowly, so I used cProfile to find out what was taking the time.
It seems there's a lot of time spent in what Python is reporting as "{built-in method acquire}". I ... | What is Python's "built-in method acquire"? How can I speed it up? | I'm writing a Python program with a lot of file access. It's running surprisingly slowly, so I used cProfile to find out what was taking the time.
It seems there's a lot of time spent in what Python is reporting as "{built-in method acquire}". I have no idea what this method is. What is it, and how can I speed up my... | [
"Without seeing your code, it is hard to guess. But to guess I would say that it is the threading.Lock.acquire method. Part of your code is trying to get a threading lock, and it is waiting until it has got it.\nThere may be simple ways of fixing it by\n\nrestructuring your file access,\nnot locking,\nusing blockin... | [
6,
0,
0
] | [] | [] | [
"optimization",
"performance",
"profiling",
"python"
] | stackoverflow_0000530127_optimization_performance_profiling_python.txt |
Q:
Python standard module for emulating geometric points
Is there a standard class in Python to emulate a geometric point that includes coordinates and a value, including arithmetic operations between the coordinates?
A:
If you just want standard matrix arithmetic operations for your coordinates, try numpy's array... | Python standard module for emulating geometric points | Is there a standard class in Python to emulate a geometric point that includes coordinates and a value, including arithmetic operations between the coordinates?
| [
"If you just want standard matrix arithmetic operations for your coordinates, try numpy's array type.\n"
] | [
1
] | [] | [] | [
"geometry",
"python"
] | stackoverflow_0001267968_geometry_python.txt |
Q:
Standard Solution for Decoding Additive Numbers
From the Oracle docs.
A number representing one or more statistics class. The following class numbers are additive:
1 - User
2 - Redo
4 - Enqueue
8 - Cache
16 - OS
32 - Real Application Clusters
64 - SQL
128 - Debug
It there a standard solution for... | Standard Solution for Decoding Additive Numbers | From the Oracle docs.
A number representing one or more statistics class. The following class numbers are additive:
1 - User
2 - Redo
4 - Enqueue
8 - Cache
16 - OS
32 - Real Application Clusters
64 - SQL
128 - Debug
It there a standard solution for taking say 22 and decoding that into 16, 4, and 2? M... | [
"Each of those values corresponds to a single bit. So use the binary.\n1<<0 - 1 - User\n1<<1 - 2 - Redo\n1<<2 - 4 - Enqueue\n1<<3 - 8 - Cache\n1<<4 - 16 - OS\n1<<5 - 32 - Real Application Clusters\n1<<6 - 64 - SQL\n1<<7 - 128 - Debug\n\nUse & to test for each bit.\ndef decode(value):\n readable = []\n flags ... | [
4,
4
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0001268050_algorithm_python.txt |
Q:
Importing Model / Lib Class and calling from controller
I'm new to python and pylons although experienced in PHP.
I'm trying to write a model class which will act as a my data access to my database (couchdb). My problem is simple
My model looks like this and is called models/BlogModel.py
from couchdb import *
c... | Importing Model / Lib Class and calling from controller | I'm new to python and pylons although experienced in PHP.
I'm trying to write a model class which will act as a my data access to my database (couchdb). My problem is simple
My model looks like this and is called models/BlogModel.py
from couchdb import *
class BlogModel:
def getTitles(self):
# code to g... | [
"x = BlogModel.BlogModel()\n\nOr, more verbosely:\nAfter you did the import, you have an object in your namespace called 'BlogModel'. That object is the BlogModel module. (The module name comes from the filename.) Inside that module, there is a class object called 'BlogModel', which is what you were after. (The... | [
2
] | [] | [] | [
"model_view_controller",
"pylons",
"python"
] | stackoverflow_0001268432_model_view_controller_pylons_python.txt |
Q:
Does __str__() call decode() method behind scenes?
It seems to me that built-in functions __repr__ and __str__ have an important difference in their base definition.
>>> t2 = u'\u0131\u015f\u0131k'
>>> print t2
ışık
>>> t2
Out[0]: u'\u0131\u015f\u0131k'
t2.decode raises an error since t2 is a unicode string.
>>> ... | Does __str__() call decode() method behind scenes? | It seems to me that built-in functions __repr__ and __str__ have an important difference in their base definition.
>>> t2 = u'\u0131\u015f\u0131k'
>>> print t2
ışık
>>> t2
Out[0]: u'\u0131\u015f\u0131k'
t2.decode raises an error since t2 is a unicode string.
>>> enc = 'utf-8'
>>> t2.decode(enc)
-----------------------... | [
"Basically, __str__ can only output ascii strings. Since t2 contains unicode codepoints above ascii, it cannot be represented with just a string. __repr__, on the other hand, tries to output the python code needed to recreate the object. You'll see that the output from repr(t2) (this syntax is preferred to t2.__rep... | [
7,
5,
2,
0
] | [] | [] | [
"django",
"python",
"string",
"unicode"
] | stackoverflow_0001267754_django_python_string_unicode.txt |
Q:
Regex Matching Error
I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.
I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says
rai... | Regex Matching Error | I am new to Python (I dont have any programming training either), so please keep that in mind as I ask my question.
I am trying to search a retrieved webpage and find all links using a specified pattern. I have done this successfully in other scripts, but I am getting an error that says
raise error, v # invalid expr... | [
"You need to escape the literal '?' and the literal '(' and ')' that you are trying to match.\nAlso, instead of '?+', I think you're looking for the non-greedy matching provided by '+?'.\nMore documentation here.\nFor your case, try this:\npattern = r'<a href=\"http://forums.epicgames.com/archive/index.php\\?t-([0-... | [
1,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001268761_python_regex.txt |
Q:
Really long query
How do u do long query? Is there way to optimize it?
I would do complicated and long query:
all_accepted_parts = acceptedFragment.objects.filter(fragmentID = fragment.objects.filter(categories = fragmentCategory.objects.filter(id=1)))
but it doesn't work, i get:
Error binding parameter 0 - prob... | Really long query | How do u do long query? Is there way to optimize it?
I would do complicated and long query:
all_accepted_parts = acceptedFragment.objects.filter(fragmentID = fragment.objects.filter(categories = fragmentCategory.objects.filter(id=1)))
but it doesn't work, i get:
Error binding parameter 0 - probably unsupported type.
... | [
"If it's not working, you can't optimize it. First make it work.\nAt first glance, it seems that you have really mixed concepts about fields, relationships and equality/membership. First go thought the docs, and build your query piece by piece on the python shell (likely from the inside out).\nJust a shot in the ... | [
4,
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001268899_django_django_models_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.