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:
Russian-to-English Parallel Word Corpus?
I am looking for a simple Russian to English word corpus. It can be as simple as a csv that lists a russian word in the first column and the equivalent English word in the second. Any ideas where I can find such a thing? Does the NLTK toolkit have something like this?
Thanks
A:
You can use English-Russian Müller Dictionary which is freely available in DICT format. You will need to invert it manually.
| Russian-to-English Parallel Word Corpus? | I am looking for a simple Russian to English word corpus. It can be as simple as a csv that lists a russian word in the first column and the equivalent English word in the second. Any ideas where I can find such a thing? Does the NLTK toolkit have something like this?
Thanks
| [
"You can use English-Russian Müller Dictionary which is freely available in DICT format. You will need to invert it manually.\n"
] | [
5
] | [] | [] | [
"corpus",
"lexicon",
"python",
"translation"
] | stackoverflow_0002785371_corpus_lexicon_python_translation.txt |
Q:
Extract points within a shape from a raster
I have a raster file (basically 2D array) with close to a million points. I am trying to extract a circle from the raster (and all the points that lie within the circle). Using ArcGIS is exceedingly slow for this. Can anyone suggest any image processing library that is both easy to learn and powerful and quick enough for something like this?
Thanks!
A:
Extracting a subset of points efficiently depends on the exact format you are using. Assuming you store your raster as a numpy array of integers, you can extract points like this:
from numpy import *
def points_in_circle(circle, arr):
"A generator to return all points whose indices are within given circle."
i0,j0,r = circle
def intceil(x):
return int(ceil(x))
for i in xrange(intceil(i0-r),intceil(i0+r)):
ri = sqrt(r**2-(i-i0)**2)
for j in xrange(intceil(j0-ri),intceil(j0+ri)):
yield arr[i][j]
points_in_circle will create a generator returning all points. Please note that I used yield instead of return. This function does not actually return point values, but describes how to find all of them. It creates a sequential iterator over values of points within circle. See Python documentation for more details how yield works.
I used the fact that for circle we can explicitly loop only over inner points. For more complex shapes you may loop over the points of the extent of a shape, and then check if a point belongs to it. The trick is not to check every point, only a narrow subset of them.
Now an example of how to use points_in_circle:
# raster dimensions, 10 million points
N, M = 3200, 3200
# circle center and its radius in index space
i0, j0, r = 70, 20, 12.3
raster = fromfunction(lambda i,j: 100+10*i+j, (N, M), dtype=int)
print "raster is ready"
print raster
pts_iterator = points_in_circle((i0,j0,r), raster) # very quick, do not extract points yet
pts = array(list(pts_iterator)) # actually extract all points
print pts.size, "points extracted, sum = ", sum(pts)
On a raster of 10 million integers it is pretty quick.
Please describe file format or put a sample somewhere if you need more specific answer.
A:
Numpy allows you to do this, and is extremely fast:
import numpy
all_points = numpy.random.random((1000, 1000)) # Input array
# Size of your array of points all_points:
(image_size_x, image_size_y) = all_points.shape
# Disk definition:
(center_x, center_y) = (500, 500)
radius = 10
x_grid, y_grid = numpy.meshgrid(numpy.arange(image_size_x),
numpy.arange(image_size_y))
# Array of booleans with the disk shape
disk = ((x_grid-center_x)**2 + (y_grid-center_y)**2) <= radius**2
# You can now do all sorts of things with the mask "disk":
# For instance, the following array has only 317 points (about pi*radius**2):
points_in_disk = all_points[disk]
# You can also use masked arrays:
points_in_circle2 = numpy.ma.masked_array(all_points, ~disk)
from matplotlib import pyplot
pyplot.imshow(points_in_circle2)
A:
You need a library that can read your raster. I am not sure how to do that in Python but you could look at geotools (especially with some of the new raster library integration) if you want to program in Java. If you are good with C I would reccomend using something like GDAL.
If you want to look at a desktop tool you could look at extending QGIS with python to do the operation above.
If I remember correctly, the Raster extension to PostGIS may support clipping rasters based upon vectors. This means you would need to create your circles to features in the DB and then import your raster but then you might be able to use SQL to extract your values.
If you are really just a text file with numbers in a grid then I would go with the suggestions above.
| Extract points within a shape from a raster | I have a raster file (basically 2D array) with close to a million points. I am trying to extract a circle from the raster (and all the points that lie within the circle). Using ArcGIS is exceedingly slow for this. Can anyone suggest any image processing library that is both easy to learn and powerful and quick enough for something like this?
Thanks!
| [
"Extracting a subset of points efficiently depends on the exact format you are using. Assuming you store your raster as a numpy array of integers, you can extract points like this:\nfrom numpy import *\n\ndef points_in_circle(circle, arr):\n \"A generator to return all points whose indices are within given circle.\"\n i0,j0,r = circle\n def intceil(x):\n return int(ceil(x))\n for i in xrange(intceil(i0-r),intceil(i0+r)):\n ri = sqrt(r**2-(i-i0)**2)\n for j in xrange(intceil(j0-ri),intceil(j0+ri)):\n yield arr[i][j]\n\npoints_in_circle will create a generator returning all points. Please note that I used yield instead of return. This function does not actually return point values, but describes how to find all of them. It creates a sequential iterator over values of points within circle. See Python documentation for more details how yield works.\nI used the fact that for circle we can explicitly loop only over inner points. For more complex shapes you may loop over the points of the extent of a shape, and then check if a point belongs to it. The trick is not to check every point, only a narrow subset of them.\nNow an example of how to use points_in_circle:\n# raster dimensions, 10 million points\nN, M = 3200, 3200\n# circle center and its radius in index space\ni0, j0, r = 70, 20, 12.3\n\nraster = fromfunction(lambda i,j: 100+10*i+j, (N, M), dtype=int)\nprint \"raster is ready\"\nprint raster\n\npts_iterator = points_in_circle((i0,j0,r), raster) # very quick, do not extract points yet\npts = array(list(pts_iterator)) # actually extract all points\nprint pts.size, \"points extracted, sum = \", sum(pts)\n\nOn a raster of 10 million integers it is pretty quick.\nPlease describe file format or put a sample somewhere if you need more specific answer.\n",
"Numpy allows you to do this, and is extremely fast:\nimport numpy\n\nall_points = numpy.random.random((1000, 1000)) # Input array\n# Size of your array of points all_points:\n(image_size_x, image_size_y) = all_points.shape\n# Disk definition:\n(center_x, center_y) = (500, 500)\nradius = 10\n\nx_grid, y_grid = numpy.meshgrid(numpy.arange(image_size_x),\n numpy.arange(image_size_y))\n# Array of booleans with the disk shape\ndisk = ((x_grid-center_x)**2 + (y_grid-center_y)**2) <= radius**2\n\n# You can now do all sorts of things with the mask \"disk\":\n\n# For instance, the following array has only 317 points (about pi*radius**2):\npoints_in_disk = all_points[disk]\n# You can also use masked arrays:\npoints_in_circle2 = numpy.ma.masked_array(all_points, ~disk)\nfrom matplotlib import pyplot\npyplot.imshow(points_in_circle2)\n\n",
"You need a library that can read your raster. I am not sure how to do that in Python but you could look at geotools (especially with some of the new raster library integration) if you want to program in Java. If you are good with C I would reccomend using something like GDAL.\nIf you want to look at a desktop tool you could look at extending QGIS with python to do the operation above.\nIf I remember correctly, the Raster extension to PostGIS may support clipping rasters based upon vectors. This means you would need to create your circles to features in the DB and then import your raster but then you might be able to use SQL to extract your values.\nIf you are really just a text file with numbers in a grid then I would go with the suggestions above. \n"
] | [
2,
2,
1
] | [] | [] | [
"arcgis",
"python",
"raster"
] | stackoverflow_0002770356_arcgis_python_raster.txt |
Q:
Migrating from SQLAlchemy to MongoDB in Pylons
Is there a migration guide for the the models aspect in pylons, syntax with SQLAlchemy to MongoDB?
A:
I am not aware of any guide, but if you're looking for something ORM-like, check out Mongokit http://bitbucket.org/namlook/mongokit/wiki/Home.
That said, MongoDB fits Python dictionaries very well. You might not need an ORM at all.
| Migrating from SQLAlchemy to MongoDB in Pylons | Is there a migration guide for the the models aspect in pylons, syntax with SQLAlchemy to MongoDB?
| [
"I am not aware of any guide, but if you're looking for something ORM-like, check out Mongokit http://bitbucket.org/namlook/mongokit/wiki/Home.\nThat said, MongoDB fits Python dictionaries very well. You might not need an ORM at all.\n"
] | [
1
] | [] | [] | [
"mongodb",
"python",
"sqlalchemy"
] | stackoverflow_0002776998_mongodb_python_sqlalchemy.txt |
Q:
How to build a Django form which requires a delay to be re-submitted?
In order to avoid spamming, I would like to add a waiting time to re-submit a form (i.e. the user should wait a few seconds to submit the form, except the first time that this form is submitted).
To do that, I added a timestamp to my form (and a security_hash field containing the timestamp plus the settings.SECRET_KEY which ensures that the timestamp is not fiddled with). This look like:
class MyForm(forms.Form):
timestamp = forms.IntegerField(widget=forms.HiddenInput)
security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
# + some other fields..
# + methods to build the hash and to clean the timestamp...
# (it is based on django.contrib.comments.forms.CommentSecurityForm)
def clean_timestamp(self):
"""Make sure the delay is over (5 seconds)."""
ts = self.cleaned_data["timestamp"]
if not time.time() - ts > 5:
raise forms.ValidationError("Timestamp check failed")
return ts
# etc...
This works fine. However there is still an issue: the timestamp is checked the first time the form is submitted by the user, and I need to avoid this.
Any idea to fix it ?
Thank you ! :-)
A:
the timestamp is checked the first time the form is submitted by the user, and I need to avoid this.
If this is the problem, couldn't you create the form setting the timestamp -5 minutes?
A:
One way to do this is to set an initial value to time, let's say 0, and update it to the current timestamp once the form validates, and only check timestamp when it's not 0:
class MyForm(forms.Form):
timestamp = forms.IntegerField(widget=forms.HiddenInput, initial=0)
#look at the initial = 0
security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
def clean_timestamp(self):
"""Make sure the delay is over (5 seconds)."""
ts = self.cleaned_data["timestamp"]
if timestamp != 0 and not time.time() - ts > 5:
raise forms.ValidationError("Timestamp check failed")
return ts
def clean(self):
cleaned_data = self.cleaned_data
if len(self._errors) == 0: #it validates
cleaned_data["timestamp"] = time.time()
return cleaned_data
Another possible solution is to use sessions. It's safer but not bulletproof. With the previous apporach the user can send the same post data several times, and the form will validate several times (cause he's sending the same timestamp). With sessions you need the user to have cookies enabled, but they won't be able to send post data that validates quicker than 5 seconds.
This way once a correct form submission happens you can save the time in a user's session key and check that before revalidating your form. This is easily done in a view. If you want to do it at the form logic level, you need to create your own clean method in the form that takes the request (so you can use the session). Be careful, the user can clean his cookies and post as a "new" user.
Hope this helps.
| How to build a Django form which requires a delay to be re-submitted? | In order to avoid spamming, I would like to add a waiting time to re-submit a form (i.e. the user should wait a few seconds to submit the form, except the first time that this form is submitted).
To do that, I added a timestamp to my form (and a security_hash field containing the timestamp plus the settings.SECRET_KEY which ensures that the timestamp is not fiddled with). This look like:
class MyForm(forms.Form):
timestamp = forms.IntegerField(widget=forms.HiddenInput)
security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
# + some other fields..
# + methods to build the hash and to clean the timestamp...
# (it is based on django.contrib.comments.forms.CommentSecurityForm)
def clean_timestamp(self):
"""Make sure the delay is over (5 seconds)."""
ts = self.cleaned_data["timestamp"]
if not time.time() - ts > 5:
raise forms.ValidationError("Timestamp check failed")
return ts
# etc...
This works fine. However there is still an issue: the timestamp is checked the first time the form is submitted by the user, and I need to avoid this.
Any idea to fix it ?
Thank you ! :-)
| [
"\nthe timestamp is checked the first time the form is submitted by the user, and I need to avoid this.\n\nIf this is the problem, couldn't you create the form setting the timestamp -5 minutes? \n",
"One way to do this is to set an initial value to time, let's say 0, and update it to the current timestamp once the form validates, and only check timestamp when it's not 0:\nclass MyForm(forms.Form):\n timestamp = forms.IntegerField(widget=forms.HiddenInput, initial=0)\n #look at the initial = 0\n\n security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)\n\n\n def clean_timestamp(self):\n \"\"\"Make sure the delay is over (5 seconds).\"\"\"\n ts = self.cleaned_data[\"timestamp\"]\n if timestamp != 0 and not time.time() - ts > 5:\n raise forms.ValidationError(\"Timestamp check failed\")\n return ts\n\n def clean(self):\n cleaned_data = self.cleaned_data\n if len(self._errors) == 0: #it validates\n cleaned_data[\"timestamp\"] = time.time()\n return cleaned_data\n\nAnother possible solution is to use sessions. It's safer but not bulletproof. With the previous apporach the user can send the same post data several times, and the form will validate several times (cause he's sending the same timestamp). With sessions you need the user to have cookies enabled, but they won't be able to send post data that validates quicker than 5 seconds.\nThis way once a correct form submission happens you can save the time in a user's session key and check that before revalidating your form. This is easily done in a view. If you want to do it at the form logic level, you need to create your own clean method in the form that takes the request (so you can use the session). Be careful, the user can clean his cookies and post as a \"new\" user.\nHope this helps.\n"
] | [
2,
2
] | [] | [] | [
"django",
"django_forms",
"forms",
"python",
"timestamp"
] | stackoverflow_0002784111_django_django_forms_forms_python_timestamp.txt |
Q:
Parsing html for domain links
I have a script that parses an html page for all the links within it. I am getting all of them fine, but I have a list of domains I want to compare it against. So a sample list contains
list=['www.domain.com', 'sub.domain.com']
But I may have a list of links that look like
http://domain.com
http://sub.domain.com/some/other/page
I can strip off the http:// just fine, but in the two example links I just posted, they both should match. The first I would like to match against the www.domain.com, and the second, I would like to match against the subdomain in the list.
Right now I am using url2lib for parsing the html. What are my options in completely this task?
A:
You might consider stripping 'www.' from the list and doing something as simple as:
url = 'domain.com/'
for domain in list:
if url.startswith(domain):
... do something ...
Or trying both wont hurt either I spose:
url = 'domain.com/'
for domain in list:
domain_minus_www = domain
if domain_minus_www.startswith('www.'):
domain_minus_www = domain_minus_www[4:]
if url.startswith(domain) or url.startswith(domain_minus_www):
... do something ...
| Parsing html for domain links | I have a script that parses an html page for all the links within it. I am getting all of them fine, but I have a list of domains I want to compare it against. So a sample list contains
list=['www.domain.com', 'sub.domain.com']
But I may have a list of links that look like
http://domain.com
http://sub.domain.com/some/other/page
I can strip off the http:// just fine, but in the two example links I just posted, they both should match. The first I would like to match against the www.domain.com, and the second, I would like to match against the subdomain in the list.
Right now I am using url2lib for parsing the html. What are my options in completely this task?
| [
"You might consider stripping 'www.' from the list and doing something as simple as:\nurl = 'domain.com/'\nfor domain in list:\n if url.startswith(domain):\n ... do something ...\n\nOr trying both wont hurt either I spose:\nurl = 'domain.com/'\nfor domain in list:\n domain_minus_www = domain\n if domain_minus_www.startswith('www.'):\n domain_minus_www = domain_minus_www[4:]\n if url.startswith(domain) or url.startswith(domain_minus_www):\n ... do something ...\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002785714_python.txt |
Q:
python xml.dom.minidom.Attr question
Getting attributes using minidom in Python, one uses the "attributes" property. e.g. node.attributes["id"].value
So if I have <a id="foo"></a>, that should give me "foo". node.attributes["id"] does not return the value of the named attribute, but an xml.dom.minidom.Attr instance.
But looking at the help for Attr, by doing help('xml.dom.minidom.Attr'), nowhere is this magic "value" property mentioned. I like to learn APIs by looking at the type hierarchy, instance methods etc. Where did this "value" property come from?? Why is it not listed in the Attr class' page? The only data descriptors mentioned are isId, localName and schemaType. Its also not inherited from any superclasses. Since I'm new to Python, would some of the Python gurus enlighten?
A:
The minidom is just an implementation of the xml.dom interfaces, so any docs specifically on minidom will only be about its peculiarities or limitations wrt xml.dom itself.
The xml.dom docs on Attr say, and I quote:
Attr inherits from Node, so inherits
all its attributes.
The docs on Node actually name the attribute differently: nodeValue. But, indeed...:
>>> import xml.dom.minidom as xdm
>>> dom = xdm.parseString('<foo bar="baz"/>')
>>> root = dom.documentElement
>>> atr = root.getAttributeNode('bar')
>>> atr.nodeValue
u'baz'
The fact that the documented nodeValue attribute has an _un_documented alias value may be considered unfortunate, but you can always stick with the documented, and therefore arguably right, attribute name, nodeValue. Yes, it's verbose, but then so is all of minidom, as well as slower than the excellent xml.etree.ElementTree (esp. in the latter's C implementation, xml.etree.cElementTree), so presumably if you choose to use minidom it must be because you like extensive verbosity...;-).
A:
Geez, never noticed that before. You're not kidding, node.value isn't mentioned anywhere. It is definitely being set in the code though under def __setitem__ in xml.dom.minidom.
Not sure what to say other than, it looks like you'll have to use that.
| python xml.dom.minidom.Attr question | Getting attributes using minidom in Python, one uses the "attributes" property. e.g. node.attributes["id"].value
So if I have <a id="foo"></a>, that should give me "foo". node.attributes["id"] does not return the value of the named attribute, but an xml.dom.minidom.Attr instance.
But looking at the help for Attr, by doing help('xml.dom.minidom.Attr'), nowhere is this magic "value" property mentioned. I like to learn APIs by looking at the type hierarchy, instance methods etc. Where did this "value" property come from?? Why is it not listed in the Attr class' page? The only data descriptors mentioned are isId, localName and schemaType. Its also not inherited from any superclasses. Since I'm new to Python, would some of the Python gurus enlighten?
| [
"The minidom is just an implementation of the xml.dom interfaces, so any docs specifically on minidom will only be about its peculiarities or limitations wrt xml.dom itself.\nThe xml.dom docs on Attr say, and I quote:\n\nAttr inherits from Node, so inherits\n all its attributes.\n\nThe docs on Node actually name the attribute differently: nodeValue. But, indeed...:\n>>> import xml.dom.minidom as xdm\n>>> dom = xdm.parseString('<foo bar=\"baz\"/>')\n>>> root = dom.documentElement\n>>> atr = root.getAttributeNode('bar')\n>>> atr.nodeValue\nu'baz'\n\nThe fact that the documented nodeValue attribute has an _un_documented alias value may be considered unfortunate, but you can always stick with the documented, and therefore arguably right, attribute name, nodeValue. Yes, it's verbose, but then so is all of minidom, as well as slower than the excellent xml.etree.ElementTree (esp. in the latter's C implementation, xml.etree.cElementTree), so presumably if you choose to use minidom it must be because you like extensive verbosity...;-).\n",
"Geez, never noticed that before. You're not kidding, node.value isn't mentioned anywhere. It is definitely being set in the code though under def __setitem__ in xml.dom.minidom.\nNot sure what to say other than, it looks like you'll have to use that.\n"
] | [
4,
0
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0002785703_minidom_python_xml.txt |
Q:
Best practices for parsing HTML from Wikipedia for iPhone viewing?
I am building an iPhone Wikipeida game app, that requires modifying the default Wiki HTML a little bit (mostly simplifying the page).
So far I am directly downloading the HTML output from en.wikipedia.org/wiki/Article_Foo to a python Google App Engine, and then modify its CSS and HTML structure, cache it, and finally output to iPhone. It works but I find this method quite tedious, there must be a better method?
Please note that I use App Engine not just for parsing the Wiki, but the game also requires it to keep the stores...etc, hence not a overkill. Also, I would prefer doing all the work with python on App Engine, to keep the iPhone client as thin and mobile as possible (XML on iPhone is a big no fun)
Thanks a lot.
=======
Nick mentions why not use the mobile Wiki which already optimizes for iPhone. However, the issue is that it goes down quite frequently (every couple weeks or so), also its HTML structure changes quite frequently too.
A:
You can use the MediaWiki API to download the markup text and use some API tools for Python that could make the process/modify work easier.
Caching and outputting to iPhone is fine. I believe there is not much to simplify here.
A:
Why not just fetch the mobile version of the page from http://en.m.wikipedia.org/? This is already formatted for mobile devices.
A:
You can set up your own copy of the server used by m.wikimedia.org:
http://github.com/hcatlin/wikimedia-mobile
It's written in Ruby, but this shouldn't be an issue if your app just uses the HTML output.
| Best practices for parsing HTML from Wikipedia for iPhone viewing? | I am building an iPhone Wikipeida game app, that requires modifying the default Wiki HTML a little bit (mostly simplifying the page).
So far I am directly downloading the HTML output from en.wikipedia.org/wiki/Article_Foo to a python Google App Engine, and then modify its CSS and HTML structure, cache it, and finally output to iPhone. It works but I find this method quite tedious, there must be a better method?
Please note that I use App Engine not just for parsing the Wiki, but the game also requires it to keep the stores...etc, hence not a overkill. Also, I would prefer doing all the work with python on App Engine, to keep the iPhone client as thin and mobile as possible (XML on iPhone is a big no fun)
Thanks a lot.
=======
Nick mentions why not use the mobile Wiki which already optimizes for iPhone. However, the issue is that it goes down quite frequently (every couple weeks or so), also its HTML structure changes quite frequently too.
| [
"You can use the MediaWiki API to download the markup text and use some API tools for Python that could make the process/modify work easier.\nCaching and outputting to iPhone is fine. I believe there is not much to simplify here.\n",
"Why not just fetch the mobile version of the page from http://en.m.wikipedia.org/? This is already formatted for mobile devices.\n",
"You can set up your own copy of the server used by m.wikimedia.org:\nhttp://github.com/hcatlin/wikimedia-mobile\nIt's written in Ruby, but this shouldn't be an issue if your app just uses the HTML output.\n"
] | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"iphone",
"mediawiki",
"python",
"wiki"
] | stackoverflow_0002706416_google_app_engine_iphone_mediawiki_python_wiki.txt |
Q:
How to get data from a incoming email and then copy data to some directory
First of all, I have some time reading this page and I find very interesting, the content also has many questions and are very entertaining.
My question is about handling my incoming mail server, no matter if you use PHP, Perl, or Python.
I do not care, what if I want is the result which should be as close to:
I send an email to update@mydomain.com, this post will add a case such as photos, then when the mail reaches the server, the server takes to process mail and copy the attached files, in this case the photos to a folder / home / public_html / photos and then, if possible notify you if it was successful or not.
In advance thank you very much. And I hope and can be done. ñ_ñ
A:
Set up a pipe alias in /etc/aliases then restart the MTA:
update: |/usr/local/bin/myscript
Then just have the script send out an email once it's done processing.
| How to get data from a incoming email and then copy data to some directory | First of all, I have some time reading this page and I find very interesting, the content also has many questions and are very entertaining.
My question is about handling my incoming mail server, no matter if you use PHP, Perl, or Python.
I do not care, what if I want is the result which should be as close to:
I send an email to update@mydomain.com, this post will add a case such as photos, then when the mail reaches the server, the server takes to process mail and copy the attached files, in this case the photos to a folder / home / public_html / photos and then, if possible notify you if it was successful or not.
In advance thank you very much. And I hope and can be done. ñ_ñ
| [
"Set up a pipe alias in /etc/aliases then restart the MTA:\nupdate: |/usr/local/bin/myscript\n\nThen just have the script send out an email once it's done processing.\n"
] | [
2
] | [] | [] | [
"apache",
"email",
"linux",
"php",
"python"
] | stackoverflow_0002786007_apache_email_linux_php_python.txt |
Q:
How to write full chat server / client using python 2.5
I want to write server/client chat protocol using python-2.5 .
I want to make protocol similar to yahoo messenger or google-talk.
Please suggest me how to start.
Thanks
Reetesh Nigam
A:
You should look at Twisted Words. Twisted is a Python networking library, and Words is a chat component for it. It has support for XMPP/Jabber, the protocol used by Google Talk.
A:
I would suggest xmppy, though I'm sure Twisted Words (recommended by another answer) and jabber.py, python-xmpp, and no doubt many others, are also usable. Why not try them out a few of them and pick the one that best suits you?
A:
There are several popular Python libraries for working with XMPP, a/k/a the Jabber protocol, which Google Talk uses. Here is a review that will point you to 3 of them.
| How to write full chat server / client using python 2.5 | I want to write server/client chat protocol using python-2.5 .
I want to make protocol similar to yahoo messenger or google-talk.
Please suggest me how to start.
Thanks
Reetesh Nigam
| [
"You should look at Twisted Words. Twisted is a Python networking library, and Words is a chat component for it. It has support for XMPP/Jabber, the protocol used by Google Talk.\n",
"I would suggest xmppy, though I'm sure Twisted Words (recommended by another answer) and jabber.py, python-xmpp, and no doubt many others, are also usable. Why not try them out a few of them and pick the one that best suits you?\n",
"There are several popular Python libraries for working with XMPP, a/k/a the Jabber protocol, which Google Talk uses. Here is a review that will point you to 3 of them.\n"
] | [
3,
0,
0
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0002786128_python_python_2.5.txt |
Q:
Unable to import nltk in NetBeans
I am trying to import NLTK in my python code and I get this error:
Traceback (most recent call last):
File "/home/afs/NetBeansProjects/NER/getNE_followers.py", line 7, in <module>
import nltk
ImportError: No module named nltk
I am using NetBeans: 6.7.1, Python 2.6 NLTK.
My NLTK module is installed in /usr/local/lib/python2.6/dist-packages/nltk/ and I have added this in Python paths in Netbeans.
What am I missing here?
Thanks in advance.
A:
You might have default python installation on /usr/bin/python. So, In Netbeans preference, try to set python interpreter to /usr/local/bin/python instead of /usr/bin/python
A:
Rectified the problem. I had included the nltk path in the Netbeans global settings but the project was still using Jython 2.5 as its Python platform so the global settings never affected the project.
| Unable to import nltk in NetBeans | I am trying to import NLTK in my python code and I get this error:
Traceback (most recent call last):
File "/home/afs/NetBeansProjects/NER/getNE_followers.py", line 7, in <module>
import nltk
ImportError: No module named nltk
I am using NetBeans: 6.7.1, Python 2.6 NLTK.
My NLTK module is installed in /usr/local/lib/python2.6/dist-packages/nltk/ and I have added this in Python paths in Netbeans.
What am I missing here?
Thanks in advance.
| [
"You might have default python installation on /usr/bin/python. So, In Netbeans preference, try to set python interpreter to /usr/local/bin/python instead of /usr/bin/python\n",
"Rectified the problem. I had included the nltk path in the Netbeans global settings but the project was still using Jython 2.5 as its Python platform so the global settings never affected the project.\n"
] | [
1,
1
] | [] | [] | [
"netbeans",
"nltk",
"python"
] | stackoverflow_0002786384_netbeans_nltk_python.txt |
Q:
Google app engine: query that return entity ID using python
how do I return the entity ID using python in GAE?
Assuming I have following
class Names(db.Model):
name = db.StringProperty()
A:
You retrieve the entity, e.g. with a query, then you call .key().id() on that entity (will be None if the entity has no numeric id; see here for other info you can retrieve from a Key object).
A:
The question has long been answered.
(I am adding some full examples hopefully while not stepping on any toes...)
Getting an entity using a query; just getting the keys is faster and uses less CPU than retrieving the full entity:
query = Names.all(keys_only=True)
names = query.get() # this is a shorter equivalent to `query.fetch(limit=1)`
names.id()
From a template:
{{ names.id }}
GQL alternative, as suggested in a comment:
from google.appengine.ext import db
query = db.GqlQuery("SELECT __key__ FROM Names")
names = query.get()
names.id()
| Google app engine: query that return entity ID using python | how do I return the entity ID using python in GAE?
Assuming I have following
class Names(db.Model):
name = db.StringProperty()
| [
"You retrieve the entity, e.g. with a query, then you call .key().id() on that entity (will be None if the entity has no numeric id; see here for other info you can retrieve from a Key object).\n",
"The question has long been answered.\n(I am adding some full examples hopefully while not stepping on any toes...)\nGetting an entity using a query; just getting the keys is faster and uses less CPU than retrieving the full entity:\nquery = Names.all(keys_only=True)\nnames = query.get() # this is a shorter equivalent to `query.fetch(limit=1)`\nnames.id()\n\nFrom a template:\n{{ names.id }}\n\nGQL alternative, as suggested in a comment: \nfrom google.appengine.ext import db\n\nquery = db.GqlQuery(\"SELECT __key__ FROM Names\")\nnames = query.get()\nnames.id()\n\n"
] | [
13,
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002786244_google_app_engine_python.txt |
Q:
PyGTK, Glade, Changing the window view and threads
Forgive me if this seems like a stupid question, just so far no where on the internet can I find someone offering a solution to this and I just wanted to get some feedback from someone with more experience than myself (I've only been using python, pyGTK and Glade for 2 days now).
I have a UI window displaying and it updates with messages from a thread that is handling a bluetooth connection.
This is fine and I have the application closing and running quite reliably, the problem is, after a bluetooth connection is made I wish to maintain the bluetooth thread (i.e. keep the connection going) but completely change the UI of the main window.
Now the impression I am getting from pyGTK applications made from glade, is that the easiest thing to do is just open a new window. Is this really the best option? Can I cut the tree of widgets off at the root, maintaining the window widget but add on a new set of widgets from a separate glade file?
If opening a new window is the best option, am I right in assuming that the bluetooth thread can be kept alive during this transition, providing I update any callbacks?
Any help or pointers would be great.
Cheers,
Matt
A:
If i well understand the connection is strictly coupled with the window. This seems like a good example of aggregation and composition. Simple decouple the window from the connection. Without code or more information is impossible to be more accurate. After this you can use both the solution you proposed: create a new window with a reference of the connection thread or "detach" the whole widgets tree and attach a brand new one, simple use gtk.Container.remove and gtk.Container.add (gtk.Window derive from gtk.Container).
If this is not enough modify your questions and add some info and code.
A:
I think you already know, but GTK (PyGtk) is thread aware and not thread safe, so, modifying the UI from another thread that is not the one that holds gtk's main loop will probably make your program to crash.
You can make use of the .glade files several times, you can use just one widget (and its children) if you want and ignore everything else, that's why gtk.glade.XML accepts a root parameter. This root is where your widget tree will start.
gladeobject = gtk.glade.XML(path_to_glade_file, root='widgetname')
You can safely hide the windows and keep it updated, and avoid the "new window" solution.
| PyGTK, Glade, Changing the window view and threads | Forgive me if this seems like a stupid question, just so far no where on the internet can I find someone offering a solution to this and I just wanted to get some feedback from someone with more experience than myself (I've only been using python, pyGTK and Glade for 2 days now).
I have a UI window displaying and it updates with messages from a thread that is handling a bluetooth connection.
This is fine and I have the application closing and running quite reliably, the problem is, after a bluetooth connection is made I wish to maintain the bluetooth thread (i.e. keep the connection going) but completely change the UI of the main window.
Now the impression I am getting from pyGTK applications made from glade, is that the easiest thing to do is just open a new window. Is this really the best option? Can I cut the tree of widgets off at the root, maintaining the window widget but add on a new set of widgets from a separate glade file?
If opening a new window is the best option, am I right in assuming that the bluetooth thread can be kept alive during this transition, providing I update any callbacks?
Any help or pointers would be great.
Cheers,
Matt
| [
"If i well understand the connection is strictly coupled with the window. This seems like a good example of aggregation and composition. Simple decouple the window from the connection. Without code or more information is impossible to be more accurate. After this you can use both the solution you proposed: create a new window with a reference of the connection thread or \"detach\" the whole widgets tree and attach a brand new one, simple use gtk.Container.remove and gtk.Container.add (gtk.Window derive from gtk.Container).\nIf this is not enough modify your questions and add some info and code.\n",
"I think you already know, but GTK (PyGtk) is thread aware and not thread safe, so, modifying the UI from another thread that is not the one that holds gtk's main loop will probably make your program to crash.\nYou can make use of the .glade files several times, you can use just one widget (and its children) if you want and ignore everything else, that's why gtk.glade.XML accepts a root parameter. This root is where your widget tree will start.\ngladeobject = gtk.glade.XML(path_to_glade_file, root='widgetname')\n\nYou can safely hide the windows and keep it updated, and avoid the \"new window\" solution.\n"
] | [
2,
0
] | [] | [] | [
"glade",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0002554121_glade_multithreading_pygtk_python.txt |
Q:
Have to find if some window name has some string on it with python
First of all, I get the name of the current window
win32gui.GetWindowText(win32gui.GetForegroundWindow())
k, no problem with that...
But now, how can I make an if with the result for having an specific string on it...
For example, the result gave me
C:/Python26/
How can I make an True of False for the result containing the word, 'python' ?
I'm trying with re.search, but I'm not being able to make it do it
A:
python is not the same as Python. You probably need to pass re.IGNORECASE to enable case-insensitive matching. Example:
title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
if re.search(title, "python", re.IGNORECASE):
print "Found it!"
However, if you don't need the power of regexes, it is simpler and faster to do a simple string search:
if title.lower().find("python") >= 0:
| Have to find if some window name has some string on it with python | First of all, I get the name of the current window
win32gui.GetWindowText(win32gui.GetForegroundWindow())
k, no problem with that...
But now, how can I make an if with the result for having an specific string on it...
For example, the result gave me
C:/Python26/
How can I make an True of False for the result containing the word, 'python' ?
I'm trying with re.search, but I'm not being able to make it do it
| [
"python is not the same as Python. You probably need to pass re.IGNORECASE to enable case-insensitive matching. Example:\ntitle = win32gui.GetWindowText(win32gui.GetForegroundWindow())\nif re.search(title, \"python\", re.IGNORECASE):\n print \"Found it!\"\n\nHowever, if you don't need the power of regexes, it is simpler and faster to do a simple string search:\nif title.lower().find(\"python\") >= 0:\n\n"
] | [
0
] | [] | [] | [
"python",
"winapi",
"window"
] | stackoverflow_0002786513_python_winapi_window.txt |
Q:
PyGTK: How do I make a custom widget look like a gtk.Notebook tab?
I'm writing a program and I need some extra functionality from the gtk.Notebook widget, so I have taken to creating my own.
My only problem is styling my tabs so that they look like the tabs in gtk.Notebook and will change according to the user's theme.
I really don't know where to start so any advice would be much appreciated, thanks :)
A:
I solved the problem eventually by getting the colours from gtk.Notebook's style.
A:
Just for the record, if you are going to create something similar to a gtk.Notebook, I'll recomment you to subclass gtk.Notebook to save a lot of work.
| PyGTK: How do I make a custom widget look like a gtk.Notebook tab? | I'm writing a program and I need some extra functionality from the gtk.Notebook widget, so I have taken to creating my own.
My only problem is styling my tabs so that they look like the tabs in gtk.Notebook and will change according to the user's theme.
I really don't know where to start so any advice would be much appreciated, thanks :)
| [
"I solved the problem eventually by getting the colours from gtk.Notebook's style.\n",
"Just for the record, if you are going to create something similar to a gtk.Notebook, I'll recomment you to subclass gtk.Notebook to save a lot of work.\n"
] | [
0,
0
] | [] | [] | [
"coding_style",
"pygtk",
"python",
"tabs"
] | stackoverflow_0002174873_coding_style_pygtk_python_tabs.txt |
Q:
Python: Huge file reading by using linecache Vs normal file access open()
I am in a situation where multiple threads reading the same huge file with mutliple file pointers to same file. The file will have atleast 1 million lines. Eachline's length varies from 500 characters to 1500 characters. There won't "write" operations on the file. Each thread will start reading the same file from different lines. Which is the efficient way..? Using the Python's linecache or normal readline() or is there anyother effient way?
A:
Have a look at the mmap module: http://docs.python.org/library/mmap.html
It will allow you to use the file as an array, while the OS handles the actual reading and buffering.
| Python: Huge file reading by using linecache Vs normal file access open() | I am in a situation where multiple threads reading the same huge file with mutliple file pointers to same file. The file will have atleast 1 million lines. Eachline's length varies from 500 characters to 1500 characters. There won't "write" operations on the file. Each thread will start reading the same file from different lines. Which is the efficient way..? Using the Python's linecache or normal readline() or is there anyother effient way?
| [
"Have a look at the mmap module: http://docs.python.org/library/mmap.html\nIt will allow you to use the file as an array, while the OS handles the actual reading and buffering.\n"
] | [
2
] | [] | [] | [
"file",
"multithreading",
"python"
] | stackoverflow_0002787276_file_multithreading_python.txt |
Q:
how to show all method in
i want to see the all method in
how to get it
thanks
A:
Use the source, luke zjm1126 (or the docs).
A:
As Tamás has answered, you can use the dir function, but I think all the methods are well explained in the docs:
Instance Methods
A User instance provides the following
methods:
nickname()
Returns the "nickname" of the user, a displayable name. The nickname
will be either the "name" portion of
the user's email address if the
address is in the same domain as the
application, or the user's full email
address otherwise.
email()
Returns the email address of the user. Applications should use nickname
for displayable names.
user_id()
Returns the unique permanent ID of the user, a str. This ID is always the
same for the user regardless of
whether the user changes her email
address.
A:
from google.appengine.api.users import User
print dir(User)
| how to show all method in | i want to see the all method in
how to get it
thanks
| [
"Use the source, luke zjm1126 (or the docs).\n",
"As Tamás has answered, you can use the dir function, but I think all the methods are well explained in the docs:\n\nInstance Methods\nA User instance provides the following\n methods:\nnickname()\nReturns the \"nickname\" of the user, a displayable name. The nickname\n will be either the \"name\" portion of\n the user's email address if the\n address is in the same domain as the\n application, or the user's full email\n address otherwise. \nemail()\nReturns the email address of the user. Applications should use nickname\n for displayable names. \nuser_id()\nReturns the unique permanent ID of the user, a str. This ID is always the\n same for the user regardless of\n whether the user changes her email\n address.\n\n",
"from google.appengine.api.users import User\nprint dir(User)\n\n"
] | [
3,
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002786992_google_app_engine_python.txt |
Q:
gae error:AttributeError: 'NoneType' object has no attribute 'user_is_member'
class Thread(db.Model):
members = db.StringListProperty()
def user_is_member(self, user):
return str(user) in self.members
and
thread = Thread.get(db.Key.from_path('Thread', int(id)))
is_member = thread.user_is_member(user)
but the error is :
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 62, in check_login
handler_method(self, *args)
File "D:\zjm_code\forum_blog_gae\main.py", line 222, in get
is_member = thread.user_is_member(user)
AttributeError: 'NoneType' object has no attribute 'user_is_member'
why ?
thanks
A:
You're attempting to fetch an entity by key, but no entity with that key exists, so .get() is returning None. You need to check that a valid entity was returned before trying to act on it, like this:
thread = Thread.get(db.Key.from_path('Thread', int(id)))
if thread:
is_member = thread.user_is_member(user)
else:
is_member = False
or, equivalently:
thread = Thread.get(db.Key.from_path('Thread', int(id)))
is_member = thread.user_is_member(user) if thread else False
| gae error:AttributeError: 'NoneType' object has no attribute 'user_is_member' | class Thread(db.Model):
members = db.StringListProperty()
def user_is_member(self, user):
return str(user) in self.members
and
thread = Thread.get(db.Key.from_path('Thread', int(id)))
is_member = thread.user_is_member(user)
but the error is :
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 62, in check_login
handler_method(self, *args)
File "D:\zjm_code\forum_blog_gae\main.py", line 222, in get
is_member = thread.user_is_member(user)
AttributeError: 'NoneType' object has no attribute 'user_is_member'
why ?
thanks
| [
"You're attempting to fetch an entity by key, but no entity with that key exists, so .get() is returning None. You need to check that a valid entity was returned before trying to act on it, like this:\nthread = Thread.get(db.Key.from_path('Thread', int(id)))\nif thread:\n is_member = thread.user_is_member(user)\nelse:\n is_member = False\n\nor, equivalently:\nthread = Thread.get(db.Key.from_path('Thread', int(id)))\nis_member = thread.user_is_member(user) if thread else False\n\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002787319_google_app_engine_python.txt |
Q:
How to create and restore a backup from SqlAlchemy?
I'm writing a Pylons app, and am trying to create a simple backup system where every table is serialized and tarred up into a single file for an administrator to download, and use to restore the app should something bad happen.
I can serialize my table data just fine using the SqlAlchemy serializer, and I can deserialize it fine as well, but I can't figure out how to commit those changes back to the database.
In order to serialize my data I am doing this:
from myproject.model.meta import Session
from sqlalchemy.ext.serializer import loads, dumps
q = Session.query(MyTable)
serialized_data = dumps(q.all())
In order to test things out, I go ahead and truncation MyTable, and then attempt to restore using serialized_data:
from myproject.model import meta
restore_q = loads(serialized_data, meta.metadata, Session)
This doesn't seem to do anything... I've tried calling a Session.commit after the fact, individually walking through all the objects in restore_q and adding them, but nothing seems to work.
What am I missing? Or is there a better way to do what I'm aiming for? I don't want to shell out and directly touch the database, since SqlAlchemy supports different database engines.
A:
You have to use Session.merge() method instead of Session.add() to put deserialized object back into the session.
| How to create and restore a backup from SqlAlchemy? | I'm writing a Pylons app, and am trying to create a simple backup system where every table is serialized and tarred up into a single file for an administrator to download, and use to restore the app should something bad happen.
I can serialize my table data just fine using the SqlAlchemy serializer, and I can deserialize it fine as well, but I can't figure out how to commit those changes back to the database.
In order to serialize my data I am doing this:
from myproject.model.meta import Session
from sqlalchemy.ext.serializer import loads, dumps
q = Session.query(MyTable)
serialized_data = dumps(q.all())
In order to test things out, I go ahead and truncation MyTable, and then attempt to restore using serialized_data:
from myproject.model import meta
restore_q = loads(serialized_data, meta.metadata, Session)
This doesn't seem to do anything... I've tried calling a Session.commit after the fact, individually walking through all the objects in restore_q and adding them, but nothing seems to work.
What am I missing? Or is there a better way to do what I'm aiming for? I don't want to shell out and directly touch the database, since SqlAlchemy supports different database engines.
| [
"You have to use Session.merge() method instead of Session.add() to put deserialized object back into the session.\n"
] | [
14
] | [] | [] | [
"pylons",
"python",
"serialization",
"sqlalchemy"
] | stackoverflow_0002786664_pylons_python_serialization_sqlalchemy.txt |
Q:
Why connection in Python's DB-API does not have "begin" operation?
Working with cursors in mysql-python I used to call "BEGIN;", "COMMIT;", and "ROLLBACK;" explicitly as follows:
try:
cursor.execute("BEGIN;")
# some statements
cursor.execute("COMMIT;")
except:
cursor.execute("ROLLBACK;")
then, I found out that the underlying connection object has the corresponding methods:
try:
cursor.connection.begin()
# some statements
cursor.connection.commit()
except:
cursor.connection.rollback()
Inspecting the DB-API PEP I found out that it does not mention the begin() method for the connection object, even for the extensions.
Mysql-python, by the way, throws the DeprecationWarning, when you use the method. sqlite3.connection, for example, does not have the method at all.
And the question is why there is no such method in the PEP? Is the statement somehow optional, is it enough to invoke commit() instead?
A:
look a this previously asked question. Generally the "protocol" to use with transactions is:
cursor = conn.cursor()
try:
cursor.execute(...)
except DatabaseError:
conn.rollback()
raise
else:
conn.commit()
finally:
cursor.close()
Starting from python 2.6 sqlite Connection objects can be used as context managers that automatically commit or rollback transactions.
A:
Decided to answer myself:
A thread about DB API 2.0 transactions in python-list and the following excerpt from the noticeable book SQL The Complete Reference make me think that DB API implements SQL1 standard behaviour:
The first version of the SQL standard
(SQL1) defined an implicit transaction
mode, based on the transaction
support in the early releases of DB2.
In implicit mode, only the COMMIT and
ROLLBACK statements are supported. A
SQL transaction automatically begins
with the first SQL statement executed
by a user or a program and ends when a
COMMIT or ROLLBACK is executed. The
end of one transaction implicitly
starts a new one.
Explicit transaction mode (the SQL2 and SQL:1999) seems to be handy when the RDBSM supports autocommit mode and the current connection is in that mode, but DB API just does not reflect it.
| Why connection in Python's DB-API does not have "begin" operation? | Working with cursors in mysql-python I used to call "BEGIN;", "COMMIT;", and "ROLLBACK;" explicitly as follows:
try:
cursor.execute("BEGIN;")
# some statements
cursor.execute("COMMIT;")
except:
cursor.execute("ROLLBACK;")
then, I found out that the underlying connection object has the corresponding methods:
try:
cursor.connection.begin()
# some statements
cursor.connection.commit()
except:
cursor.connection.rollback()
Inspecting the DB-API PEP I found out that it does not mention the begin() method for the connection object, even for the extensions.
Mysql-python, by the way, throws the DeprecationWarning, when you use the method. sqlite3.connection, for example, does not have the method at all.
And the question is why there is no such method in the PEP? Is the statement somehow optional, is it enough to invoke commit() instead?
| [
"look a this previously asked question. Generally the \"protocol\" to use with transactions is:\ncursor = conn.cursor()\ntry:\n cursor.execute(...)\nexcept DatabaseError:\n conn.rollback()\n raise\nelse:\n conn.commit()\nfinally:\n cursor.close()\n\nStarting from python 2.6 sqlite Connection objects can be used as context managers that automatically commit or rollback transactions.\n",
"Decided to answer myself:\nA thread about DB API 2.0 transactions in python-list and the following excerpt from the noticeable book SQL The Complete Reference make me think that DB API implements SQL1 standard behaviour:\n\nThe first version of the SQL standard\n (SQL1) defined an implicit transaction\n mode, based on the transaction\n support in the early releases of DB2.\n In implicit mode, only the COMMIT and\n ROLLBACK statements are supported. A\n SQL transaction automatically begins\n with the first SQL statement executed\n by a user or a program and ends when a\n COMMIT or ROLLBACK is executed. The\n end of one transaction implicitly\n starts a new one.\n\nExplicit transaction mode (the SQL2 and SQL:1999) seems to be handy when the RDBSM supports autocommit mode and the current connection is in that mode, but DB API just does not reflect it.\n"
] | [
8,
4
] | [] | [] | [
"python",
"python_db_api",
"sql"
] | stackoverflow_0002546926_python_python_db_api_sql.txt |
Q:
Python: Open() using a variable
I've run into a problem when opening a file with a randomly generated name in Python 2.6.
import random
random = random.randint(1,10)
localfile = file("%s","wb") % random
Then I get an error message about the last line:
TypeError: unsupported operand type(s) for %: 'file' and 'int'
I just can't figure this out by myself, nor with Google, but there has to be a cure for this, I believe.
A:
This will probably work:
import random
num = random.randint(1, 10)
localfile = open("%d" % num, "wb")
Note that I've changed a couple of things here:
You shouldn't assign the generated random number to a variable named random as you are overwriting the existing reference to the module random. In other words, you will not be able to access random.randint any more if you overwrite random with the randomly generated number.
The formatting operator (%) should be applied to the string you are formatting, not the call to the file method.
I guess file is deprecated in Python 3. It's time to get used to using open instead of file.
Since you are formatting an integer into a string, you should write "%d" instead of "%s" (although the latter would work as well).
An alternative way of writing "%d" % num is str(num), which might be a bit more efficient.
A:
Try:
localfile = file("%s" % random,"wb")
| Python: Open() using a variable | I've run into a problem when opening a file with a randomly generated name in Python 2.6.
import random
random = random.randint(1,10)
localfile = file("%s","wb") % random
Then I get an error message about the last line:
TypeError: unsupported operand type(s) for %: 'file' and 'int'
I just can't figure this out by myself, nor with Google, but there has to be a cure for this, I believe.
| [
"This will probably work:\nimport random\n\nnum = random.randint(1, 10)\nlocalfile = open(\"%d\" % num, \"wb\")\n\nNote that I've changed a couple of things here:\n\nYou shouldn't assign the generated random number to a variable named random as you are overwriting the existing reference to the module random. In other words, you will not be able to access random.randint any more if you overwrite random with the randomly generated number.\nThe formatting operator (%) should be applied to the string you are formatting, not the call to the file method.\nI guess file is deprecated in Python 3. It's time to get used to using open instead of file.\nSince you are formatting an integer into a string, you should write \"%d\" instead of \"%s\" (although the latter would work as well).\n\nAn alternative way of writing \"%d\" % num is str(num), which might be a bit more efficient.\n",
"Try:\nlocalfile = file(\"%s\" % random,\"wb\")\n\n"
] | [
9,
3
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0002788386_python_string_formatting.txt |
Q:
python dictionary conversion from string?
if I've string like
"{ partner_name = test_partner}" OR " { partner_name : test_partner }
its an example string will be very complex with several special characters included like =, [ , ] , { , }
what will be the best way to convert it into a python object - so I can process it
I tried with eval but it requires " ' " for string, but how can we add this special character \' before starting and ending of every word, I tried regular express re.findal('\w+') but it fails when my string contains ' _ ' or like characters as it will separate the string by ' _ '
Object of this question is my application needs, user friendly language as input - and I thought Json Dict will be good - but user is lazzy to put " ' " before and after of each string...
then I thought for yaml but its also complex, if anybody can suggest better user friendly input which I use as python object - then please help me out.
A:
If YAML is too complex for your users, you should perhaps think about giving them a structured input form and formatting the data correctly from there. YAML is pretty much as easy to write as possible for specifying structures, certainly easier than the curly braces syntax.
A:
Fixing the input would be the best solution.
But you could jump through a series of hoops in an attempt to make the input parsable by json. This is fragile since your input isn't json exactly and diverging input could break this easily (although it's still imo to be preferred over bland use of eval).
>>> import json
>>> s = '{ partner_name = test_partner}'
>>> t = s.replace(' ', '') # strip whitespace
>>> t = t.replace('=', '":"')
>>> t = t.replace('{','{"')
>>> t = t.replace('}','"}')
>>> json.loads(t)
{u'partner_name': u'test_partner'}
A:
If it's some outside data, do not use eval() on it! If you want to parse it properly, have a look at some parsing libraries. The ones using parsing combinators are quite nice - for example https://github.com/pyparsing/pyparsing Or maybe a peg parser: http://fdik.org/pyPEG/
A:
>>> import ast
>>> ast.literal_eval("{ 'partner_name' : 'test_partner' }")
{'partner_name': 'test_partner'}
copied from
EDIT
You can use regular expressions
>>> import re
>>> m = re.match(r"(?P<partner_name>\w+) = (?P<test_partner>\w+)", "foo = bar")
>>> m.groupdict()
{'partner_name': 'foo', 'test_partner': 'bar'}
>>>
A:
you could replace or delete any unwanted character
>>> s
'{ partner_name = test_partner }'
>>> s = ''.join([c for c in s.replace('=', ':') if not c in '\ {}'])
>>> s
'partner_name:test_partner'
and then split the string in two to create a dict
>>> dict([s.split(':')])
{'partner_name': 'test_partner'}
or update
>>> your_dict.update([s.split(':')])
| python dictionary conversion from string? | if I've string like
"{ partner_name = test_partner}" OR " { partner_name : test_partner }
its an example string will be very complex with several special characters included like =, [ , ] , { , }
what will be the best way to convert it into a python object - so I can process it
I tried with eval but it requires " ' " for string, but how can we add this special character \' before starting and ending of every word, I tried regular express re.findal('\w+') but it fails when my string contains ' _ ' or like characters as it will separate the string by ' _ '
Object of this question is my application needs, user friendly language as input - and I thought Json Dict will be good - but user is lazzy to put " ' " before and after of each string...
then I thought for yaml but its also complex, if anybody can suggest better user friendly input which I use as python object - then please help me out.
| [
"If YAML is too complex for your users, you should perhaps think about giving them a structured input form and formatting the data correctly from there. YAML is pretty much as easy to write as possible for specifying structures, certainly easier than the curly braces syntax.\n",
"Fixing the input would be the best solution.\nBut you could jump through a series of hoops in an attempt to make the input parsable by json. This is fragile since your input isn't json exactly and diverging input could break this easily (although it's still imo to be preferred over bland use of eval).\n>>> import json\n>>> s = '{ partner_name = test_partner}'\n>>> t = s.replace(' ', '') # strip whitespace\n>>> t = t.replace('=', '\":\"')\n>>> t = t.replace('{','{\"')\n>>> t = t.replace('}','\"}')\n>>> json.loads(t)\n{u'partner_name': u'test_partner'}\n\n",
"If it's some outside data, do not use eval() on it! If you want to parse it properly, have a look at some parsing libraries. The ones using parsing combinators are quite nice - for example https://github.com/pyparsing/pyparsing Or maybe a peg parser: http://fdik.org/pyPEG/\n",
">>> import ast\n\n>>> ast.literal_eval(\"{ 'partner_name' : 'test_partner' }\")\n{'partner_name': 'test_partner'}\n\ncopied from \nEDIT\nYou can use regular expressions \n>>> import re\n>>> m = re.match(r\"(?P<partner_name>\\w+) = (?P<test_partner>\\w+)\", \"foo = bar\")\n>>> m.groupdict()\n{'partner_name': 'foo', 'test_partner': 'bar'}\n>>> \n\n",
"you could replace or delete any unwanted character \n>>> s\n'{ partner_name = test_partner }'\n>>> s = ''.join([c for c in s.replace('=', ':') if not c in '\\ {}'])\n>>> s\n'partner_name:test_partner'\n\nand then split the string in two to create a dict\n>>> dict([s.split(':')])\n{'partner_name': 'test_partner'}\n\nor update \n>>> your_dict.update([s.split(':')])\n\n"
] | [
3,
1,
1,
0,
0
] | [] | [] | [
"dictionary",
"eval",
"python",
"serialization",
"yaml"
] | stackoverflow_0002787303_dictionary_eval_python_serialization_yaml.txt |
Q:
How do I convert a unicode to a string at the Python level?
The following unicode and string can exist on their own if defined explicitly:
>>> value_str='Andr\xc3\xa9'
>>> value_uni=u'Andr\xc3\xa9'
If I only have u'Andr\xc3\xa9' assigned to a variable like above, how do I convert it to 'Andr\xc3\xa9' in Python 2.5 or 2.6?
EDIT:
I did the following:
>>> value_uni.encode('latin-1')
'Andr\xc3\xa9'
which fixes my issue. Can someone explain to me what exactly is happening?
A:
You seem to have gotten your encodings muddled up. It seems likely that what you really want is u'Andr\xe9' which is equivalent to 'André'.
But what you have seems to be a UTF-8 encoding that has been incorrectly decoded. You can fix it by converting the unicode string to an ordinary string. I'm not sure what the best way is, but this seems to work:
>>> ''.join(chr(ord(c)) for c in u'Andr\xc3\xa9')
'Andr\xc3\xa9'
Then decode it correctly:
>>> ''.join(chr(ord(c)) for c in u'Andr\xc3\xa9').decode('utf8')
u'Andr\xe9'
Now it is in the correct format.
However instead of doing this, if possible you should try to work out why the data has been incorrectly encoded in the first place, and fix that problem there.
A:
If you have u'Andr\xc3\xa9', that is a Unicode string that was decoded from a byte string with the wrong encoding. The correct encoding is UTF-8. To convert it back to a byte string so you can decode it correctly, you can use the trick you discovered. The first 256 code points of Unicode are a 1:1 mapping with ISO-8859-1 (alias latin1) encoding. So:
>>> u'Andr\xc3\xa9'.encode('latin1')
'Andr\xc3\xa9'
Now it is a byte string that can be decoded correctly with utf8:
>>> 'Andr\xc3\xa9'.decode('utf8')
u'Andr\xe9'
>>> print 'Andr\xc3\xa9'.decode('utf8')
André
In one step:
>>> print u'Andr\xc3\xa9'.encode('latin1').decode('utf8')
André
A:
You asked (in a comment) """That is what's puzzling me. How did it go from it original accented to what it is now? When you say double encoding with utf8 and latin1, is that a total of 3 encodings(2 utf8 + 1 latin1)? What's the order of the encode from the original state to the current one?"""
In the answer by Mark Byers, he says """what you have seems to be a UTF-8 encoding that has been incorrectly decoded""". You have accepted his answer. But you are still puzzled? OK, here's the blow-by-blow description:
Note: All strings will be displayed using (implicitly) repr(). unicodedata.name() will be used to verify the contents. That way, variations in console encoding cannot confuse interpretation of the strings.
Initial state: you have a unicode object that you have named u1. It contains e-acute:
>>> u1 = u'\xe9'
>>> import unicodedata as ucd
>>> ucd.name(u1)
'LATIN SMALL LETTER E WITH ACUTE'
You encode u1 as UTF-8 and name the result s:
>>> s = u1.encode('utf8')
>>> s
'\xc3\xa9'
You decode s using latin1 -- INCORRECTLY; s was encoded using utf8, NOT latin1. The result is meaningless rubbish.
>>> u2 = s.decode('latin1')
>>> u2
u'\xc3\xa9'
>>> ucd.name(u2[0]); ucd.name(u2[1])
'LATIN CAPITAL LETTER A WITH TILDE'
'COPYRIGHT SIGN'
>>>
Please understand: unicode_object.encode('x').decode('y) when x != y is normally [see note below] a nonsense; it will raise an exception if you are lucky; if you are unlucky it will silently create gibberish. Also please understand that silently creating gibberish is not a bug -- there is no general way that Python (or any other language) can detect that a nonsense has been committed. This applies particularly when latin1 is involved, because all 256 codepoints map 1 to 1 with the first 256 Unicode codepoints, so it is impossible to get a UnicodeDecodeError from str_object.decode('latin1').
Of course, abnormally (one hopes that it's abnormal) you may need to reverse out such a nonsense by doing gibberish_unicode_object.encode('y').decode('x') as suggested in various answers to your question.
A:
value_uni.encode('utf8') or whatever encoding you need.
See http://docs.python.org/library/stdtypes.html#str.encode
A:
The OP is not converting to ascii nor utf-8. That's why the suggested encode methods won't work. Try this:
v = u'Andr\xc3\xa9'
s = ''.join(map(lambda x: chr(ord(x)),v))
The chr(ord(x)) business gets the numeric value of the unicode character (which better fit in one byte for your application), and the ''.join call is an idiom that converts a list of ints back to an ordinary string. No doubt there is a more elegant way.
A:
Simplified explanation. The str type is able to hold only characters from 0-255 range. If you want to store unicode (which can contain characters from much wider range) in str you first have to encode unicode to format suitable for str, for example UTF-8.
To do this call method encode on your str object and as an argument give desired encoding, for example this_is_str = value_uni.encode('utf-8').
You can read longer and more in-depth (and language agnostic) article on Unicode handling here: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).
Another excellent article (this time Python-specific): Unicode HOWTO
| How do I convert a unicode to a string at the Python level? | The following unicode and string can exist on their own if defined explicitly:
>>> value_str='Andr\xc3\xa9'
>>> value_uni=u'Andr\xc3\xa9'
If I only have u'Andr\xc3\xa9' assigned to a variable like above, how do I convert it to 'Andr\xc3\xa9' in Python 2.5 or 2.6?
EDIT:
I did the following:
>>> value_uni.encode('latin-1')
'Andr\xc3\xa9'
which fixes my issue. Can someone explain to me what exactly is happening?
| [
"You seem to have gotten your encodings muddled up. It seems likely that what you really want is u'Andr\\xe9' which is equivalent to 'André'.\nBut what you have seems to be a UTF-8 encoding that has been incorrectly decoded. You can fix it by converting the unicode string to an ordinary string. I'm not sure what the best way is, but this seems to work:\n>>> ''.join(chr(ord(c)) for c in u'Andr\\xc3\\xa9')\n'Andr\\xc3\\xa9'\n\nThen decode it correctly:\n>>> ''.join(chr(ord(c)) for c in u'Andr\\xc3\\xa9').decode('utf8')\nu'Andr\\xe9' \n\nNow it is in the correct format.\nHowever instead of doing this, if possible you should try to work out why the data has been incorrectly encoded in the first place, and fix that problem there.\n",
"If you have u'Andr\\xc3\\xa9', that is a Unicode string that was decoded from a byte string with the wrong encoding. The correct encoding is UTF-8. To convert it back to a byte string so you can decode it correctly, you can use the trick you discovered. The first 256 code points of Unicode are a 1:1 mapping with ISO-8859-1 (alias latin1) encoding. So:\n>>> u'Andr\\xc3\\xa9'.encode('latin1')\n'Andr\\xc3\\xa9'\n\nNow it is a byte string that can be decoded correctly with utf8:\n>>> 'Andr\\xc3\\xa9'.decode('utf8')\nu'Andr\\xe9'\n>>> print 'Andr\\xc3\\xa9'.decode('utf8')\nAndré\n\nIn one step:\n>>> print u'Andr\\xc3\\xa9'.encode('latin1').decode('utf8')\nAndré\n\n",
"You asked (in a comment) \"\"\"That is what's puzzling me. How did it go from it original accented to what it is now? When you say double encoding with utf8 and latin1, is that a total of 3 encodings(2 utf8 + 1 latin1)? What's the order of the encode from the original state to the current one?\"\"\"\nIn the answer by Mark Byers, he says \"\"\"what you have seems to be a UTF-8 encoding that has been incorrectly decoded\"\"\". You have accepted his answer. But you are still puzzled? OK, here's the blow-by-blow description:\nNote: All strings will be displayed using (implicitly) repr(). unicodedata.name() will be used to verify the contents. That way, variations in console encoding cannot confuse interpretation of the strings.\nInitial state: you have a unicode object that you have named u1. It contains e-acute:\n>>> u1 = u'\\xe9'\n>>> import unicodedata as ucd\n>>> ucd.name(u1)\n'LATIN SMALL LETTER E WITH ACUTE'\n\nYou encode u1 as UTF-8 and name the result s:\n>>> s = u1.encode('utf8')\n>>> s\n'\\xc3\\xa9'\n\nYou decode s using latin1 -- INCORRECTLY; s was encoded using utf8, NOT latin1. The result is meaningless rubbish.\n>>> u2 = s.decode('latin1')\n>>> u2\nu'\\xc3\\xa9'\n>>> ucd.name(u2[0]); ucd.name(u2[1])\n'LATIN CAPITAL LETTER A WITH TILDE'\n'COPYRIGHT SIGN'\n>>>\n\nPlease understand: unicode_object.encode('x').decode('y) when x != y is normally [see note below] a nonsense; it will raise an exception if you are lucky; if you are unlucky it will silently create gibberish. Also please understand that silently creating gibberish is not a bug -- there is no general way that Python (or any other language) can detect that a nonsense has been committed. This applies particularly when latin1 is involved, because all 256 codepoints map 1 to 1 with the first 256 Unicode codepoints, so it is impossible to get a UnicodeDecodeError from str_object.decode('latin1').\nOf course, abnormally (one hopes that it's abnormal) you may need to reverse out such a nonsense by doing gibberish_unicode_object.encode('y').decode('x') as suggested in various answers to your question.\n",
"value_uni.encode('utf8') or whatever encoding you need.\nSee http://docs.python.org/library/stdtypes.html#str.encode\n",
"The OP is not converting to ascii nor utf-8. That's why the suggested encode methods won't work. Try this:\nv = u'Andr\\xc3\\xa9'\ns = ''.join(map(lambda x: chr(ord(x)),v))\n\nThe chr(ord(x)) business gets the numeric value of the unicode character (which better fit in one byte for your application), and the ''.join call is an idiom that converts a list of ints back to an ordinary string. No doubt there is a more elegant way.\n",
"Simplified explanation. The str type is able to hold only characters from 0-255 range. If you want to store unicode (which can contain characters from much wider range) in str you first have to encode unicode to format suitable for str, for example UTF-8.\nTo do this call method encode on your str object and as an argument give desired encoding, for example this_is_str = value_uni.encode('utf-8').\nYou can read longer and more in-depth (and language agnostic) article on Unicode handling here: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).\nAnother excellent article (this time Python-specific): Unicode HOWTO\n"
] | [
16,
5,
5,
4,
1,
0
] | [
"It seems like\nstr(value_uni)\n\nshould work... at least, it did when I tried it.\nEDIT: Turns out that this only works because my system's default encoding is, as far as I can tell, ISO-8859-1 (Latin-1). So for a platform-independent version of this, try\nvalue_uni.encode('latin1')\n\n"
] | [
-1
] | [
"python",
"python_2.x",
"unicode"
] | stackoverflow_0002783079_python_python_2.x_unicode.txt |
Q:
Create Django formset without multiple queries
I need to display multiple forms (up to 10) of a model on a page. This is the code I use for to accomplish this.
TheFormSet = formset_factory(SomeForm, extra=10)
...
formset = TheFormSet(prefix='party')
return render_to_response('template.html', {
'formset' : formset,
})
The problem is, that it seems to me that Django queries the database for each of the forms in the formset, even though the data displayed in them is the same.
Is this the way Formsets work or am I doing something wrong? Is there a way around it inside django or would I have to use JavaScript for a workaround?
A:
What happens if you use modelformset_factory instead of formset_factory? Does that help?
A:
If the queries are all identical, it may be worth looking at johnny-cache, and see if that will improve performance.
A:
Are you sure that django queries database? Try to use Django Debug Toolbar to see what queries django actually makes.
| Create Django formset without multiple queries | I need to display multiple forms (up to 10) of a model on a page. This is the code I use for to accomplish this.
TheFormSet = formset_factory(SomeForm, extra=10)
...
formset = TheFormSet(prefix='party')
return render_to_response('template.html', {
'formset' : formset,
})
The problem is, that it seems to me that Django queries the database for each of the forms in the formset, even though the data displayed in them is the same.
Is this the way Formsets work or am I doing something wrong? Is there a way around it inside django or would I have to use JavaScript for a workaround?
| [
"What happens if you use modelformset_factory instead of formset_factory? Does that help?\n",
"If the queries are all identical, it may be worth looking at johnny-cache, and see if that will improve performance.\n",
"Are you sure that django queries database? Try to use Django Debug Toolbar to see what queries django actually makes.\n"
] | [
1,
1,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002787263_django_django_forms_python.txt |
Q:
Python: How to round 123 to 100 instead of 100.0?
>>> round(123,-2)
100.0
>>>
How to round it to 100 instead of 100.0?
A:
int(round(123,-2))
The int function can be used to convert a string or number to a plain integer.
A:
you can just throw it in int:
In [1]: int(round(123, -2))
Out[1]: 100
A:
You could use int(100.0) to convert to 100 in python 2.x and in python3.x, its just works
Python 3.1.2 (r312:79149, ...
>>>
>>> round(123,-2)
100
>>>
A:
You can use regular expression : (\d+)\..* to match the entire thing and extract only the integer part.
| Python: How to round 123 to 100 instead of 100.0? | >>> round(123,-2)
100.0
>>>
How to round it to 100 instead of 100.0?
| [
"int(round(123,-2))\n\nThe int function can be used to convert a string or number to a plain integer.\n",
"you can just throw it in int:\nIn [1]: int(round(123, -2))\nOut[1]: 100\n\n",
"You could use int(100.0) to convert to 100 in python 2.x and in python3.x, its just works\nPython 3.1.2 (r312:79149, ...\n>>>\n>>> round(123,-2)\n100\n>>>\n\n",
"You can use regular expression : (\\d+)\\..* to match the entire thing and extract only the integer part.\n"
] | [
13,
2,
1,
0
] | [] | [] | [
"python",
"rounding"
] | stackoverflow_0002742784_python_rounding.txt |
Q:
Python Glade GTKBuilder Checkbutton
How do I find if a GTKBuilder Checkbutton is checked?
A:
Use checkbutton.get_active(). What's this got to do with GtkBuilder?
| Python Glade GTKBuilder Checkbutton | How do I find if a GTKBuilder Checkbutton is checked?
| [
"Use checkbutton.get_active(). What's this got to do with GtkBuilder?\n"
] | [
1
] | [] | [] | [
"glade",
"gtk",
"gtkbuilder",
"pygtk",
"python"
] | stackoverflow_0002788927_glade_gtk_gtkbuilder_pygtk_python.txt |
Q:
Multithreaded python script silently dies - how to debug
I have a python script that creates and starts 3 threads, and then goes to a KeyboardInterrupt-catching-loop, to send the threads stop signal when ctrl+c is pressed.
The threads' run method has a top level try-except which logs every exception, also the top level code that creates threads is wrapped into try-except to log every exception.
But the script just dies randomly, sometimes after a day, sometimes after an hour, without any exception being logged.
It's driving me crazy, because I have no further ideas how to debug this.
Any ideas guys?
Edit:
As Luper suggested a look into syslog indeed revealed
python[27737]: segfault at 0 ip 0808e1d3 sp b662c5e0 error 4 in python2.5[8048000+fb000]
Still no idea how to go from here.
As for the code, it doesnt do anything fancy, some file parsing and copying between directories, and calling some executables via os.system
A:
A segfault in python is usually caused by a bug in a module written in C. There is nothing the interpreter can do.
A quick search revealed that the common problems that cause a segfault are 1) bad memory (but you should see more segfaults - run memcheck from a live CD if you suspect this), 2) corrupted installation (try reinstall python and packages, re-downloading everything) and 3) bugs (duh).
Try if it is 1) or 2) first, then to see where the process stops, can use strace to record all system calls. That may give you some other clue of what is going on (the output file may grow big):
strace -f python my_script.py > strace.out 2>&1
| Multithreaded python script silently dies - how to debug | I have a python script that creates and starts 3 threads, and then goes to a KeyboardInterrupt-catching-loop, to send the threads stop signal when ctrl+c is pressed.
The threads' run method has a top level try-except which logs every exception, also the top level code that creates threads is wrapped into try-except to log every exception.
But the script just dies randomly, sometimes after a day, sometimes after an hour, without any exception being logged.
It's driving me crazy, because I have no further ideas how to debug this.
Any ideas guys?
Edit:
As Luper suggested a look into syslog indeed revealed
python[27737]: segfault at 0 ip 0808e1d3 sp b662c5e0 error 4 in python2.5[8048000+fb000]
Still no idea how to go from here.
As for the code, it doesnt do anything fancy, some file parsing and copying between directories, and calling some executables via os.system
| [
"A segfault in python is usually caused by a bug in a module written in C. There is nothing the interpreter can do.\nA quick search revealed that the common problems that cause a segfault are 1) bad memory (but you should see more segfaults - run memcheck from a live CD if you suspect this), 2) corrupted installation (try reinstall python and packages, re-downloading everything) and 3) bugs (duh). \nTry if it is 1) or 2) first, then to see where the process stops, can use strace to record all system calls. That may give you some other clue of what is going on (the output file may grow big):\nstrace -f python my_script.py > strace.out 2>&1\n\n"
] | [
2
] | [] | [] | [
"crash",
"multithreading",
"python"
] | stackoverflow_0002788964_crash_multithreading_python.txt |
Q:
ManyToManyField error when having recursive structure. How to solve it?
I have the following table in the model with a recursive structure (a page can have children pages)
class DynamicPage(models.Model):
name = models.CharField("Titre",max_length=200)
parent = models.ForeignKey('self',null=True,blank=True)
I want to create another table with ManyToMany relation with this one.
class UserMessage(models.Model):
name = models.CharField("Nom", max_length=100)
page = models.ManyToManyField(DynamicPage)
A UserMessage can be displayed on several pages and a page can display several messages.
When I add a new UserMessage, I have an error due to the following foreign key constraint.
ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`);
I think that my problem cause is that the constraint is set on the parent field of DynamicPage and not on its id.
Top level DynamicPages don't have a parent page but they can display UserMessage.
So, I would like to have the ManyToMany relationship with the page id and not with the page parent.
I don't see in the Django docs how to say that the ManyToMay is between the UserMessage id and the DynamicPage id rather than the DynamicPage parent.
How to do that? Is it possible?
Is recreating the SQL constraint by hand a possible solution?
Thanks in advance
A:
(Assuming I understand question correctly ;))
Try this:
class DynamicPage(models.Model):
#...
other = models.ManyToManyField("self")
with the optional symmetrical keyword parameter (defaults to True).
http://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield
| ManyToManyField error when having recursive structure. How to solve it? | I have the following table in the model with a recursive structure (a page can have children pages)
class DynamicPage(models.Model):
name = models.CharField("Titre",max_length=200)
parent = models.ForeignKey('self',null=True,blank=True)
I want to create another table with ManyToMany relation with this one.
class UserMessage(models.Model):
name = models.CharField("Nom", max_length=100)
page = models.ManyToManyField(DynamicPage)
A UserMessage can be displayed on several pages and a page can display several messages.
When I add a new UserMessage, I have an error due to the following foreign key constraint.
ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`);
I think that my problem cause is that the constraint is set on the parent field of DynamicPage and not on its id.
Top level DynamicPages don't have a parent page but they can display UserMessage.
So, I would like to have the ManyToMany relationship with the page id and not with the page parent.
I don't see in the Django docs how to say that the ManyToMay is between the UserMessage id and the DynamicPage id rather than the DynamicPage parent.
How to do that? Is it possible?
Is recreating the SQL constraint by hand a possible solution?
Thanks in advance
| [
"(Assuming I understand question correctly ;))\nTry this:\nclass DynamicPage(models.Model):\n #...\n other = models.ManyToManyField(\"self\")\n\nwith the optional symmetrical keyword parameter (defaults to True).\nhttp://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"many_to_many",
"python"
] | stackoverflow_0002789162_django_django_models_many_to_many_python.txt |
Q:
Python metaprogramming help
im looking into mongoengine, and i wanted to make a class an "EmbeddedDocument" dynamically, so i do this
def custom(cls):
cls = type( cls.__name__, (EmbeddedDocument,), cls.__dict__.copy() )
cls.a = FloatField(required=True)
cls.b = FloatField(required=True)
return cls
A = custom( A )
and tried it on some classes, but its not doing some of the base class's init or sumthing
in BaseDocument
def __init__(self, **values):
self._data = {}
# Assign initial values to instance
for attr_name, attr_value in self._fields.items():
if attr_name in values:
setattr(self, attr_name, values.pop(attr_name))
else:
# Use default value if present
value = getattr(self, attr_name, None)
setattr(self, attr_name, value)
but this never gets used, thus never setting ._data, and giving me errors. how do i do this?
update:
im playing with it more, and it seems to have an issue with classes with init methods. maybe i need to make it explicit?
A:
The class you are creating isn't a subclass of cls. You can mix-in EmbeddedDocument, but you still need to be subclassing the original to get the parent's methods (like __init__).
cls = type(cls.__name__, (cls, EmbeddedDocument), {'a': FloatField(required=True), 'b': FloatField(required=True)})
EDIT: you can put the 'a' and 'b' attributes right in the attribute dict passed to type()
| Python metaprogramming help | im looking into mongoengine, and i wanted to make a class an "EmbeddedDocument" dynamically, so i do this
def custom(cls):
cls = type( cls.__name__, (EmbeddedDocument,), cls.__dict__.copy() )
cls.a = FloatField(required=True)
cls.b = FloatField(required=True)
return cls
A = custom( A )
and tried it on some classes, but its not doing some of the base class's init or sumthing
in BaseDocument
def __init__(self, **values):
self._data = {}
# Assign initial values to instance
for attr_name, attr_value in self._fields.items():
if attr_name in values:
setattr(self, attr_name, values.pop(attr_name))
else:
# Use default value if present
value = getattr(self, attr_name, None)
setattr(self, attr_name, value)
but this never gets used, thus never setting ._data, and giving me errors. how do i do this?
update:
im playing with it more, and it seems to have an issue with classes with init methods. maybe i need to make it explicit?
| [
"The class you are creating isn't a subclass of cls. You can mix-in EmbeddedDocument, but you still need to be subclassing the original to get the parent's methods (like __init__).\ncls = type(cls.__name__, (cls, EmbeddedDocument), {'a': FloatField(required=True), 'b': FloatField(required=True)})\n\nEDIT: you can put the 'a' and 'b' attributes right in the attribute dict passed to type()\n"
] | [
2
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0002789270_metaprogramming_python.txt |
Q:
Testing sample code in python modules
I'm in the process of writing a python module that includes some samples. These samples aren't unit-tests, and they are too long and complex to be doctests. I'm interested in best practices for automatically checking that these samples run.
My current project layout is pretty standard, except that there is an extra top level makefile that has build, install, unittest, coverage and profile targets, that delegate responsibility to setup.py and nose as required.
projectname/
Makefile
README
setup.py
samples/
foo-sample
foobar-sample
projectname/
__init__.py
foo.py
bar.py
tests/
test-foo.py
test-bar.py
I've considered adding a sampletest module, or adding nose.tools.istest decorators to the entry-point functions of the samples, but for a small number of samples, these solutions sound a bit ugly.
This question is similar to Automatically Unit Test Example Code, but I assume python best practices will differ from C#
A:
Can't you just do:
if __name__ == "__main__":
run_tests()
in the module code? This way, it will only run if the module is called as a stand-alone progran, not when it's imported into other code.
A:
Most of the time, I just use unittest for testing my examples and functional tests. It isn't unit testing, but a lot of what I do with the unittest module isn't. To quote Knuth, "A computer doesn’t mind if its programs are put to purposes that don’t match their names."
| Testing sample code in python modules | I'm in the process of writing a python module that includes some samples. These samples aren't unit-tests, and they are too long and complex to be doctests. I'm interested in best practices for automatically checking that these samples run.
My current project layout is pretty standard, except that there is an extra top level makefile that has build, install, unittest, coverage and profile targets, that delegate responsibility to setup.py and nose as required.
projectname/
Makefile
README
setup.py
samples/
foo-sample
foobar-sample
projectname/
__init__.py
foo.py
bar.py
tests/
test-foo.py
test-bar.py
I've considered adding a sampletest module, or adding nose.tools.istest decorators to the entry-point functions of the samples, but for a small number of samples, these solutions sound a bit ugly.
This question is similar to Automatically Unit Test Example Code, but I assume python best practices will differ from C#
| [
"Can't you just do:\nif __name__ == \"__main__\":\n run_tests()\n\nin the module code? This way, it will only run if the module is called as a stand-alone progran, not when it's imported into other code.\n",
"Most of the time, I just use unittest for testing my examples and functional tests. It isn't unit testing, but a lot of what I do with the unittest module isn't. To quote Knuth, \"A computer doesn’t mind if its programs are put to purposes that don’t match their names.\"\n"
] | [
3,
3
] | [] | [] | [
"python",
"testing",
"unit_testing"
] | stackoverflow_0002788953_python_testing_unit_testing.txt |
Q:
setup.py install dependency too?
I have a python source distribution, and it depends on some other modules that I've also made. The directory tree looks like this.
I've written a setup.py file for one of those modules (pydirac225, for those of you who are following along at home), and I want to have that setup.py called from the main setup.py?
Another module dependency (pysoundtouch14) has a setup.py file, but the contents of it are basically pasted into the main setup.py script. It seems more modular to allow each of these components to specify how they are set up, and allow the main setup file to invoke their setup scripts individually. Is there a standard way to deal with this issue?
To recap: I have some code that depends on other modules: should the other module's setup code go in the main setup.py, or is there a way to have my code's setup.py invoke their setup.py files?
A:
code that depends on other modeules
if this means that you import the other module, your main setup.py should take care of the dependency and include all neccessary files.
Alternatively take a look at the include and or data_files parameter of setup.py
clarification: if your python scripts which should be bundled by your main setup.py import the extensions, then the extensions are automatically included in the bundled package.
| setup.py install dependency too? | I have a python source distribution, and it depends on some other modules that I've also made. The directory tree looks like this.
I've written a setup.py file for one of those modules (pydirac225, for those of you who are following along at home), and I want to have that setup.py called from the main setup.py?
Another module dependency (pysoundtouch14) has a setup.py file, but the contents of it are basically pasted into the main setup.py script. It seems more modular to allow each of these components to specify how they are set up, and allow the main setup file to invoke their setup scripts individually. Is there a standard way to deal with this issue?
To recap: I have some code that depends on other modules: should the other module's setup code go in the main setup.py, or is there a way to have my code's setup.py invoke their setup.py files?
| [
"\ncode that depends on other modeules\n\nif this means that you import the other module, your main setup.py should take care of the dependency and include all neccessary files.\nAlternatively take a look at the include and or data_files parameter of setup.py\n\nclarification: if your python scripts which should be bundled by your main setup.py import the extensions, then the extensions are automatically included in the bundled package.\n"
] | [
2
] | [] | [] | [
"python",
"setup.py",
"setup_deployment"
] | stackoverflow_0002789886_python_setup.py_setup_deployment.txt |
Q:
Overriding Built-in Classes (Python)
How can I view and override the full definition for built in classes? I have seen the library docs but am looking for something more.
For e.g. is it possible to override the Array Class such that the base index starts from 1 instead of 0, or to override .sort() of list to a sorting algorithm of my own liking?
A:
For creating your own sort() method, it's as simple as this:
class MyList(list):
def sort(self):
return 'custom sorting algorithm'
mylist = MyList([1,2,3])
mylist.sort() # => 'custom sorting algorithm'
I would NOT recommend changing the way lists are indexed as that goes against best practices, so I'm not even providing an example of that! Whenever you want to break convention for things like operator overloading or indexing, I feel that you should rethink why you want to do that and adapt to convention.
A:
You can inherit from builtin types and override or add behaviour. If you should do this is an other question altogether. For an implementation of an n-based list (starting at 1 for example) see this link (Array should be very similar).
For sort you can simply use the key function on sorted.
| Overriding Built-in Classes (Python) | How can I view and override the full definition for built in classes? I have seen the library docs but am looking for something more.
For e.g. is it possible to override the Array Class such that the base index starts from 1 instead of 0, or to override .sort() of list to a sorting algorithm of my own liking?
| [
"For creating your own sort() method, it's as simple as this:\nclass MyList(list):\n def sort(self):\n return 'custom sorting algorithm'\n\nmylist = MyList([1,2,3])\nmylist.sort() # => 'custom sorting algorithm'\n\nI would NOT recommend changing the way lists are indexed as that goes against best practices, so I'm not even providing an example of that! Whenever you want to break convention for things like operator overloading or indexing, I feel that you should rethink why you want to do that and adapt to convention.\n",
"You can inherit from builtin types and override or add behaviour. If you should do this is an other question altogether. For an implementation of an n-based list (starting at 1 for example) see this link (Array should be very similar).\nFor sort you can simply use the key function on sorted.\n"
] | [
6,
4
] | [] | [] | [
"built_in",
"overriding",
"python"
] | stackoverflow_0002790043_built_in_overriding_python.txt |
Q:
How to bind events to Canvas items?
If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, what's the best way of going about this?
Searching online I can find information about how to bind events to tags but that seems to be more indirect then what I want. I don't want to group items with tags, but rather have specific function calls when the user clicks specific items on the canvas.
A:
To interact with objects contained in a Canvas object you need to use tag_bind() which has this format: tag_bind(item, event=None, callback=None, add=None)
The item parameter can be either a tag or an id.
Here is an example to illustrate the concept:
from tkinter import *
def onObjectClick(event):
print('Got object click', event.x, event.y)
print(event.widget.find_closest(event.x, event.y))
root = Tk()
canv = Canvas(root, width=100, height=100)
obj1Id = canv.create_line(0, 30, 100, 30, width=5, tags="obj1Tag")
obj2Id = canv.create_text(50, 70, text='Click', tags='obj2Tag')
canv.tag_bind(obj1Id, '<ButtonPress-1>', onObjectClick)
canv.tag_bind('obj2Tag', '<ButtonPress-1>', onObjectClick)
print('obj1Id: ', obj1Id)
print('obj2Id: ', obj2Id)
canv.pack()
root.mainloop()
| How to bind events to Canvas items? | If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, what's the best way of going about this?
Searching online I can find information about how to bind events to tags but that seems to be more indirect then what I want. I don't want to group items with tags, but rather have specific function calls when the user clicks specific items on the canvas.
| [
"To interact with objects contained in a Canvas object you need to use tag_bind() which has this format: tag_bind(item, event=None, callback=None, add=None)\nThe item parameter can be either a tag or an id.\nHere is an example to illustrate the concept:\nfrom tkinter import * \n\ndef onObjectClick(event): \n print('Got object click', event.x, event.y)\n print(event.widget.find_closest(event.x, event.y))\n\nroot = Tk()\ncanv = Canvas(root, width=100, height=100)\nobj1Id = canv.create_line(0, 30, 100, 30, width=5, tags=\"obj1Tag\")\nobj2Id = canv.create_text(50, 70, text='Click', tags='obj2Tag')\n\ncanv.tag_bind(obj1Id, '<ButtonPress-1>', onObjectClick) \ncanv.tag_bind('obj2Tag', '<ButtonPress-1>', onObjectClick) \nprint('obj1Id: ', obj1Id)\nprint('obj2Id: ', obj2Id)\ncanv.pack()\nroot.mainloop()\n\n"
] | [
73
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas",
"user_interface"
] | stackoverflow_0002786877_python_tkinter_tkinter_canvas_user_interface.txt |
Q:
console window on top with Python?
How do I force my console window to be always on top with Python?
A:
Don't. There's nothing worse than two windows that think they deserve to be the one on top fighting it out. I've seen CPUs dragged to their knees by it.
A:
Unless you are using a console window written by yourself as a "real" window you can alter the state of, you'd have to talk to the window manager (be it Windows's or some of the Linux ones).
But I agree with Paul Tomblin. I think most window managers have that feature built in for users to activate it if they WANT it on top!
| console window on top with Python? | How do I force my console window to be always on top with Python?
| [
"Don't. There's nothing worse than two windows that think they deserve to be the one on top fighting it out. I've seen CPUs dragged to their knees by it.\n",
"Unless you are using a console window written by yourself as a \"real\" window you can alter the state of, you'd have to talk to the window manager (be it Windows's or some of the Linux ones).\nBut I agree with Paul Tomblin. I think most window managers have that feature built in for users to activate it if they WANT it on top!\n"
] | [
3,
2
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0002790108_python_windows.txt |
Q:
SQLAlchemy Relationship Filter?
Can I do
table.relationship.filter( column = value )
to get a subset of rows for relationships? and the same for order_by?
A:
relationship() with lazy='dynamic' option gives you a query (AppenderQuery object which allows you to add/remove items), so you can .filter()/.filter_by() and .order_by() it.
A:
According to the relationship() documentation, you can use order_by keyword argument with relationships, to set the order that will be returned. On the same page, it mentions that you can also use primaryjoin keyword argument to define extra join parameters. I think that can be used for the filter you want.
| SQLAlchemy Relationship Filter? | Can I do
table.relationship.filter( column = value )
to get a subset of rows for relationships? and the same for order_by?
| [
"relationship() with lazy='dynamic' option gives you a query (AppenderQuery object which allows you to add/remove items), so you can .filter()/.filter_by() and .order_by() it.\n",
"According to the relationship() documentation, you can use order_by keyword argument with relationships, to set the order that will be returned. On the same page, it mentions that you can also use primaryjoin keyword argument to define extra join parameters. I think that can be used for the filter you want.\n"
] | [
50,
15
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002767503_python_sqlalchemy.txt |
Q:
Is there some module for Python that works with Firefox?
Is there some module for Python that tells me when some page finish the loading, or something else on Firefox?
A:
There's selenium
Code example test_google.py:
from selenium import selenium
sel = selenium("localhost", 4444, "*firefox", "http://www.google.com/webhp")
sel.start()
sel.open("http://www.google.com/webhp")
sel.type("q", "hello world")
sel.click("btnG")
sel.wait_for_page_to_load(5000)
assert "hello world - Google Search" == sel.get_title()
sel.stop()
A:
You can use the moz-repl plugin. It will instantiate a command prompt on a local port and you can then script it using the cmd module. This will allow you to peek at the browser internals and get back the information you need.
A:
you can alternatively try the gtkmozembed module. lets you run a firefox instance and load pages in there.
selenium might be best if you are just after load times, but if you want to do more interactions with the page, like execute javascript, or take screenshots even, gtkmozembed might be your man.
| Is there some module for Python that works with Firefox? | Is there some module for Python that tells me when some page finish the loading, or something else on Firefox?
| [
"There's selenium\nCode example test_google.py:\nfrom selenium import selenium\n\nsel = selenium(\"localhost\", 4444, \"*firefox\", \"http://www.google.com/webhp\")\nsel.start()\n\nsel.open(\"http://www.google.com/webhp\")\nsel.type(\"q\", \"hello world\")\nsel.click(\"btnG\")\nsel.wait_for_page_to_load(5000)\nassert \"hello world - Google Search\" == sel.get_title()\nsel.stop()\n\n",
"You can use the moz-repl plugin. It will instantiate a command prompt on a local port and you can then script it using the cmd module. This will allow you to peek at the browser internals and get back the information you need. \n",
"you can alternatively try the gtkmozembed module. lets you run a firefox instance and load pages in there.\nselenium might be best if you are just after load times, but if you want to do more interactions with the page, like execute javascript, or take screenshots even, gtkmozembed might be your man.\n"
] | [
4,
1,
0
] | [] | [] | [
"firefox",
"python"
] | stackoverflow_0002789989_firefox_python.txt |
Q:
Print string as HTML
I would like to know if is there any way to convert a plain unicode string to HTML in Genshi, so, for example, it renders newlines as <br/>.
I want this to render some text entered in a textarea.
Thanks in advance!
A:
If Genshi works just as KID (which it should), then all you have to do is
${XML("<p>Hi!</p>")}
We have a small function to transform from a wiki format to HTML
def wikiFormat(text):
patternBold = re.compile("(''')(.+?)(''')")
patternItalic = re.compile("('')(.+?)('')")
patternBoldItalic = re.compile("(''''')(.+?)(''''')")
translatedText = (text or "").replace("\n", "<br/>")
translatedText = patternBoldItalic.sub(r'<b><i>\2</i></b>', textoTraducido or '')
translatedText = patternBold.sub(r'<b>\2</b>', translatedText or '')
translatedText = patternItalic.sub(r'<i>\2</i>', translatedText or '')
return translatedText
You should adapt it to your needs.
${XML(wikiFormat(text))}
A:
Maybe use a <pre> tag.
A:
Convert plain text to HTML, by escaping "<" and "&" characters (and maybe some more, but these two are the absolute minimum) as HTML entities
Substitute every newline with the text "<br />", possibly still combined with a newline.
In that order.
All in all that shouldn't be more than a few lines of Python code. (I don't do Python but any Python programmer should be able to do that, easily.)
edit I found code on the web for the first step. For step 2, see string.replace at the bottom of this page.
A:
In case anyone is interested, this is how I solved it. This is the python code before the data is sent to the genshi template.
from trac.wiki.formatter import format_to_html
from trac.mimeview.api import Context
...
context = Context.from_request(req, 'resource')
data['comment'] = format_to_html(self.env, context, comment, True)
return template, data, None
| Print string as HTML | I would like to know if is there any way to convert a plain unicode string to HTML in Genshi, so, for example, it renders newlines as <br/>.
I want this to render some text entered in a textarea.
Thanks in advance!
| [
"If Genshi works just as KID (which it should), then all you have to do is\n${XML(\"<p>Hi!</p>\")}\n\nWe have a small function to transform from a wiki format to HTML\ndef wikiFormat(text):\n patternBold = re.compile(\"(''')(.+?)(''')\")\n patternItalic = re.compile(\"('')(.+?)('')\")\n patternBoldItalic = re.compile(\"(''''')(.+?)(''''')\")\n translatedText = (text or \"\").replace(\"\\n\", \"<br/>\")\n translatedText = patternBoldItalic.sub(r'<b><i>\\2</i></b>', textoTraducido or '')\n translatedText = patternBold.sub(r'<b>\\2</b>', translatedText or '')\n translatedText = patternItalic.sub(r'<i>\\2</i>', translatedText or '')\n return translatedText\n\nYou should adapt it to your needs.\n${XML(wikiFormat(text))}\n\n",
"Maybe use a <pre> tag.\n",
"\nConvert plain text to HTML, by escaping \"<\" and \"&\" characters (and maybe some more, but these two are the absolute minimum) as HTML entities\nSubstitute every newline with the text \"<br />\", possibly still combined with a newline.\n\nIn that order. \nAll in all that shouldn't be more than a few lines of Python code. (I don't do Python but any Python programmer should be able to do that, easily.)\nedit I found code on the web for the first step. For step 2, see string.replace at the bottom of this page.\n",
"In case anyone is interested, this is how I solved it. This is the python code before the data is sent to the genshi template.\nfrom trac.wiki.formatter import format_to_html\nfrom trac.mimeview.api import Context\n...\n context = Context.from_request(req, 'resource')\n data['comment'] = format_to_html(self.env, context, comment, True)\n return template, data, None\n\n"
] | [
1,
0,
0,
0
] | [] | [] | [
"genshi",
"html",
"newline",
"python"
] | stackoverflow_0002786803_genshi_html_newline_python.txt |
Q:
Problem running a Python program, error: Name 's' is not defined
Here's my code:
#This is a game to guess a random number.
import random
guessTaken = 0
print("Hello! What's your name kid")
myName = input()
number = random.randint(1,20)
print("Well, " + myName + ", I'm thinking of a number between 1 and 20.")
while guessTaken < 6:
print("Take a guess.")
guess = input()
guess = int(guess)
guessTaken = guessTaken + 1
if guess < number:
print("You guessed a little bit too low.")
if guess > number:
print("You guessed a little too high.")
if guess == number:
break
if guess == number:
guessTaken = str(guessTaken)
print("Well done " + myName + "! You guessed the number in " + guessTaken + " guesses!")
if guess != number:
number = str(number)
print("No dice kid. I was thinking of this number: " + number)
This is the error I get:
Name error: Name 's' is not defined.
I think the problem may be that I have Python 3 installed, but the program is being interpreted by Python 2.6. I'm using Linux Mint if that can help you guys help me.
Using Geany as the IDE and pressing F5 to test it. It may be loading 2.6 by default, but I don't really know. :(
Edit:
Error 1 is:
File "GuessingGame.py", line 8, in <Module>
myName = input()
Error 2 is:
File <string>, line 1, in <Module>
A:
When you enter data for input() in Python 2, you're entering a Python expression. Whatever you're typing
Looks like an expression -- not a literal.
Has an S in it (hence the undefined variable.)
Either
put your strings in quotes or
stop using input() and use raw_input()
stop using Python 2.6.
It's not clear what "I have Python 3 installed, but the program is being interpreted by Python 2.6." means. If it's installed, why isn't it being used? What's wrong with your PATH?
A:
If you want to run this in Python 2, you will have to replace the calls to input() with raw_input().
A:
Simple fix. Change your input to raw_input and off you go. For example:
myName = raw_input("Hello! What's your name kid? ")
Check out the Python documentation for more details, but you want to avoid using input as it's attempting to eval() what is returned;
Warning
This function is not safe from user
errors! It expects a valid Python
expression as input; if the input is
not syntactically valid, a SyntaxError
will be raised. Other exceptions may
be raised if there is an error during
evaluation. (On the other hand,
sometimes this is exactly what you
need when writing a quick script for
expert use.)
| Problem running a Python program, error: Name 's' is not defined | Here's my code:
#This is a game to guess a random number.
import random
guessTaken = 0
print("Hello! What's your name kid")
myName = input()
number = random.randint(1,20)
print("Well, " + myName + ", I'm thinking of a number between 1 and 20.")
while guessTaken < 6:
print("Take a guess.")
guess = input()
guess = int(guess)
guessTaken = guessTaken + 1
if guess < number:
print("You guessed a little bit too low.")
if guess > number:
print("You guessed a little too high.")
if guess == number:
break
if guess == number:
guessTaken = str(guessTaken)
print("Well done " + myName + "! You guessed the number in " + guessTaken + " guesses!")
if guess != number:
number = str(number)
print("No dice kid. I was thinking of this number: " + number)
This is the error I get:
Name error: Name 's' is not defined.
I think the problem may be that I have Python 3 installed, but the program is being interpreted by Python 2.6. I'm using Linux Mint if that can help you guys help me.
Using Geany as the IDE and pressing F5 to test it. It may be loading 2.6 by default, but I don't really know. :(
Edit:
Error 1 is:
File "GuessingGame.py", line 8, in <Module>
myName = input()
Error 2 is:
File <string>, line 1, in <Module>
| [
"When you enter data for input() in Python 2, you're entering a Python expression. Whatever you're typing\n\nLooks like an expression -- not a literal.\nHas an S in it (hence the undefined variable.)\n\nEither \n\nput your strings in quotes or \nstop using input() and use raw_input()\nstop using Python 2.6. \n\nIt's not clear what \"I have Python 3 installed, but the program is being interpreted by Python 2.6.\" means. If it's installed, why isn't it being used? What's wrong with your PATH?\n",
"If you want to run this in Python 2, you will have to replace the calls to input() with raw_input(). \n",
"Simple fix. Change your input to raw_input and off you go. For example:\nmyName = raw_input(\"Hello! What's your name kid? \")\n\nCheck out the Python documentation for more details, but you want to avoid using input as it's attempting to eval() what is returned;\n\nWarning\nThis function is not safe from user\n errors! It expects a valid Python\n expression as input; if the input is\n not syntactically valid, a SyntaxError\n will be raised. Other exceptions may\n be raised if there is an error during\n evaluation. (On the other hand,\n sometimes this is exactly what you\n need when writing a quick script for\n expert use.)\n\n"
] | [
5,
2,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002790565_python_python_3.x.txt |
Q:
Python handing of Web Forms
I am having some trouble generating a web form using fields specified in an ascii file.
What I want to do is the following:
1) Read in the ascii file.
This is of the form (can have N elements):
Object1 value1
Object2 value2
Object3 value3
Object4 value4
...
2) Generate a web form from the ascii file contents. Each line in the ascii file should represent a form checkbox option.
...
3) Display the form at a specific url.
4) On "submit", call a cgi script to process the form.
My problem is in step 2. I can easily generate a static form with fixed values and save it as a standard html form but I need something that will read in the ascii file and generate the html file on the fly when visiting that url.
Any advice on what the easiest way of doing this is?
A:
Simplest way to set up HTTP service in Python: get CherryPy ( http://www.cherrypy.org )
For example, this program:
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
Sets up a web server on http://127.0.0.1/8080/ and prints "Hello World!" when opened. Just return your custom HTML instead and you're ready :)
Alternatively, if you want to host the form at a specific server, you can use the python ftplib module to put it there.
A:
Given that you cite step 2 (template processing) as your primary concern, you should look into one of python's templating libraries. The good ones (that I can remember right now) are Mako, Genshi, Jinja and Cheetah. Python's website has a whole list of them: http://wiki.python.org/moin/Templating
I personally find Mako easy to use, but others might be better suited to your particular problem.
You might also want to look at a web application framework, which will have templating plus the cgi stuff described in your 3rd and 4th steps. Again, check out python's website for details and options.
| Python handing of Web Forms | I am having some trouble generating a web form using fields specified in an ascii file.
What I want to do is the following:
1) Read in the ascii file.
This is of the form (can have N elements):
Object1 value1
Object2 value2
Object3 value3
Object4 value4
...
2) Generate a web form from the ascii file contents. Each line in the ascii file should represent a form checkbox option.
...
3) Display the form at a specific url.
4) On "submit", call a cgi script to process the form.
My problem is in step 2. I can easily generate a static form with fixed values and save it as a standard html form but I need something that will read in the ascii file and generate the html file on the fly when visiting that url.
Any advice on what the easiest way of doing this is?
| [
"Simplest way to set up HTTP service in Python: get CherryPy ( http://www.cherrypy.org )\nFor example, this program:\nimport cherrypy\n\nclass HelloWorld(object):\n def index(self):\n return \"Hello World!\"\n index.exposed = True\n\ncherrypy.quickstart(HelloWorld())\n\nSets up a web server on http://127.0.0.1/8080/ and prints \"Hello World!\" when opened. Just return your custom HTML instead and you're ready :)\nAlternatively, if you want to host the form at a specific server, you can use the python ftplib module to put it there.\n",
"Given that you cite step 2 (template processing) as your primary concern, you should look into one of python's templating libraries. The good ones (that I can remember right now) are Mako, Genshi, Jinja and Cheetah. Python's website has a whole list of them: http://wiki.python.org/moin/Templating\n\nI personally find Mako easy to use, but others might be better suited to your particular problem.\n\nYou might also want to look at a web application framework, which will have templating plus the cgi stuff described in your 3rd and 4th steps. Again, check out python's website for details and options.\n"
] | [
2,
1
] | [] | [] | [
"cgi",
"forms",
"html",
"python"
] | stackoverflow_0002790413_cgi_forms_html_python.txt |
Q:
Help with cURL in Python
I have to POST a request to a server. In the API documentation of the website there is this example that uses cURL in PHP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.website.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
;
$data = curl_exec($ch);
curl_close($ch);
But my app is done using Python, so I tried to write something like that but this code doesn't work:
req = urllib2.Request(url, formatted)
response = urllib2.urlopen(req)
html = response.read()
print html+"\n\n"
Can you help me write a working conversion of a PHP cURL program to Python?
Thank you!!
A:
curl is for Python too: http://pycurl.sourceforge.net/
The example could be translated into Python and pycurl like this:
import pycurl
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://api.website.com")
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, "request=%s" % wrapper)
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()
c.close()
data = b.getvalue()
Your Python code using urllib2 looks OK, it should be working. Probably there is an error in something other you did not mention in question; could you be please more specific?
A:
Consider using a packet sniffer to figure out if cURL is sending User-Agent information. If it is, and the service is expecting that information, then use the add_header() method on your Request (from urllib2 documentation, bottom of page):
import urllib2
req = urllib2.Request('http://api.website.com/')
# Your parameter encoding here
req.add_header('User-agent', 'Mozilla/5.0')
r = urllib2.urlopen(req)
# Process the response
A:
Taking your code, this should actually work.
import urllib
import urllib2
url = 'http://api.website.com/'
values = {'some_key':'some_value'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
page = response.read()
print page + '\n\n'
What is the error you are getting?
A:
It's quite embarrassing but... the only problem with my code that uses urllib and urllib2 is... that this code do a GET and not a POST !!!
Here my scan using Wireshark:
1- using urllib and urllib2
Hypertext Transfer Protocol
GET / HTTP/1.1\r\n
[Expert Info (Chat/Sequence): GET / HTTP/1.1\r\n]
[Message: GET / HTTP/1.1\r\n]
[Severity level: Chat]
[Group: Sequence]
Request Method: GET
Request URI: /
Request Version: HTTP/1.1
Accept-Encoding: identity\r\n
Host: api.apptrackr.org\r\n
Connection: close\r\n
User-Agent: Python-urllib/2.6\r\n
\r\n
2- using PyCurl
Hypertext Transfer Protocol
POST / HTTP/1.1\r\n
[Expert Info (Chat/Sequence): POST / HTTP/1.1\r\n]
[Message: POST / HTTP/1.1\r\n]
[Severity level: Chat]
[Group: Sequence]
Request Method: POST
Request URI: /
Request Version: HTTP/1.1
User-Agent: PycURL/7.19.5\r\n
Host: api.website.com\r\n
Accept: */*\r\n
Content-Length: 365\r\n
[Content length: 365]
Content-Type: application/x-www-form-urlencoded\r\n
\r\n
Line-based text data: application/x-www-form-urlencoded
[truncated] request=%7B%22enc_key%22%3A%22o37vOsNetKgprRE0VsBYefYViP4%2ByB3pjxfkfCYtpgiQ%2ByxONgkhhsxtqAwaXwCrrgx%2BPDuDtMRZNI1ez//4Zw%3D%3D%22%2C%22format%22%3A%22RSA_RC4_Sealed%22%2C%22profile%22%3A%22Ldn%22%2C%22request%22%3A%22bQ%2BHm/
so the code works, but it's not right for me because i need a POST, but i will prefer to use NOT PyCurl.
Any idea?
Thank you very much!!
| Help with cURL in Python | I have to POST a request to a server. In the API documentation of the website there is this example that uses cURL in PHP:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.website.com');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
;
$data = curl_exec($ch);
curl_close($ch);
But my app is done using Python, so I tried to write something like that but this code doesn't work:
req = urllib2.Request(url, formatted)
response = urllib2.urlopen(req)
html = response.read()
print html+"\n\n"
Can you help me write a working conversion of a PHP cURL program to Python?
Thank you!!
| [
"curl is for Python too: http://pycurl.sourceforge.net/\nThe example could be translated into Python and pycurl like this:\nimport pycurl\nc = pycurl.Curl()\nc.setopt(pycurl.URL, \"http://api.website.com\")\nc.setopt(pycurl.POST, 1)\nc.setopt(pycurl.POSTFIELDS, \"request=%s\" % wrapper)\nimport StringIO\nb = StringIO.StringIO()\nc.setopt(pycurl.WRITEFUNCTION, b.write)\nc.perform()\nc.close()\ndata = b.getvalue()\n\nYour Python code using urllib2 looks OK, it should be working. Probably there is an error in something other you did not mention in question; could you be please more specific?\n",
"Consider using a packet sniffer to figure out if cURL is sending User-Agent information. If it is, and the service is expecting that information, then use the add_header() method on your Request (from urllib2 documentation, bottom of page):\nimport urllib2\nreq = urllib2.Request('http://api.website.com/')\n# Your parameter encoding here\nreq.add_header('User-agent', 'Mozilla/5.0')\nr = urllib2.urlopen(req)\n# Process the response\n\n",
"Taking your code, this should actually work.\n import urllib \n import urllib2\n\n url = 'http://api.website.com/' \n values = {'some_key':'some_value'} \n data = urllib.urlencode(values) \n req = urllib2.Request(url, data) \n response = urllib2.urlopen(req) \n page = response.read()\n print page + '\\n\\n'\n\nWhat is the error you are getting?\n",
"It's quite embarrassing but... the only problem with my code that uses urllib and urllib2 is... that this code do a GET and not a POST !!!\nHere my scan using Wireshark:\n1- using urllib and urllib2\nHypertext Transfer Protocol\n GET / HTTP/1.1\\r\\n\n [Expert Info (Chat/Sequence): GET / HTTP/1.1\\r\\n]\n [Message: GET / HTTP/1.1\\r\\n]\n [Severity level: Chat]\n [Group: Sequence]\n Request Method: GET\n Request URI: /\n Request Version: HTTP/1.1\n Accept-Encoding: identity\\r\\n\n Host: api.apptrackr.org\\r\\n\n Connection: close\\r\\n\n User-Agent: Python-urllib/2.6\\r\\n\n \\r\\n\n\n2- using PyCurl\nHypertext Transfer Protocol\n POST / HTTP/1.1\\r\\n\n [Expert Info (Chat/Sequence): POST / HTTP/1.1\\r\\n]\n [Message: POST / HTTP/1.1\\r\\n]\n [Severity level: Chat]\n [Group: Sequence]\n Request Method: POST\n Request URI: /\n Request Version: HTTP/1.1\n User-Agent: PycURL/7.19.5\\r\\n\n Host: api.website.com\\r\\n\n Accept: */*\\r\\n\n Content-Length: 365\\r\\n\n [Content length: 365]\n Content-Type: application/x-www-form-urlencoded\\r\\n\n \\r\\n\nLine-based text data: application/x-www-form-urlencoded\n [truncated] request=%7B%22enc_key%22%3A%22o37vOsNetKgprRE0VsBYefYViP4%2ByB3pjxfkfCYtpgiQ%2ByxONgkhhsxtqAwaXwCrrgx%2BPDuDtMRZNI1ez//4Zw%3D%3D%22%2C%22format%22%3A%22RSA_RC4_Sealed%22%2C%22profile%22%3A%22Ldn%22%2C%22request%22%3A%22bQ%2BHm/\n\nso the code works, but it's not right for me because i need a POST, but i will prefer to use NOT PyCurl.\nAny idea?\nThank you very much!!\n"
] | [
2,
2,
1,
1
] | [] | [] | [
"curl",
"libcurl",
"php",
"post",
"python"
] | stackoverflow_0002776794_curl_libcurl_php_post_python.txt |
Q:
Python Split usage
I'm cocking this up and it should be really simple but the value of sortdate is none (note im only doing this because converting a string to a date in Python is a bugger).
DateToPass = str(self.request.get('startdate'))
mybreak.startdate = DateToPass
faf = DateToPass.split('-')
sortdate = str(faf[2] + faf[1] + faf[0])
That should work? but its just being stored as null though the datetopass is being stored fine.
A:
It would be helpful to see what self.request.get('startdate') looked like. Is it ISO (YYYY-MM-DD)? If so I'll show an example using datetime. There's no need for splits because of datetime.datetime.strptime:
>>> import datetime
>>> date_to_pass = '2010-05-07'
>>> sortdate = datetime.datetime.strptime(date_to_pass, '%Y-%m-%d')
>>> sortdate
datetime.datetime(2010, 5, 7, 0, 0)
Datetime objects are sortable, so there's no need to convert to a string. Unless I'm missing the point of your question.
A:
If the real issue is converting a string to a time, as you have indicated, then have you looked into time.strptime?
A:
If your input date is in the format 'YYYY-MM-DD' then the code you have shold work fine. There are a few extraneous str() calls, and yeah, it'd be more proper to use strptime, but nothing that should break.
For example, this works:
Python 2.5.2 (r252:60911, Apr 15 2008, 11:28:25)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> startdate = '2002-04-20'
>>> splitdate = startdate.split('-')
>>> type(splitdate[0])
<type 'str'>
>>> splitdate[2]+splitdate[1]+splitdate[0]
'20042002'
So the two places I'd look are:
What is the format you get from self.request.get('startdate') and store in DateToPass?
You haven't shown us the code where you store sortdate. Is it broken?
| Python Split usage | I'm cocking this up and it should be really simple but the value of sortdate is none (note im only doing this because converting a string to a date in Python is a bugger).
DateToPass = str(self.request.get('startdate'))
mybreak.startdate = DateToPass
faf = DateToPass.split('-')
sortdate = str(faf[2] + faf[1] + faf[0])
That should work? but its just being stored as null though the datetopass is being stored fine.
| [
"It would be helpful to see what self.request.get('startdate') looked like. Is it ISO (YYYY-MM-DD)? If so I'll show an example using datetime. There's no need for splits because of datetime.datetime.strptime:\n>>> import datetime\n>>> date_to_pass = '2010-05-07'\n>>> sortdate = datetime.datetime.strptime(date_to_pass, '%Y-%m-%d')\n>>> sortdate\ndatetime.datetime(2010, 5, 7, 0, 0)\n\nDatetime objects are sortable, so there's no need to convert to a string. Unless I'm missing the point of your question.\n",
"If the real issue is converting a string to a time, as you have indicated, then have you looked into time.strptime? \n",
"If your input date is in the format 'YYYY-MM-DD' then the code you have shold work fine. There are a few extraneous str() calls, and yeah, it'd be more proper to use strptime, but nothing that should break.\nFor example, this works:\nPython 2.5.2 (r252:60911, Apr 15 2008, 11:28:25)\n[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> startdate = '2002-04-20'\n>>> splitdate = startdate.split('-')\n>>> type(splitdate[0])\n<type 'str'>\n>>> splitdate[2]+splitdate[1]+splitdate[0]\n'20042002'\n\nSo the two places I'd look are:\n\nWhat is the format you get from self.request.get('startdate') and store in DateToPass?\nYou haven't shown us the code where you store sortdate. Is it broken?\n\n"
] | [
4,
1,
1
] | [] | [] | [
"datetime",
"google_app_engine",
"python"
] | stackoverflow_0002789764_datetime_google_app_engine_python.txt |
Q:
Can I pass class method as and a default argument to another class method
I want to pass class method as and a default argument to another class method, so that I can reuse the method as a @classmethod:
@classmethod
class foo:
def func1(self,x):
do somthing;
def func2(self, aFunc = self.func1):
# make some a call to afunc
afunc(4)
This is why when the method func2 is called within the class aFunc defaults to self.func1, but I can call this same function from outside of the class and pass it a different function at the input.
I get:
NameError: name 'self' is not defined
Here is my setup:
class transmissionLine:
def electricalLength(self, l=l0, f=f0, gamma=self.propagationConstant, deg=False):
But I want to be able to call electricalLength with a different function for gamma, like:
transmissionLine().electricalLength (l, f, gamma=otherFunc)
A:
Default argument values are computed during function definition, not during function call. So no, you can't. You can do the following, however:
def func2(self, aFunc = None):
if aFunc is None:
aFunc = self.func1
...
A:
The way you are trying wont work, because Foo isnt defined yet.
class Foo:
@classmethod
def func1(cls, x):
print 'something: ', cls, x
def func2(cls, a_func=Foo.func1):
a_func('test')
Foo.func2 = classmethod(func2)
Foo.func2()
A:
You should write it like this:
class Foo(object):
@classmethod
def func1(cls, x):
print x
def func2(self, afunc=None):
if afunc is None:
afunc = self.func1
afunc(4)
Though it would be helpful if you gave a little more info on what you are trying to do. There is probably a more elegant way to do this without classmethods.
| Can I pass class method as and a default argument to another class method | I want to pass class method as and a default argument to another class method, so that I can reuse the method as a @classmethod:
@classmethod
class foo:
def func1(self,x):
do somthing;
def func2(self, aFunc = self.func1):
# make some a call to afunc
afunc(4)
This is why when the method func2 is called within the class aFunc defaults to self.func1, but I can call this same function from outside of the class and pass it a different function at the input.
I get:
NameError: name 'self' is not defined
Here is my setup:
class transmissionLine:
def electricalLength(self, l=l0, f=f0, gamma=self.propagationConstant, deg=False):
But I want to be able to call electricalLength with a different function for gamma, like:
transmissionLine().electricalLength (l, f, gamma=otherFunc)
| [
"Default argument values are computed during function definition, not during function call. So no, you can't. You can do the following, however:\ndef func2(self, aFunc = None):\n if aFunc is None:\n aFunc = self.func1\n ...\n\n",
"The way you are trying wont work, because Foo isnt defined yet.\nclass Foo: \n @classmethod\n def func1(cls, x):\n print 'something: ', cls, x\n\ndef func2(cls, a_func=Foo.func1):\n a_func('test')\n\nFoo.func2 = classmethod(func2)\n\nFoo.func2()\n\n",
"You should write it like this:\nclass Foo(object):\n @classmethod\n def func1(cls, x):\n print x\n def func2(self, afunc=None):\n if afunc is None:\n afunc = self.func1\n afunc(4)\n\nThough it would be helpful if you gave a little more info on what you are trying to do. There is probably a more elegant way to do this without classmethods.\n"
] | [
13,
2,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002791291_class_python.txt |
Q:
Convert seconds to end to date format
SOAP client return seconds to end event.
How can I get from this seconds date in format "yyy-mm-dd hh:ii:ss"
A:
A quick example (add 50000 seconds from now with datetime.timedelta):
>>> import datetime
>>> time_now = datetime.datetime.now()
>>> time_event = time_now + datetime.timedelta(seconds=50000)
>>> time_event.strftime("%Y-%m-%d %H:%M:%S")
'2010-05-08 12:07:05'
| Convert seconds to end to date format | SOAP client return seconds to end event.
How can I get from this seconds date in format "yyy-mm-dd hh:ii:ss"
| [
"A quick example (add 50000 seconds from now with datetime.timedelta):\n>>> import datetime\n>>> time_now = datetime.datetime.now()\n>>> time_event = time_now + datetime.timedelta(seconds=50000)\n>>> time_event.strftime(\"%Y-%m-%d %H:%M:%S\")\n'2010-05-08 12:07:05'\n\n"
] | [
3
] | [] | [] | [
"python",
"time"
] | stackoverflow_0002791358_python_time.txt |
Q:
Passing C++ object to C++ code through Python?
I have written some physics simulation code in C++ and parsing the input text files is a bottleneck of it. As one of the input parameters, the user has to specify a math function which will be evaluated many times at run-time. The C++ code has some pre-defined function classes for this (they are actually quite complex on the math side) and some limited parsing capability but I am not satisfied with this construction at all.
What I need is that both the algorithm and the function evaluation remain speedy, so it is advantageous to keep them both as compiled code (and preferrably, the math functions as C++ function objects). However I thought of glueing the whole simulation together with Python: the user could specify the input parameters in a Python script, while also implementing storage, visualization of the results (matplotlib) and GUI, too, in Python.
I know that most of the time, exposing C++ classes can be done, e.g. with SWIG but I still have a question concerning the parsing of the user defined math function in Python:
Is it possible to somehow to construct a C++ function object in Python and pass it to the C++ algorithm?
E.g. when I call
f = WrappedCPPGaussianFunctionClass(sigma=0.5)
WrappedCPPAlgorithm(f)
in Python, it would return a pointer to a C++ object which would then be passed to a C++ routine requiring such a pointer, or something similar... (don't ask me about memory management in this case, though :S)
The point is that no callback should be made to Python code in the algorithm. Later I would like to extend this example to also do some simple expression parsing on the Python side, such as sum or product of functions, and return some compound, parse-tree like C++ object but let's stay at the basics for now.
Sorry for the long post and thx for the suggestions in advance.
A:
I do things similar to this all the time. The simplest solution, and the one I usually pick because, if nothing else, I'm lazy, is to flatten your API to a C-like API and then just pass pointers to and from Python (or your other language of choice).
First create your classes
class MyFunctionClass
{
public:
MyFunctionClass(int Param)
...
};
class MyAlgorithmClass
{
public:
MyAlgorithmClass(myfunctionclass& Func)
...
};
Then create a C-style api of functions that creates and destroys those classes. I usually flatted in out to pass void* around becuase the languages I use don't keep type safety anyway. It's just easier that way. Just make sure to cast back to the right type before you actually use the void*
void* CreateFunction(int Param)
{
return new MyFunctionClass(Param);
}
void DeleteFunction(void* pFunc)
{
if (pFunc)
delete (MyFunctionClass*)pFunc;
}
void* CreateAlgorithm(void* pFunc)
{
return new MyAlgorithmClass(*(MyFunctionClass*)pFunc)
}
void DelteAlgorithm(void* pAlg)
{
if (pAlg)
delete (MyAlgorithmClass*)pAlg;
}
No all you need to do is make python call those C-style function. In fact, they can (and probably should) be extern "c" functions to make the linking that much easier.
| Passing C++ object to C++ code through Python? | I have written some physics simulation code in C++ and parsing the input text files is a bottleneck of it. As one of the input parameters, the user has to specify a math function which will be evaluated many times at run-time. The C++ code has some pre-defined function classes for this (they are actually quite complex on the math side) and some limited parsing capability but I am not satisfied with this construction at all.
What I need is that both the algorithm and the function evaluation remain speedy, so it is advantageous to keep them both as compiled code (and preferrably, the math functions as C++ function objects). However I thought of glueing the whole simulation together with Python: the user could specify the input parameters in a Python script, while also implementing storage, visualization of the results (matplotlib) and GUI, too, in Python.
I know that most of the time, exposing C++ classes can be done, e.g. with SWIG but I still have a question concerning the parsing of the user defined math function in Python:
Is it possible to somehow to construct a C++ function object in Python and pass it to the C++ algorithm?
E.g. when I call
f = WrappedCPPGaussianFunctionClass(sigma=0.5)
WrappedCPPAlgorithm(f)
in Python, it would return a pointer to a C++ object which would then be passed to a C++ routine requiring such a pointer, or something similar... (don't ask me about memory management in this case, though :S)
The point is that no callback should be made to Python code in the algorithm. Later I would like to extend this example to also do some simple expression parsing on the Python side, such as sum or product of functions, and return some compound, parse-tree like C++ object but let's stay at the basics for now.
Sorry for the long post and thx for the suggestions in advance.
| [
"I do things similar to this all the time. The simplest solution, and the one I usually pick because, if nothing else, I'm lazy, is to flatten your API to a C-like API and then just pass pointers to and from Python (or your other language of choice).\nFirst create your classes\nclass MyFunctionClass\n{\n public:\n MyFunctionClass(int Param)\n ...\n};\n\nclass MyAlgorithmClass\n{\n public:\n MyAlgorithmClass(myfunctionclass& Func)\n ...\n};\n\nThen create a C-style api of functions that creates and destroys those classes. I usually flatted in out to pass void* around becuase the languages I use don't keep type safety anyway. It's just easier that way. Just make sure to cast back to the right type before you actually use the void*\n void* CreateFunction(int Param)\n {\n return new MyFunctionClass(Param);\n }\n\n void DeleteFunction(void* pFunc)\n {\n if (pFunc)\n delete (MyFunctionClass*)pFunc;\n }\n\n void* CreateAlgorithm(void* pFunc)\n {\n return new MyAlgorithmClass(*(MyFunctionClass*)pFunc)\n }\n\n void DelteAlgorithm(void* pAlg)\n {\n if (pAlg)\n delete (MyAlgorithmClass*)pAlg;\n }\n\nNo all you need to do is make python call those C-style function. In fact, they can (and probably should) be extern \"c\" functions to make the linking that much easier. \n"
] | [
3
] | [] | [] | [
"c++",
"functor",
"python",
"word_wrap"
] | stackoverflow_0002791653_c++_functor_python_word_wrap.txt |
Q:
Why do you need this method inside a Django model?
class mytable(models.Model):
abc = ...
xyz = ...
def __unicode__(self):
Why is the def __unicode__ necessary?
A:
These resources do a far better job at explaining that I can:
Django Docs
Python Docs
__str__ versus __unicode__
In short, you need to define __unicode__ so Django can print some readable representation when you call an object. __unicode__ is also the 'new' preferred way to return your character string.
A:
__unicode__ is a Python "magic method" that determines how your object looks when you want to display that object as a unicode string. It's not Django-specific or anything, but any time you either call str() or unicode() or use string interpolation and pass that object in, it will call that method to determine what unicode string is returned.
For objects displayed in templates, this method will be called to determine what is displayed in the template because this is the method that Python uses to determine what an object looks like as a character string.
A:
so the admin can display its breadcrumbs, and you are able to put {{ myobject }} into a template to show the __unicode__ of your object.
A:
In my experience, there is one very important reason why to define the __unicode__ method: the Django shell.
Playing with the console is usually a very powerful tool while developing a Django application, because it allows inspection of your (and others) classes, as well as quick prototype ideas and solutions.
And, working in the shell, every time you do a print a where a is a model instance, you will thank a lot having a __unicode__ method that allows to easily recognize what object are you working with.
| Why do you need this method inside a Django model? | class mytable(models.Model):
abc = ...
xyz = ...
def __unicode__(self):
Why is the def __unicode__ necessary?
| [
"These resources do a far better job at explaining that I can:\nDjango Docs\nPython Docs\n__str__ versus __unicode__\nIn short, you need to define __unicode__ so Django can print some readable representation when you call an object. __unicode__ is also the 'new' preferred way to return your character string.\n",
"__unicode__ is a Python \"magic method\" that determines how your object looks when you want to display that object as a unicode string. It's not Django-specific or anything, but any time you either call str() or unicode() or use string interpolation and pass that object in, it will call that method to determine what unicode string is returned.\nFor objects displayed in templates, this method will be called to determine what is displayed in the template because this is the method that Python uses to determine what an object looks like as a character string.\n",
"so the admin can display its breadcrumbs, and you are able to put {{ myobject }} into a template to show the __unicode__ of your object.\n",
"In my experience, there is one very important reason why to define the __unicode__ method: the Django shell.\nPlaying with the console is usually a very powerful tool while developing a Django application, because it allows inspection of your (and others) classes, as well as quick prototype ideas and solutions.\nAnd, working in the shell, every time you do a print a where a is a model instance, you will thank a lot having a __unicode__ method that allows to easily recognize what object are you working with.\n"
] | [
5,
2,
1,
1
] | [] | [] | [
"django",
"python",
"unicode"
] | stackoverflow_0002791694_django_python_unicode.txt |
Q:
Optimization in Python - do's, don'ts and rules of thumb
Well I was reading this post and then I came across a code which was:
jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?
Well I tried it and timed three codes
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?
If this is - What are the other implicit/internal optimizations in Python ?
What are the developer's rules of thumb for optimization in Python?
Edit1: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from Triptych and Ali A for the do's.
I will change the question a bit and request for don'ts.
Can we have some experiences from people who faced the 'slowness', what was the problem and how it was corrected?
Edit2: For those who haven't here is an interesting read
Edit3: Incorrect usage of timeit in question please see dF's answer for correct usage and hence timings for the three codes.
A:
You're not using timeit correctly: the argument to -s (setup) is a statement to be executed once initially, so you're really just testing an empty statement. You want to do
$ python -m timeit -s "jokes=range(1000000)" "domain=[(0,(len(jokes)*2)-i-1) for i in range(0, len(jokes)*2)]"
10 loops, best of 3: 1.08 sec per loop
$ python -m timeit -s "jokes=range(1000000)" "l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0, l*2)]"
10 loops, best of 3: 908 msec per loop
$ python -m timeit -s "jokes=range(1000000)" "l=len(jokes*2);domain=[(0,l-i-1) for i in range(0, l)]"
10 loops, best of 3: 813 msec per loop
While the speedup is still not dramatic, it's more significant (16% and 25% respectively). So since it doesn't make the code any more complicated, this simple optimization is probably worth it.
To address the actual question... the usual rule of thumb in Python is to
Favor straightforward and readable code over optimization when coding.
Profile your code (profile / cProfile and pstats are your friends) to figure out what you need to optimize (usually things like tight loops).
As a last resort, re-implement these as C extensions, which is made much easier with tools like pyrex and cython.
One thing to watch out for: compared to many other languages, function calls are relatively expensive in Python which is why the optimization in your example made a difference even though len is O(1) for lists.
A:
Read this: Python Speed / Performance Tips
Also, in your example, the total time is so short that the margin of error will outweigh any actual difference in speed.
A:
This applies to all programming, not just Python:
Profile
Identify bottlenecks
Optimize
And I would even add not to bother doing any of that unless you have a slowness issue that is causing you pain.
And perhaps most important is that Unit tests will help you during the actual process.
A:
On a tangentially related note, chaining together generators is much more efficient than chaining together list comprehensions, and often more intuitive.
As for the developer's rules of thumb for optimization in Python, they're the same as they are in all languages.
Don't optimize.
(advanced) Optimize later.
A:
len for lists is O(1). It doesn't need to scan the whole list to find the length, because the size of the list is stored for lookup. But apparently, it is still slightly faster to extract it into a local variable.
To answer your question though, I would never care about performance variations on the order of 5%, unless I was doing some crazy tight inner loop optimizations in some simulation or something. And in that case, you could speed this up much more by not using range at all.
A:
The most important thing to do is to write idiomatic, clear, and beautiful Python code. Many common tasks are already found in the stdlib, so you don't have to rewrite a slower version. (I'm thinking of string methods and itertools specifically here.) Make liberal use of Python's builtin containers, too. dict for example has had "the snot optimized" out of it, and it's said that Python code using dicts will be faster than plain C!
If that's not already fast enough, there are some hacks you can use, but it's also signal that you probably should be offloading some work to C extension modules.
Regarding list comprehensions: CPython is able to do a few optimizations over regular accumulator loops. Namely the LIST_APPEND opcode makes appending to a list native operation.
A:
I have a program that parses log files and generates a data warehouse. A typical run involves around 200M log file lines, and runs for the better part of a day. Well worth optimizing!
Since it's a parser, and parsing some rather variable and idiosyncratic and untrustworthy text at that, there are around 100 regular expressions, dutifully re.compiled() in advance, and applied to each of the 200M log file lines. I was pretty sure they were my bottleneck, and had been pondering how to improve that situation. Had some ideas: on the one hand, make fewer, fancier REs; on the other, more and simpler; stuff like that.
I profiled with CProfile, and looked at the result in "runsnake".
RE processing was only about 10% of code execution time. That's not it!
In fact, a large square blob in the runsnake display instantly told me that about 60% of my time was spent in one of those infamous "one line changes" I'd added one day, eliminating non-printing characters (which appear occasionally, but always represent something so bogus I really don't care about it). These were confusing my parse and throwing exceptions, which I did care about because it halted my day of log file analysis.
line = ''.join([c for c in line if curses.ascii.isprint(c) ])
There you go: that line touches every byte of every one of those 200M lines (and the lines average a couple hundred bytes long). No wonder it's 60% of my execution time!
There are better ways to handle this, I now know, such as str.translate(). But such lines are rare, and I don't care about them anyway, and they end up throwing an exception: now I just catch the exception at the right spot and skip the line. Voila! the program's around 3X faster, instantly!
So the profiling
highlighted, in around one second, where the problem actually was
drew my attention away from a mistaken assumption about where the problem was (which might be the even greater pay-off)
A:
Can we have some experiences from
people who faced the 'slowness', what
was the problem and how it was
corrected?
The problem was slow data retrieval in a GUI app. I gained a 50x speedup by adding an index to the table, and was widely hailed as a hero and savior.
| Optimization in Python - do's, don'ts and rules of thumb | Well I was reading this post and then I came across a code which was:
jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?
Well I tried it and timed three codes
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?
If this is - What are the other implicit/internal optimizations in Python ?
What are the developer's rules of thumb for optimization in Python?
Edit1: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from Triptych and Ali A for the do's.
I will change the question a bit and request for don'ts.
Can we have some experiences from people who faced the 'slowness', what was the problem and how it was corrected?
Edit2: For those who haven't here is an interesting read
Edit3: Incorrect usage of timeit in question please see dF's answer for correct usage and hence timings for the three codes.
| [
"You're not using timeit correctly: the argument to -s (setup) is a statement to be executed once initially, so you're really just testing an empty statement. You want to do\n$ python -m timeit -s \"jokes=range(1000000)\" \"domain=[(0,(len(jokes)*2)-i-1) for i in range(0, len(jokes)*2)]\"\n10 loops, best of 3: 1.08 sec per loop\n$ python -m timeit -s \"jokes=range(1000000)\" \"l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0, l*2)]\"\n10 loops, best of 3: 908 msec per loop\n$ python -m timeit -s \"jokes=range(1000000)\" \"l=len(jokes*2);domain=[(0,l-i-1) for i in range(0, l)]\"\n10 loops, best of 3: 813 msec per loop\n\nWhile the speedup is still not dramatic, it's more significant (16% and 25% respectively). So since it doesn't make the code any more complicated, this simple optimization is probably worth it.\nTo address the actual question... the usual rule of thumb in Python is to \n\nFavor straightforward and readable code over optimization when coding. \nProfile your code (profile / cProfile and pstats are your friends) to figure out what you need to optimize (usually things like tight loops). \nAs a last resort, re-implement these as C extensions, which is made much easier with tools like pyrex and cython.\n\nOne thing to watch out for: compared to many other languages, function calls are relatively expensive in Python which is why the optimization in your example made a difference even though len is O(1) for lists.\n",
"Read this: Python Speed / Performance Tips\nAlso, in your example, the total time is so short that the margin of error will outweigh any actual difference in speed.\n",
"This applies to all programming, not just Python:\n\nProfile\nIdentify bottlenecks\nOptimize\n\nAnd I would even add not to bother doing any of that unless you have a slowness issue that is causing you pain.\nAnd perhaps most important is that Unit tests will help you during the actual process.\n",
"On a tangentially related note, chaining together generators is much more efficient than chaining together list comprehensions, and often more intuitive.\nAs for the developer's rules of thumb for optimization in Python, they're the same as they are in all languages.\n\nDon't optimize.\n(advanced) Optimize later.\n\n",
"len for lists is O(1). It doesn't need to scan the whole list to find the length, because the size of the list is stored for lookup. But apparently, it is still slightly faster to extract it into a local variable. \nTo answer your question though, I would never care about performance variations on the order of 5%, unless I was doing some crazy tight inner loop optimizations in some simulation or something. And in that case, you could speed this up much more by not using range at all.\n",
"The most important thing to do is to write idiomatic, clear, and beautiful Python code. Many common tasks are already found in the stdlib, so you don't have to rewrite a slower version. (I'm thinking of string methods and itertools specifically here.) Make liberal use of Python's builtin containers, too. dict for example has had \"the snot optimized\" out of it, and it's said that Python code using dicts will be faster than plain C!\nIf that's not already fast enough, there are some hacks you can use, but it's also signal that you probably should be offloading some work to C extension modules.\nRegarding list comprehensions: CPython is able to do a few optimizations over regular accumulator loops. Namely the LIST_APPEND opcode makes appending to a list native operation.\n",
"I have a program that parses log files and generates a data warehouse. A typical run involves around 200M log file lines, and runs for the better part of a day. Well worth optimizing!\nSince it's a parser, and parsing some rather variable and idiosyncratic and untrustworthy text at that, there are around 100 regular expressions, dutifully re.compiled() in advance, and applied to each of the 200M log file lines. I was pretty sure they were my bottleneck, and had been pondering how to improve that situation. Had some ideas: on the one hand, make fewer, fancier REs; on the other, more and simpler; stuff like that.\nI profiled with CProfile, and looked at the result in \"runsnake\".\nRE processing was only about 10% of code execution time. That's not it!\nIn fact, a large square blob in the runsnake display instantly told me that about 60% of my time was spent in one of those infamous \"one line changes\" I'd added one day, eliminating non-printing characters (which appear occasionally, but always represent something so bogus I really don't care about it). These were confusing my parse and throwing exceptions, which I did care about because it halted my day of log file analysis.\n\nline = ''.join([c for c in line if curses.ascii.isprint(c) ])\n\nThere you go: that line touches every byte of every one of those 200M lines (and the lines average a couple hundred bytes long). No wonder it's 60% of my execution time!\nThere are better ways to handle this, I now know, such as str.translate(). But such lines are rare, and I don't care about them anyway, and they end up throwing an exception: now I just catch the exception at the right spot and skip the line. Voila! the program's around 3X faster, instantly!\nSo the profiling\n\nhighlighted, in around one second, where the problem actually was\ndrew my attention away from a mistaken assumption about where the problem was (which might be the even greater pay-off)\n\n",
"\nCan we have some experiences from\n people who faced the 'slowness', what\n was the problem and how it was\n corrected?\n\nThe problem was slow data retrieval in a GUI app. I gained a 50x speedup by adding an index to the table, and was widely hailed as a hero and savior.\n"
] | [
12,
4,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0000403794_optimization_python.txt |
Q:
python httplib httpexception error codes
Does httplib.HTTPException have error codes? If so how do I get at them from the exception instance? Any help is appreciated.
A:
The httplib module doesn't use exceptions to convey HTTP responses, just genuine errors (invalid HTTP responses, broken headers, invalid status codes, prematurely broken connections, etc.) Most of the httplib.HTTPException subclasses just have an associated message string (stored in the args attribute), if even that. httplib.HTTPException itself may have an "errno" value as the first entry in args (when raised through httplib.FakeSocket) but it's not a HTTP error code.
The HTTP response codes are conveyed through the httplib.HTTPConnection object, though; the getresponse method will (usually) return a HTTPResponse instance with a status attribute set to the HTTP response code, and a reason attribute set to the text version of it. This includes error codes like 404 and 500. I say "usually" because you (or a library you use) can override httplib.HTTPConnection.response_class to return something else.
| python httplib httpexception error codes | Does httplib.HTTPException have error codes? If so how do I get at them from the exception instance? Any help is appreciated.
| [
"The httplib module doesn't use exceptions to convey HTTP responses, just genuine errors (invalid HTTP responses, broken headers, invalid status codes, prematurely broken connections, etc.) Most of the httplib.HTTPException subclasses just have an associated message string (stored in the args attribute), if even that. httplib.HTTPException itself may have an \"errno\" value as the first entry in args (when raised through httplib.FakeSocket) but it's not a HTTP error code.\nThe HTTP response codes are conveyed through the httplib.HTTPConnection object, though; the getresponse method will (usually) return a HTTPResponse instance with a status attribute set to the HTTP response code, and a reason attribute set to the text version of it. This includes error codes like 404 and 500. I say \"usually\" because you (or a library you use) can override httplib.HTTPConnection.response_class to return something else.\n"
] | [
5
] | [] | [] | [
"exception",
"http",
"python",
"tcp"
] | stackoverflow_0002791946_exception_http_python_tcp.txt |
Q:
Speed vs security vs compatibility over methods to do string concatenation in Python
Similar questions have been brought (good speed comparison there) on this same subject. Hopefully this question is different and updated to Python 2.6 and 3.0.
So far I believe the faster and most compatible method (among different Python versions) is the plain simple + sign:
text = "whatever" + " you " + SAY
But I keep hearing and reading it's not secure and / or advisable.
I'm not even sure how many methods are there to manipulate strings! I could count only about 4: There's interpolation and all its sub-options such as % and format and then there's the simple ones, join and +.
Finally, the new approach to string formatting, which is with format, is certainly not good for backwards compatibility at same time making % not good for forward compatibility. But should it be used for every string manipulation, including every concatenation, whenever we restrict ourselves to 3.x only?
Well, maybe this is more of a wiki than a question, but I do wish to have an answer on which is the proper usage of each string manipulation method. And which one could be generally used with each focus in mind (best all around for compatibility, for speed and for security).
Thanks.
edit: I'm not sure I should accept an answer if I don't feel it really answers the question... But my point is that all them 3 together do a proper job.
Daniel's most voted answer is actually the one I'd prefer for accepting, if not for the "note". I highly disagree with "concatenation is strictly using the + operator to concatenate strings" because, for one, join does string concatenation as well, and we can build any arbitrary library for that.
All current 3 answers are valuable and I'd rather having some answer mixing them all. While nobody volunteer to do that, I guess by choosing the one less voted (but fairly broader than THC4k's, which is more like a large and very welcomed comment) I can draw attention to the others as well.
A:
As a note: Really this is all about string construction and not concatenation, per se, as concatenation is strictly using the + operator to concatenate strings together one after the other.
+ (concatenation) - generally inefficient but can be easier to read for some people, only use when readability is priority and performance is not (simple scripts, throwaway scripts, non-performance intensive code)
join (building a string from a sequence of strings) - use this when you have a sequence of strings that you need to join using a common character (or no character at all if you want to use the empty string '' to join on)
% and format (interpolation) - basically every other operation should use whichever one of these is appropriate, choose which operator/function is appropriate based on which version of Python you want to support for the lifetime of the code (use % for 2.x and format for 3.x)
A:
The problem with + for strings is the same as in many other languages: Each time you extend the string, it is copied. So to construct a single strings from 100 substrings, Python copies each of the 99 steps.
And that takes some time:
# join 100 pretty short strings
python -m timeit -s "s = ['pretty short'] * 100" "t = ''.join(s)"
100000 loops, best of 3: 4.18 usec per loop
# same thing, 6 times slower
python -m timeit -s "s = ['pretty short'] * 100" "t = ''" "for x in s:" " t+=x"
10000 loops, best of 3: 30 usec per loop
A:
Using + is OK, but not if it's automated:
a + small + number + of + strings + "is pretty fast"
but this can be very slow:
s = ''
for line in anything:
s += line
Use this instead:
s = ''.join([line for line in anything])
There are pros and cons of use + vs '%s%line' - using + will fail here:
s = 'Error - unexpected string' + 42
Whether you want it to throw an exception, or silently do something unusual depends on your use.
| Speed vs security vs compatibility over methods to do string concatenation in Python | Similar questions have been brought (good speed comparison there) on this same subject. Hopefully this question is different and updated to Python 2.6 and 3.0.
So far I believe the faster and most compatible method (among different Python versions) is the plain simple + sign:
text = "whatever" + " you " + SAY
But I keep hearing and reading it's not secure and / or advisable.
I'm not even sure how many methods are there to manipulate strings! I could count only about 4: There's interpolation and all its sub-options such as % and format and then there's the simple ones, join and +.
Finally, the new approach to string formatting, which is with format, is certainly not good for backwards compatibility at same time making % not good for forward compatibility. But should it be used for every string manipulation, including every concatenation, whenever we restrict ourselves to 3.x only?
Well, maybe this is more of a wiki than a question, but I do wish to have an answer on which is the proper usage of each string manipulation method. And which one could be generally used with each focus in mind (best all around for compatibility, for speed and for security).
Thanks.
edit: I'm not sure I should accept an answer if I don't feel it really answers the question... But my point is that all them 3 together do a proper job.
Daniel's most voted answer is actually the one I'd prefer for accepting, if not for the "note". I highly disagree with "concatenation is strictly using the + operator to concatenate strings" because, for one, join does string concatenation as well, and we can build any arbitrary library for that.
All current 3 answers are valuable and I'd rather having some answer mixing them all. While nobody volunteer to do that, I guess by choosing the one less voted (but fairly broader than THC4k's, which is more like a large and very welcomed comment) I can draw attention to the others as well.
| [
"As a note: Really this is all about string construction and not concatenation, per se, as concatenation is strictly using the + operator to concatenate strings together one after the other.\n\n+ (concatenation) - generally inefficient but can be easier to read for some people, only use when readability is priority and performance is not (simple scripts, throwaway scripts, non-performance intensive code)\njoin (building a string from a sequence of strings) - use this when you have a sequence of strings that you need to join using a common character (or no character at all if you want to use the empty string '' to join on)\n% and format (interpolation) - basically every other operation should use whichever one of these is appropriate, choose which operator/function is appropriate based on which version of Python you want to support for the lifetime of the code (use % for 2.x and format for 3.x)\n\n",
"The problem with + for strings is the same as in many other languages: Each time you extend the string, it is copied. So to construct a single strings from 100 substrings, Python copies each of the 99 steps. \nAnd that takes some time:\n# join 100 pretty short strings\npython -m timeit -s \"s = ['pretty short'] * 100\" \"t = ''.join(s)\"\n100000 loops, best of 3: 4.18 usec per loop\n\n# same thing, 6 times slower\npython -m timeit -s \"s = ['pretty short'] * 100\" \"t = ''\" \"for x in s:\" \" t+=x\"\n10000 loops, best of 3: 30 usec per loop\n\n",
"Using + is OK, but not if it's automated:\na + small + number + of + strings + \"is pretty fast\"\n\nbut this can be very slow:\ns = ''\nfor line in anything:\n s += line \n\nUse this instead:\ns = ''.join([line for line in anything])\n\nThere are pros and cons of use + vs '%s%line' - using + will fail here:\ns = 'Error - unexpected string' + 42\n\nWhether you want it to throw an exception, or silently do something unusual depends on your use.\n"
] | [
5,
4,
3
] | [] | [] | [
"concatenation",
"python",
"string"
] | stackoverflow_0002791931_concatenation_python_string.txt |
Q:
show() doesn't redraw anymore
I am working in linux and I don't know why using python and matplotlib commands draws me only once the chart I want.
The first time I call show() the plot is drawn, wihtout any problem, but not the second time and the following.
I close the window showing the chart between the two calls. Do you know why and hot to fix it?
Thanks AFG
from numpy import *
from pylab import *
data = array( [ 1,2,3,4,5] )
plot(data)
[<matplotlib.lines.Line2D object at 0x90c98ac>]
show() # this call shows me a plot
#..now I close the window...
data = array( [ 1,2,3,4,5,6] )
plot(data)
[<matplotlib.lines.Line2D object at 0x92dafec>]
show() # this one doesn't shows me anything
A:
in windows this works perfect:
from pylab import *
plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x03442C10>]
#close window here
plot([1,2,3,4])
[<matplotlib.lines.Line2D object at 0x035BC570>]
did you try with:
from matplotlib import interactive
interactive(True)
sometimes matplotlib produces some headaches because we have to remember that some options are set in matplotlibrc (such as the backend or the interactive parameters). If you use matplotlib from different editors (IDLE-tk, pycrust-wxpython) or alternating interactive with scripting, then you have to take into account that the configuration that works in one mode could give you problems in the other mode and must be modified programmatically or using a dedicated configuration file.
The example I give, works directly (and without show()) because in matplotlibrc I have interactive set to True as default
A:
You likely have conflicts between your editor/IDE windowing system, and your plot windows.
A very good way around this is to use IPython. IPython is a great interactive environment, and has worked out these issues plus has many other advantages. At the beginning, start IPython with the command (from a terminal window) ipython -pylab to put it in the interactive pylab mode.
A:
I'm guessing that you are doing this in IDLE on Windows because that's where I've noticed this same problem.
From what I've deduced, there is a problem with using the TkAgg backend,which comes with the basic Python dist and appears to be the default for matplotlib, when using matplotlib with IDLE. It has something to do with the way IDLE uses subprocesses because if I start IDLE with the -n option, which disables subprocesses, I don't have this problem. An easy way to start it IDLE with the -n option on Windows is to right click and file and select 'Open with IDLE'. If you do this you should get an IDLE shell which says
=== No Subprocess ===
just above the prompt. For instance, borrowing code from joaquin's solution, you could try this simple code:
from matplotlib import interactive
interactive(True)
from pylab import *
plot([1,2,3,4])
then close the window and type the last line into the console again. It works for me in IDLE with the -n option.
So what can you do? You can always run IDLE in the mode without subprocesses, but there are dangers to that. You can use a different IDE. Many people suggest IPython though I'm not sold on it yet myself. You could also try a different backend for matplotlib. I'm going to try that in a little while cause I've been wondering whether it will work.
A:
show() is only meant to be used once in a program, at the very end: it is a never ending loop that checks for events in the graphic windows.
The normal way of doing what you want is:
# … plot …
draw() # Draws for real
raw_input() # Or anything that waits for user input
# … 2nd plot …
draw()
raw_input()
# Last plot
show() # or, again, draw(); raw_input()
You could try to see whether this works for you.
Alternatively, you can try to change the backend, as some backends work better than others:
import matplotlib
matplotlib.use('TkAgg') # For other backends, do matplotlib.use('') in a shell
| show() doesn't redraw anymore | I am working in linux and I don't know why using python and matplotlib commands draws me only once the chart I want.
The first time I call show() the plot is drawn, wihtout any problem, but not the second time and the following.
I close the window showing the chart between the two calls. Do you know why and hot to fix it?
Thanks AFG
from numpy import *
from pylab import *
data = array( [ 1,2,3,4,5] )
plot(data)
[<matplotlib.lines.Line2D object at 0x90c98ac>]
show() # this call shows me a plot
#..now I close the window...
data = array( [ 1,2,3,4,5,6] )
plot(data)
[<matplotlib.lines.Line2D object at 0x92dafec>]
show() # this one doesn't shows me anything
| [
"in windows this works perfect:\nfrom pylab import *\nplot([1,2,3,4])\n[<matplotlib.lines.Line2D object at 0x03442C10>]\n#close window here\nplot([1,2,3,4])\n[<matplotlib.lines.Line2D object at 0x035BC570>]\n\ndid you try with:\nfrom matplotlib import interactive\ninteractive(True)\n\nsometimes matplotlib produces some headaches because we have to remember that some options are set in matplotlibrc (such as the backend or the interactive parameters). If you use matplotlib from different editors (IDLE-tk, pycrust-wxpython) or alternating interactive with scripting, then you have to take into account that the configuration that works in one mode could give you problems in the other mode and must be modified programmatically or using a dedicated configuration file.\nThe example I give, works directly (and without show()) because in matplotlibrc I have interactive set to True as default \n",
"You likely have conflicts between your editor/IDE windowing system, and your plot windows. \nA very good way around this is to use IPython. IPython is a great interactive environment, and has worked out these issues plus has many other advantages. At the beginning, start IPython with the command (from a terminal window) ipython -pylab to put it in the interactive pylab mode.\n",
"I'm guessing that you are doing this in IDLE on Windows because that's where I've noticed this same problem. \nFrom what I've deduced, there is a problem with using the TkAgg backend,which comes with the basic Python dist and appears to be the default for matplotlib, when using matplotlib with IDLE. It has something to do with the way IDLE uses subprocesses because if I start IDLE with the -n option, which disables subprocesses, I don't have this problem. An easy way to start it IDLE with the -n option on Windows is to right click and file and select 'Open with IDLE'. If you do this you should get an IDLE shell which says \n === No Subprocess ===\njust above the prompt. For instance, borrowing code from joaquin's solution, you could try this simple code:\nfrom matplotlib import interactive\ninteractive(True)\nfrom pylab import *\nplot([1,2,3,4])\n\nthen close the window and type the last line into the console again. It works for me in IDLE with the -n option.\nSo what can you do? You can always run IDLE in the mode without subprocesses, but there are dangers to that. You can use a different IDE. Many people suggest IPython though I'm not sold on it yet myself. You could also try a different backend for matplotlib. I'm going to try that in a little while cause I've been wondering whether it will work.\n",
"show() is only meant to be used once in a program, at the very end: it is a never ending loop that checks for events in the graphic windows.\nThe normal way of doing what you want is:\n# … plot …\ndraw() # Draws for real\nraw_input() # Or anything that waits for user input\n\n# … 2nd plot …\ndraw()\nraw_input()\n\n# Last plot\nshow() # or, again, draw(); raw_input()\n\nYou could try to see whether this works for you.\nAlternatively, you can try to change the backend, as some backends work better than others:\nimport matplotlib\nmatplotlib.use('TkAgg') # For other backends, do matplotlib.use('') in a shell\n\n"
] | [
2,
1,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002789180_matplotlib_python.txt |
Q:
try...else...except syntax error
I can't understand this...
Cannot get this code to run and I've no idea why it is a syntax error.
try:
newT.read()
#existingArtist = newT['Exif.Image.Artist'].value
#existingKeywords = newT['Xmp.dc.subject'].value
except KeyError:
print "KeyError"
else:
#Program will NOT remove existing values
newT.read()
if existingArtist != "" :
newT['Exif.Image.Artist'] = artistString
print existingKeywords
keywords = os.path.normpath(relativePath).split(os.sep)
print keywords
newT['Xmp.dc.subject'] = existingKeywords + keywords
newT.write()
except:
print "Cannot write tags to ",filePath
Syntax error occurs on the last "except:". Again...I have no idea why python is throwing a syntax error (spent ~3hrs on this problem).
A:
You can't have another except after the else. The try, except, and else blocks aren't like function calls or other code - you can't just mix and match them as you like. It's always a specific sequence:
try:
# execute some code
except:
# if that code raises an error, go here
# (this part is just regular code)
else:
# if the "try" code did not raise an error, go here
# (this part is also just regular code)
If you want to catch an error that occurs during the else block, you'll need another try statement. Like so:
try:
...
except:
...
else:
try:
...
except:
...
FYI, the same applies if you want to catch an error that occurs during the except block - in that case as well, you would need another try statement, like this:
try:
...
except:
try:
...
except:
...
else:
...
A:
Reading the documentation would give you this phrase:
The try ... except statement has an optional else clause, which, when present, must follow all except clauses.
Move else to the end of your handler.
A:
looking at the python documentation: http://docs.python.org/reference/compound_stmts.html#the-try-statement It doesn't look like you can have multiple elses with try. Maybe you meant finally at the end?
| try...else...except syntax error | I can't understand this...
Cannot get this code to run and I've no idea why it is a syntax error.
try:
newT.read()
#existingArtist = newT['Exif.Image.Artist'].value
#existingKeywords = newT['Xmp.dc.subject'].value
except KeyError:
print "KeyError"
else:
#Program will NOT remove existing values
newT.read()
if existingArtist != "" :
newT['Exif.Image.Artist'] = artistString
print existingKeywords
keywords = os.path.normpath(relativePath).split(os.sep)
print keywords
newT['Xmp.dc.subject'] = existingKeywords + keywords
newT.write()
except:
print "Cannot write tags to ",filePath
Syntax error occurs on the last "except:". Again...I have no idea why python is throwing a syntax error (spent ~3hrs on this problem).
| [
"You can't have another except after the else. The try, except, and else blocks aren't like function calls or other code - you can't just mix and match them as you like. It's always a specific sequence:\ntry:\n # execute some code\nexcept:\n # if that code raises an error, go here\n # (this part is just regular code)\nelse:\n # if the \"try\" code did not raise an error, go here\n # (this part is also just regular code)\n\nIf you want to catch an error that occurs during the else block, you'll need another try statement. Like so:\ntry:\n ...\nexcept:\n ...\nelse:\n try:\n ...\n except:\n ...\n\nFYI, the same applies if you want to catch an error that occurs during the except block - in that case as well, you would need another try statement, like this:\ntry:\n ...\nexcept:\n try:\n ...\n except:\n ...\nelse:\n ...\n\n",
"Reading the documentation would give you this phrase:\n\nThe try ... except statement has an optional else clause, which, when present, must follow all except clauses. \n\nMove else to the end of your handler.\n",
"looking at the python documentation: http://docs.python.org/reference/compound_stmts.html#the-try-statement It doesn't look like you can have multiple elses with try. Maybe you meant finally at the end?\n"
] | [
25,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0002792491_python.txt |
Q:
running code if try statements were successful in python
I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this:
successful = False
try:
#code that might fail
successful = True
except:
#error handling if code failed
if successful:
#code to run if try was successful that isn't part of try
but I was wondering if there was a shorter way.
A:
You want else:
for i in [0, 1]:
try:
print '10 / %i: ' % i, 10 / i
except:
print 'Uh-Oh'
else:
print 'Yay!'
A:
You are looking for the else keyword:
try:
#code that might fail
except SomeException:
#error handling if code failed
else:
# do this if no exception occured
| running code if try statements were successful in python | I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this:
successful = False
try:
#code that might fail
successful = True
except:
#error handling if code failed
if successful:
#code to run if try was successful that isn't part of try
but I was wondering if there was a shorter way.
| [
"You want else:\nfor i in [0, 1]:\n try:\n print '10 / %i: ' % i, 10 / i\n except:\n print 'Uh-Oh'\n else:\n print 'Yay!'\n\n",
"You are looking for the else keyword:\ntry:\n #code that might fail\nexcept SomeException:\n #error handling if code failed\nelse:\n # do this if no exception occured\n\n"
] | [
79,
24
] | [
"Your try block should be the code you want to execute, and your except should be killing the program. I'd need to understand your object better to give a better answer.\nIn OO programming, you want to \"Tell, don't ask\" so keep all the logic that should happen in the try block, and then your error handling in the except block.\n"
] | [
-5
] | [
"error_handling",
"python",
"try_catch"
] | stackoverflow_0002792568_error_handling_python_try_catch.txt |
Q:
How can I download information from a website if it returns XML/JSON in its response?
Does Python3 have a built in method to do this? Any guidance at all would be great! :)
The website in question exposes all of its information and even gives you an API key to use.
A:
Python includes a json module that can do the conversion for you. For downloading the actual data from the web site, use urllib.request.
| How can I download information from a website if it returns XML/JSON in its response? | Does Python3 have a built in method to do this? Any guidance at all would be great! :)
The website in question exposes all of its information and even gives you an API key to use.
| [
"Python includes a json module that can do the conversion for you. For downloading the actual data from the web site, use urllib.request.\n"
] | [
1
] | [] | [] | [
"python",
"screen_scraping"
] | stackoverflow_0002792613_python_screen_scraping.txt |
Q:
Workflow for App Engine
I'm about to start an App Engine project for the first time. Most likely with Python. I was wondering if anybody could give me a leg up by detailing their workflow when developing for it. What tools do you use to go from start to deployed? Did you do any app engine specific configurations to those tools?
A:
How big of an application are you planning? Using the python runtime, it's pretty easy to get even a medium-to-large sized app developed with nothing more than a text editor (I use TextMate or vi).
Python is an incredibly terse language (or can be), and you can have multiple related handlers in one file, so you don't need anything to handle more than a dozen files across a bunch of directories, like you might with Java for example.
To test your app locally you just need dev_appserver.py and to upload your app you just need appcfg.py. Easy peasy.
Even if you're planning on writing a huge complex app, I would just start small with a simple text editor and find more robust tools when you find that you need them (and know specifically what you need from them).
| Workflow for App Engine | I'm about to start an App Engine project for the first time. Most likely with Python. I was wondering if anybody could give me a leg up by detailing their workflow when developing for it. What tools do you use to go from start to deployed? Did you do any app engine specific configurations to those tools?
| [
"How big of an application are you planning? Using the python runtime, it's pretty easy to get even a medium-to-large sized app developed with nothing more than a text editor (I use TextMate or vi).\nPython is an incredibly terse language (or can be), and you can have multiple related handlers in one file, so you don't need anything to handle more than a dozen files across a bunch of directories, like you might with Java for example.\nTo test your app locally you just need dev_appserver.py and to upload your app you just need appcfg.py. Easy peasy.\nEven if you're planning on writing a huge complex app, I would just start small with a simple text editor and find more robust tools when you find that you need them (and know specifically what you need from them).\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"workflow"
] | stackoverflow_0002792545_google_app_engine_python_workflow.txt |
Q:
Parse metadata from http live stream
I'd like to extract the info string from an internet radio streamed over HTTP. By info string I mean the short note about the currently played song, band name etc.
Preferably I'd like to do it in python. So far I've tried opening a socket but from there I got a bunch of binary data that I could not parse...
thanks for any hints
A:
Sounds like you might need some stepping stone projects before you're ready for this. There's no reason to use a low-level socket library for HTTP. There are great tools both command line utilities and python standard library modules like urlopen2 that can handle the low level TCP and HTTP specifics for you.
Do you know the URL where you data resides? Have you tried something simple on the command line like using cURL to grab the raw HTML and then some basic tools like grep to hunt down the info you need? I assume here the metadata is actually available as HTML as opposed to being in a binary format read directly by the radio streamer (which presumably is in flash perhaps?).
Hard to give you any specifics because your question doesn't include any technical details about your data source.
| Parse metadata from http live stream | I'd like to extract the info string from an internet radio streamed over HTTP. By info string I mean the short note about the currently played song, band name etc.
Preferably I'd like to do it in python. So far I've tried opening a socket but from there I got a bunch of binary data that I could not parse...
thanks for any hints
| [
"Sounds like you might need some stepping stone projects before you're ready for this. There's no reason to use a low-level socket library for HTTP. There are great tools both command line utilities and python standard library modules like urlopen2 that can handle the low level TCP and HTTP specifics for you.\nDo you know the URL where you data resides? Have you tried something simple on the command line like using cURL to grab the raw HTML and then some basic tools like grep to hunt down the info you need? I assume here the metadata is actually available as HTML as opposed to being in a binary format read directly by the radio streamer (which presumably is in flash perhaps?).\nHard to give you any specifics because your question doesn't include any technical details about your data source.\n"
] | [
1
] | [] | [] | [
"http",
"metadata",
"python",
"streaming"
] | stackoverflow_0002766787_http_metadata_python_streaming.txt |
Q:
How to pdb Python code with input?
I'm debugging Python code with pdb.
The code need input from stdin, like:
python -m pdb foo.py < bar.in
Then the pdb will accept the bar.in as commands.
How to tell pdb that the input is for foo.py and not for pdb?
A:
Well, this is a tweak to Aaron's answer, but I think it misses the point in that you want to interactively debug at some point, right? This works but the program exits before you get a chance to debug.
(echo cont;cat bar.in) | python -m pdb foo.py
I think if you can edit foo.py, do import pdb then at the interesting point in foo.py do pdb.set_trace(), and just run python foo.py without the -m pdb and give it bar.in normally
python foo.py < bar.in
A:
A kind of gross work around is to put cont at the beginning of bar.in:
cont
one
two
three
four
aaron@ares ~$ python -m pdb cat.py < bar.in
> ~/cat.py(1)<module>()
-> import sys
(Pdb) one
two
three
four
The program finished and will be restarted
> ~/cat.py(1)<module>()
-> import sys
(Pdb)
| How to pdb Python code with input? | I'm debugging Python code with pdb.
The code need input from stdin, like:
python -m pdb foo.py < bar.in
Then the pdb will accept the bar.in as commands.
How to tell pdb that the input is for foo.py and not for pdb?
| [
"Well, this is a tweak to Aaron's answer, but I think it misses the point in that you want to interactively debug at some point, right? This works but the program exits before you get a chance to debug.\n(echo cont;cat bar.in) | python -m pdb foo.py\n\nI think if you can edit foo.py, do import pdb then at the interesting point in foo.py do pdb.set_trace(), and just run python foo.py without the -m pdb and give it bar.in normally\npython foo.py < bar.in\n\n",
"A kind of gross work around is to put cont at the beginning of bar.in:\ncont\none\ntwo\nthree\nfour\n\n\naaron@ares ~$ python -m pdb cat.py < bar.in \n> ~/cat.py(1)<module>()\n-> import sys\n(Pdb) one\ntwo\nthree\nfour\nThe program finished and will be restarted\n> ~/cat.py(1)<module>()\n-> import sys\n(Pdb) \n\n"
] | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002764055_python.txt |
Q:
Resetting Globals With Importing
I have this code (Reset.py) that works how I want it to unless I import it.
class Res(object):
defaults={}
class NoKey: pass
def __init__(self):
for key, values in defaults.items():
globals()[key]=values
def add_defaults(key, values):
Res.defaults[key]=value
def remove_defaults(key=NoKey, remove_all=False):
if remove_all:
Res.defaults={}
else:
del Res.defaults[key]
Without importing:
>>> a=54
>>> Res.add_default('a', 3)
>>> Res()
<__main__.Res object at 0x>
>>> a
3
>>> #great! :D
With importing:
>>> a=54
>>> Res.add_default('a', 3)
>>> Res()
<Reset.Res object at 0x>
>>> a
54
This must mean when it is imported it changes the globals() under Reset and not __main__. How can I fix this?
[Edited defaults to Res.defaults under remove_defaults (defaults was not a global variable).]
A:
You don't fix this: it isn't broken. Mutating globals, especially implicitly mutating globals within another module's namespace, is a very bad idea that leads to confusing, unmaintainable, untestable code.
Your design seems really confusing. Res doens't really seem to be a class. Most of it's methods aren't methods at all (they aren't mutating some state stored in self); the only one that is defined like a method is your __init__, which won't work (defaults shouldn't be defined from the snippet given; the class namespace only looks up there during the original definition of the class. Do you have another thing, a global named defaults?) If you are trying to use Res to group related stuff, don't use a class for that; that's what modules are for in Python.
Perhaps you should post a question describing the problem you are solving. I suspect this code indicates a very suboptimal design.
| Resetting Globals With Importing | I have this code (Reset.py) that works how I want it to unless I import it.
class Res(object):
defaults={}
class NoKey: pass
def __init__(self):
for key, values in defaults.items():
globals()[key]=values
def add_defaults(key, values):
Res.defaults[key]=value
def remove_defaults(key=NoKey, remove_all=False):
if remove_all:
Res.defaults={}
else:
del Res.defaults[key]
Without importing:
>>> a=54
>>> Res.add_default('a', 3)
>>> Res()
<__main__.Res object at 0x>
>>> a
3
>>> #great! :D
With importing:
>>> a=54
>>> Res.add_default('a', 3)
>>> Res()
<Reset.Res object at 0x>
>>> a
54
This must mean when it is imported it changes the globals() under Reset and not __main__. How can I fix this?
[Edited defaults to Res.defaults under remove_defaults (defaults was not a global variable).]
| [
"You don't fix this: it isn't broken. Mutating globals, especially implicitly mutating globals within another module's namespace, is a very bad idea that leads to confusing, unmaintainable, untestable code.\nYour design seems really confusing. Res doens't really seem to be a class. Most of it's methods aren't methods at all (they aren't mutating some state stored in self); the only one that is defined like a method is your __init__, which won't work (defaults shouldn't be defined from the snippet given; the class namespace only looks up there during the original definition of the class. Do you have another thing, a global named defaults?) If you are trying to use Res to group related stuff, don't use a class for that; that's what modules are for in Python.\nPerhaps you should post a question describing the problem you are solving. I suspect this code indicates a very suboptimal design.\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002793060_python_python_3.x.txt |
Q:
Parsing files with python
My input file is going to be something like this
key "value"
key "value"
... the above lines repeat
What I do is read the file contents, populate an object with the data and return it. There are only a set number of keys that can be present in the file. Since I am a beginner in python, I feel that my code to read the file is not that good
My code is something like this
ObjInstance = CustomClass()
fields = ['key1', 'key2', 'key3']
for field in fields:
for line in f:
if line.find(field) >= 0:
if pgn_field == 'key1':
objInstance.DataOne = get_value_using_re(line)
elif pgn_field == 'key2':
objInstance.DataTwo = get_value_using_re(line)
return objInstance;
The function "get_value_using_re" is very simple, it looks for a string in between the double quotes and returns it.
I fear that I will have multiple if elif statements and I don't know if this is the right way or not.
Am I doing the right thing here?
A:
A normal approach in Python would be something like:
for line in f:
mo = re.match(r'^(\S+)\s+"(.*?)"\s*$',line)
if not mo: continue
key, value = mo.groups()
setattr(objInstance, key, value)
If the key is not the right attribute name, in the last line line in lieu of key you might use something like translate.get(key, 'other') for some appropriate dict translate.
A:
I'd suggest looking at the YAML parser for python. It can conveniently read a file very similar to that and input it into a python dictionary. With the YAML parser:
import yaml
map = yaml.load(file(filename))
Then you can access it like a normal dictionary with map[key] returning value. The yaml files would look like this:
key1: 'value'
key2: 'value'
This does require that all the keys be unique.
| Parsing files with python | My input file is going to be something like this
key "value"
key "value"
... the above lines repeat
What I do is read the file contents, populate an object with the data and return it. There are only a set number of keys that can be present in the file. Since I am a beginner in python, I feel that my code to read the file is not that good
My code is something like this
ObjInstance = CustomClass()
fields = ['key1', 'key2', 'key3']
for field in fields:
for line in f:
if line.find(field) >= 0:
if pgn_field == 'key1':
objInstance.DataOne = get_value_using_re(line)
elif pgn_field == 'key2':
objInstance.DataTwo = get_value_using_re(line)
return objInstance;
The function "get_value_using_re" is very simple, it looks for a string in between the double quotes and returns it.
I fear that I will have multiple if elif statements and I don't know if this is the right way or not.
Am I doing the right thing here?
| [
"A normal approach in Python would be something like:\nfor line in f:\n mo = re.match(r'^(\\S+)\\s+\"(.*?)\"\\s*$',line)\n if not mo: continue\n key, value = mo.groups()\n setattr(objInstance, key, value)\n\nIf the key is not the right attribute name, in the last line line in lieu of key you might use something like translate.get(key, 'other') for some appropriate dict translate.\n",
"I'd suggest looking at the YAML parser for python. It can conveniently read a file very similar to that and input it into a python dictionary. With the YAML parser:\nimport yaml\nmap = yaml.load(file(filename))\n\nThen you can access it like a normal dictionary with map[key] returning value. The yaml files would look like this:\nkey1: 'value'\nkey2: 'value'\n\nThis does require that all the keys be unique.\n"
] | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0002792948_python.txt |
Q:
python: a way to get an exhaustive, sorted list of keys in a nested dictionary?
exhaustive:
- all keys in the dictionary, even if the keys are in a nested dictionary that is a value to a previous-level dictionary key.
sorted:
- this is to ensure the keys are always returned in the same order
The nesting is arbitrarily deep. A non-recursive algorithm is preferred.
level1 = {
'a' : 'aaaa',
'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },
'level2_2' : { 'z': 'zzzzzzz' }
}
Note: dictionary values can include lists (which can have dictionaries as elements), e.g.
tricky = {'category': [{'content': 'aaaaa'}, {'content': 'bbbbbb'}]}
A:
def _auxallkeys(aset, adict):
aset.update(adict)
for d in adict.itervalues():
if isinstance(d, dict):
_auxallkeys(aset, d)
def allkeys(adict):
aset = set()
_auxallkeys(aset, adict)
return sorted(aset)
is the obvious (recursive) solution. To eliminate recursion:
def allkeys(adict):
aset = set()
pending = [adict]
while pending:
d = pending.pop()
aset.update(d)
for dd in d.itervalues():
if isinstance(dd, dict):
pending.append(dd)
return sorted(aset)
since the order of processing of the various nested dicts does not matter for this purpose.
Edit: the OP comments whining that it doesn't work if a dict is not nested, but rather in a list (and I replied that it could also be in a tuple, an object with attributes per-instance or per-class [maybe a base class thereof], a shelf, and many other ways to hide dicts around the house;-). If the OP will deign to define precisely what he means by "nested" (obviously not the same meaning as ordinary mortals apply to the word in question), it will probably be easier to help him. Meanwhile, here's a version that covers lists (and tuples, but not generators, instances of many itertools classes, shelves, etc, etc);
def allkeys(adict):
aset = set()
pending = [adict]
pendlis = []
def do_seq(seq):
for dd in seq:
if isinstance(dd, dict):
pending.append(dd)
elif isinstance(dd, (list, tuple)):
pendlis.append(dd)
while pending or pendlis:
while pending:
d = pending.pop()
aset.update(d)
do_seq(d.itervalues())
while pendlis:
l = pendlis.pop()
do_seq(l)
return sorted(aset)
A:
A non-recursive method isn't obvious to me right now. The following works on your original example. Edit: It will now handle dicts within a list within a dict, at least the one within the tricky example cited in the comment to Alex Martelli's answer.
#!/usr/bin/env python
import types
def get_key_list(the_dict, key_list):
for k, v in (the_dict.iteritems()):
key_list.append(k)
if type(v) is types.DictType:
get_key_list(v, key_list)
if type(v) is types.ListType:
for lv in v:
if type(lv) is types.DictType:
get_key_list(lv, key_list)
return
level1 = {
'a' : 'aaaa',
'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },
'level2_2' : { 'z': 'zzzzzzz' }
}
tricky = {'category': [{'content': 'aaaaa'}, {'content': 'bbbbbb'}]}
key_list = []
get_key_list(level1, key_list)
key_list.sort()
print key_list
key_list = []
get_key_list(tricky, key_list)
key_list.sort()
print key_list
Output:
['a', 'b', 'c', 'd', 'level2_1', 'level2_2', 'level3', 'z']
['category', 'content', 'content']
A:
Here's a non-recursive solution which processes generators as well as lists, tuples and dicts and adds all successive keys if a key appears more than once:
def get_iterator(i):
if hasattr(i, 'next'):
# already an iterator - use it as-is!
return i
elif hasattr(i, '__iter__') and not isinstance(i, basestring):
# an iterable type that isn't a string
return iter(i)
else:
# Can't iterate most other types!
return None
def get_dict_keys(D):
LRtn = []
L = [(D, get_iterator(D))]
while 1:
if not L: break
cur, _iter = L[-1]
if _iter:
# Get the next item
try:
i = _iter.next()
except StopIteration:
del L[-1]
continue
if isinstance(cur, dict):
# Process a dict and all subitems
LRtn.append(i)
_iter = get_iterator(cur[i])
if _iter: L.append((cur[i], _iter))
else:
# Process generators, lists, tuples and all subitems
_iter = get_iterator(i)
if _iter: L.append((i, _iter))
# Sort and return
LRtn.sort()
return LRtn
D = {
'a' : 'aaaa',
'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd', 'e': 134, 'f': [{'blah': 553}]} },
'level2_2' : { 'z': 'zzzzzzz' },
'blah2': iter([{'blah3': None}]),
}
print get_dict_keys(D)
EDIT: Increased the speed a bit and made the code shorter.
A:
I also prefer a recursive approach...
#!/usr/bin/env python
def extract_all_keys(structure):
try:
list_of_keys = structure.keys()
for value in structure.values():
add_all_keys_in_value_to_list(value, list_of_keys)
except AttributeError:
list_of_keys = []
return list_of_keys.sort()
def add_all_keys_in_value_to_list(value, list_of_keys):
if isinstance(value, dict):
list_of_keys += extract_all_keys(value)
elif isinstance(value, (list, tuple)):
for element in value:
list_of_keys += extract_all_keys(element)
import unittest
class TestKeys(unittest.TestCase):
def given_a_structure_of(self, structure):
self.structure = structure
def when_keys_are_extracted(self):
self.list_of_keys = extract_all_keys(self.structure)
def testEmptyDict(self):
self.given_a_structure_of({})
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, [])
def testOneElement(self):
self.given_a_structure_of({'a': 'aaaa'})
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['a'])
def testTwoElementsSorted(self):
self.given_a_structure_of({
'z': 'zzzz',
'a': 'aaaa',
})
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['a', 'z'])
def testNestedElements(self):
self.given_a_structure_of({
'a': {'aaaa': 'A',},
'b': {'bbbb': 'B',},
})
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['a', 'aaaa', 'b', 'bbbb'])
def testDoublyNestedElements(self):
self.given_a_structure_of({
'level2': {'aaaa': 'A',
'level3': {'bbbb': 'B'}
}
})
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['aaaa', 'bbbb', 'level2', 'level3'])
def testNestedExampleOnStackOverflow(self):
level1 = {
'a' : 'aaaa',
'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },
'level2_2' : { 'z': 'zzzzzzz' }
}
self.given_a_structure_of(level1)
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['a', 'b', 'c', 'd', 'level2_1', 'level2_2', 'level3', 'z'])
def testListExampleOnStackOverflow(self):
tricky = {'category': [{'content': 'aaaaa'}, {'content': 'bbbbbb'}]}
self.given_a_structure_of(tricky)
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['category', 'content', 'content'])
def testTuplesTreatedLikeLists(self):
tricky_tuple = {'category': ({'content': 'aaaaa'}, {'content': 'bbbbbb'})}
self.given_a_structure_of(tricky_tuple)
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, ['category', 'content', 'content'])
def testCanHandleString(self):
self.given_a_structure_of('keys')
self.when_keys_are_extracted()
self.assertEquals(self.list_of_keys, [])
if __name__ == '__main__':
unittest.main()
A:
I think it is better to use a recursive method.
My code is in the following.
level1 = {
'a' : 'aaaa',
'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },
'level2_2' : { 'z': 'zzzzzzz' }
}
all_keys=[] # a global list to store all the keys in level1
def depth ( dict ):
for k in dict:
if type(dict[k]) == type(dict): #judge the type of elements in dictionary
depth(dict[k]) # recursive
else:
all_keys.append(k)
depth(level1)
print all_keys
| python: a way to get an exhaustive, sorted list of keys in a nested dictionary? | exhaustive:
- all keys in the dictionary, even if the keys are in a nested dictionary that is a value to a previous-level dictionary key.
sorted:
- this is to ensure the keys are always returned in the same order
The nesting is arbitrarily deep. A non-recursive algorithm is preferred.
level1 = {
'a' : 'aaaa',
'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },
'level2_2' : { 'z': 'zzzzzzz' }
}
Note: dictionary values can include lists (which can have dictionaries as elements), e.g.
tricky = {'category': [{'content': 'aaaaa'}, {'content': 'bbbbbb'}]}
| [
"def _auxallkeys(aset, adict):\n aset.update(adict)\n for d in adict.itervalues():\n if isinstance(d, dict):\n _auxallkeys(aset, d)\n\ndef allkeys(adict):\n aset = set()\n _auxallkeys(aset, adict)\n return sorted(aset)\n\nis the obvious (recursive) solution. To eliminate recursion:\ndef allkeys(adict):\n aset = set()\n pending = [adict]\n while pending:\n d = pending.pop()\n aset.update(d)\n for dd in d.itervalues():\n if isinstance(dd, dict):\n pending.append(dd)\n return sorted(aset)\n\nsince the order of processing of the various nested dicts does not matter for this purpose.\nEdit: the OP comments whining that it doesn't work if a dict is not nested, but rather in a list (and I replied that it could also be in a tuple, an object with attributes per-instance or per-class [maybe a base class thereof], a shelf, and many other ways to hide dicts around the house;-). If the OP will deign to define precisely what he means by \"nested\" (obviously not the same meaning as ordinary mortals apply to the word in question), it will probably be easier to help him. Meanwhile, here's a version that covers lists (and tuples, but not generators, instances of many itertools classes, shelves, etc, etc);\ndef allkeys(adict):\n aset = set()\n pending = [adict]\n pendlis = []\n\n def do_seq(seq):\n for dd in seq:\n if isinstance(dd, dict):\n pending.append(dd)\n elif isinstance(dd, (list, tuple)):\n pendlis.append(dd)\n\n while pending or pendlis:\n while pending:\n d = pending.pop()\n aset.update(d)\n do_seq(d.itervalues())\n while pendlis:\n l = pendlis.pop()\n do_seq(l)\n\n return sorted(aset)\n\n",
"A non-recursive method isn't obvious to me right now. The following works on your original example. Edit: It will now handle dicts within a list within a dict, at least the one within the tricky example cited in the comment to Alex Martelli's answer.\n#!/usr/bin/env python\nimport types\n\ndef get_key_list(the_dict, key_list):\n for k, v in (the_dict.iteritems()):\n key_list.append(k)\n if type(v) is types.DictType:\n get_key_list(v, key_list)\n if type(v) is types.ListType:\n for lv in v:\n if type(lv) is types.DictType:\n get_key_list(lv, key_list)\n return\n\nlevel1 = {\n 'a' : 'aaaa',\n 'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },\n 'level2_2' : { 'z': 'zzzzzzz' }\n}\ntricky = {'category': [{'content': 'aaaaa'}, {'content': 'bbbbbb'}]}\n\nkey_list = []\nget_key_list(level1, key_list)\nkey_list.sort()\nprint key_list\n\nkey_list = []\nget_key_list(tricky, key_list)\nkey_list.sort()\nprint key_list\n\nOutput: \n\n['a', 'b', 'c', 'd', 'level2_1', 'level2_2', 'level3', 'z']\n ['category', 'content', 'content']\n\n",
"Here's a non-recursive solution which processes generators as well as lists, tuples and dicts and adds all successive keys if a key appears more than once:\ndef get_iterator(i):\n if hasattr(i, 'next'):\n # already an iterator - use it as-is!\n return i\n elif hasattr(i, '__iter__') and not isinstance(i, basestring):\n # an iterable type that isn't a string\n return iter(i)\n else: \n # Can't iterate most other types!\n return None\n\ndef get_dict_keys(D):\n LRtn = []\n L = [(D, get_iterator(D))]\n while 1:\n if not L: break\n cur, _iter = L[-1]\n\n if _iter:\n # Get the next item\n try: \n i = _iter.next()\n except StopIteration:\n del L[-1]\n continue\n\n if isinstance(cur, dict): \n # Process a dict and all subitems\n LRtn.append(i)\n\n _iter = get_iterator(cur[i])\n if _iter: L.append((cur[i], _iter))\n else:\n # Process generators, lists, tuples and all subitems\n _iter = get_iterator(i)\n if _iter: L.append((i, _iter))\n\n # Sort and return\n LRtn.sort()\n return LRtn\n\nD = {\n 'a' : 'aaaa',\n 'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd', 'e': 134, 'f': [{'blah': 553}]} },\n 'level2_2' : { 'z': 'zzzzzzz' },\n 'blah2': iter([{'blah3': None}]),\n}\n\nprint get_dict_keys(D)\n\nEDIT: Increased the speed a bit and made the code shorter.\n",
"I also prefer a recursive approach...\n#!/usr/bin/env python\n\ndef extract_all_keys(structure):\n try:\n list_of_keys = structure.keys()\n for value in structure.values():\n add_all_keys_in_value_to_list(value, list_of_keys)\n except AttributeError:\n list_of_keys = []\n return list_of_keys.sort()\n\n\ndef add_all_keys_in_value_to_list(value, list_of_keys):\n if isinstance(value, dict):\n list_of_keys += extract_all_keys(value)\n elif isinstance(value, (list, tuple)):\n for element in value:\n list_of_keys += extract_all_keys(element)\n\n\nimport unittest\n\nclass TestKeys(unittest.TestCase):\n\n def given_a_structure_of(self, structure):\n self.structure = structure\n\n\n def when_keys_are_extracted(self):\n self.list_of_keys = extract_all_keys(self.structure)\n\n\n def testEmptyDict(self):\n self.given_a_structure_of({})\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, [])\n\n\n def testOneElement(self):\n self.given_a_structure_of({'a': 'aaaa'})\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['a'])\n\n\n def testTwoElementsSorted(self):\n self.given_a_structure_of({\n 'z': 'zzzz',\n 'a': 'aaaa',\n })\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['a', 'z'])\n\n\n def testNestedElements(self):\n self.given_a_structure_of({\n 'a': {'aaaa': 'A',},\n 'b': {'bbbb': 'B',},\n })\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['a', 'aaaa', 'b', 'bbbb'])\n\n\n def testDoublyNestedElements(self):\n self.given_a_structure_of({\n 'level2': {'aaaa': 'A',\n 'level3': {'bbbb': 'B'}\n }\n })\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['aaaa', 'bbbb', 'level2', 'level3'])\n\n\n def testNestedExampleOnStackOverflow(self):\n level1 = {\n 'a' : 'aaaa',\n 'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },\n 'level2_2' : { 'z': 'zzzzzzz' }\n }\n self.given_a_structure_of(level1)\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['a', 'b', 'c', 'd', 'level2_1', 'level2_2', 'level3', 'z'])\n\n\n def testListExampleOnStackOverflow(self):\n tricky = {'category': [{'content': 'aaaaa'}, {'content': 'bbbbbb'}]}\n self.given_a_structure_of(tricky)\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['category', 'content', 'content'])\n\n\n def testTuplesTreatedLikeLists(self):\n tricky_tuple = {'category': ({'content': 'aaaaa'}, {'content': 'bbbbbb'})}\n self.given_a_structure_of(tricky_tuple)\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, ['category', 'content', 'content'])\n\n\n def testCanHandleString(self):\n self.given_a_structure_of('keys')\n self.when_keys_are_extracted()\n self.assertEquals(self.list_of_keys, [])\n\nif __name__ == '__main__':\n unittest.main()\n\n",
"I think it is better to use a recursive method.\nMy code is in the following.\nlevel1 = {\n 'a' : 'aaaa',\n 'level2_1' : {'b': 'bbbbb', 'level3': {'c': 'cccc', 'd': 'dddddd'} },\n 'level2_2' : { 'z': 'zzzzzzz' }\n}\n\nall_keys=[] # a global list to store all the keys in level1\n\ndef depth ( dict ):\n for k in dict:\n if type(dict[k]) == type(dict): #judge the type of elements in dictionary \n depth(dict[k]) # recursive \n else:\n all_keys.append(k)\n\ndepth(level1)\n\nprint all_keys\n\n"
] | [
6,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002792641_dictionary_python.txt |
Q:
How can I turn a single element in a list into multiple elements using Python?
I have a list of elements, and each element consists of four separate values that are separated by tabs:
['A\tB\tC\tD', 'Q\tW\tE\tR', etc.]
What I want is to create a larger list without the tabs, so that each value is a separate element:
['A', 'B', 'C', 'D', 'Q', 'W', 'E', 'R', etc.]
How can I do that in Python? I need it for my coursework, due tonight (midnight GMT) and I'm completely stumped.
A:
All at once:
'\t'.join(['A\tB\tC\tD', 'Q\tW\tE\tR']).split('\t')
One at a time:
[c for s in ['A\tB\tC\tD', 'Q\tW\tE\tR'] for c in s.split('\t')]
Or if all elements are single letters:
[c for s in ['A\tB\tC\tD', 'Q\tW\tE\tR'] for c in s[::2]]
If there could be quoted tabs then:
import csv
rows = csv.reader(['A\t"\t"\tB\tC\tD', 'Q\tW\tE\tR'], delimiter='\t')
[c for s in rows for c in s] # or list(itertools.chain.from_iterable(rows))
A:
Homework question?
t = ['A\tB\tC\tD', 'Q\tW\tE\tR']
sum((x.split('\t') for x in t),[])
A:
This should work:
t = ['A\tB\tC\tD', 'Q\tW\tE\tR']
t = reduce(lambda x, y: x + y, map(str.split,t))
| How can I turn a single element in a list into multiple elements using Python? | I have a list of elements, and each element consists of four separate values that are separated by tabs:
['A\tB\tC\tD', 'Q\tW\tE\tR', etc.]
What I want is to create a larger list without the tabs, so that each value is a separate element:
['A', 'B', 'C', 'D', 'Q', 'W', 'E', 'R', etc.]
How can I do that in Python? I need it for my coursework, due tonight (midnight GMT) and I'm completely stumped.
| [
"All at once:\n'\\t'.join(['A\\tB\\tC\\tD', 'Q\\tW\\tE\\tR']).split('\\t')\n\nOne at a time:\n[c for s in ['A\\tB\\tC\\tD', 'Q\\tW\\tE\\tR'] for c in s.split('\\t')]\n\nOr if all elements are single letters:\n[c for s in ['A\\tB\\tC\\tD', 'Q\\tW\\tE\\tR'] for c in s[::2]]\n\nIf there could be quoted tabs then:\nimport csv\nrows = csv.reader(['A\\t\"\\t\"\\tB\\tC\\tD', 'Q\\tW\\tE\\tR'], delimiter='\\t')\n[c for s in rows for c in s] # or list(itertools.chain.from_iterable(rows))\n\n",
"Homework question? \nt = ['A\\tB\\tC\\tD', 'Q\\tW\\tE\\tR']\nsum((x.split('\\t') for x in t),[])\n\n",
"This should work:\nt = ['A\\tB\\tC\\tD', 'Q\\tW\\tE\\tR']\n\nt = reduce(lambda x, y: x + y, map(str.split,t))\n\n"
] | [
5,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002790470_list_python.txt |
Q:
Why does PEP-8 specify a maximum line length of 79 characters?
Why in this millennium should Python PEP-8 specify a maximum line length of 79 characters?
Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator.
Are there any (legitimately) good reasons for adhering to 79 characters in this age?
A:
Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.
A:
Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.
Readability is also one of the reasons for enforced line indentation.
A:
I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.
As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.
I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.
I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.
I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.
A:
I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.
A:
Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.
A:
Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember). If the lines are any longer, I have trouble reading the files, even when using word wrap. Needless to say, I hate dealing with other people's code as they love long lines.
A:
Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.
A:
I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.
The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.
A:
because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).
| Why does PEP-8 specify a maximum line length of 79 characters? | Why in this millennium should Python PEP-8 specify a maximum line length of 79 characters?
Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator.
Are there any (legitimately) good reasons for adhering to 79 characters in this age?
| [
"Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.\n",
"Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.\nReadability is also one of the reasons for enforced line indentation.\n",
"I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.\nAs a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.\nI find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.\nI say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.\nI write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.\n",
"I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.\n",
"Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.\n",
"Here's why I like the 80-character with: at work I use Vim and work on two files at a time on a monitor running at, I think, 1680x1040 (I can never remember). If the lines are any longer, I have trouble reading the files, even when using word wrap. Needless to say, I hate dealing with other people's code as they love long lines.\n",
"Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.\n",
"I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line. \nThe style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.\n",
"because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).\n"
] | [
170,
130,
57,
44,
20,
15,
6,
3,
0
] | [] | [] | [
"coding_style",
"pep8",
"python"
] | stackoverflow_0000088942_coding_style_pep8_python.txt |
Q:
List comprehension for series of deltas
How would you write a list comprehension in python to generate a series of n-1 deltas between n items in an ordered list?
Example:
L = [5,9,2,1,7]
RES = [5-9,9-2,2-1,1-7] = [4,7,1,6] # absolute values
A:
RES = [abs(L[i]-L[i+1]) for i in range(len(L)-1)]
A:
The recipes section of the itertools documentation includes source code for a function called pairwise that you can use for this purpose:
from itertools import *
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
b.next()
return izip(a, b)
You can copy and paste this into your file. With this function defined it is quite simple to do what you want:
l = [5, 9, 2, 1, 7]
print [abs(a-b) for a,b in pairwise(l)]
Result
[4, 7, 1, 6]
A:
Just figured it out:
[abs(x-y) for x,y in zip(L[:-1], L[1:])]
| List comprehension for series of deltas | How would you write a list comprehension in python to generate a series of n-1 deltas between n items in an ordered list?
Example:
L = [5,9,2,1,7]
RES = [5-9,9-2,2-1,1-7] = [4,7,1,6] # absolute values
| [
"RES = [abs(L[i]-L[i+1]) for i in range(len(L)-1)]\n\n",
"The recipes section of the itertools documentation includes source code for a function called pairwise that you can use for this purpose:\nfrom itertools import *\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n b.next()\n return izip(a, b)\n\nYou can copy and paste this into your file. With this function defined it is quite simple to do what you want:\nl = [5, 9, 2, 1, 7]\nprint [abs(a-b) for a,b in pairwise(l)]\n\nResult\n[4, 7, 1, 6] \n\n",
"Just figured it out:\n[abs(x-y) for x,y in zip(L[:-1], L[1:])]\n\n"
] | [
5,
4,
2
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0002793753_list_comprehension_python.txt |
Q:
Purge complete Python installation on OS X
I’m working on a recently-upgraded OS X Snow Leopard and MacPorts and I’m running into problems at every corner.
The first problem is the sheer number of installed Python versions: altogether, there are four:
2.5, 2.6 and 3.0 in /Library/Frameworks/Python.framework
2.6 in /opt/local/Library/Frameworks/Python.framework/ (MacPorts installation)
So there are at least two useless/redundant versions: 2.5 and the redundant 2.6.
Additionally, the pre-installed Python is giving me severe problems because some of the pre-installed libraries (in particular, scipy, numpy and matplotlib) don’t work properly.
I am sorely tempted to purge the complete /Library/Frameworks/Python.framework path, as well as the MacPorts Python installation. After that, I’ll start from a clean slate by installing a properly configured Python, e.g. that from Enthought.
Am I running headlong into trouble? Or is this a sane undertaking?
(In particular, I need a working Python in the next few days and if I end up with a non-working Python this would be a catastrophe of medium proportions. On the other hand, some features I need from matplotlib aren’t working now.)
A:
Macports only installs into /opt/local (for python and related).
Apple's python uses /Library/Frameworks/Python.framework/2.x 2.5 from Leopard and 2.6 for Snow Leopard but just puts a site-packages install in there on install
Thus I think you can get rid of /Library/Frameworks/Python.framework
I would the use the macports python and install numpy etc through that as I find that the easiest way for installing packages that have C dependencies
Alternatives are to install python for python.org and install numpy etc from that
| Purge complete Python installation on OS X | I’m working on a recently-upgraded OS X Snow Leopard and MacPorts and I’m running into problems at every corner.
The first problem is the sheer number of installed Python versions: altogether, there are four:
2.5, 2.6 and 3.0 in /Library/Frameworks/Python.framework
2.6 in /opt/local/Library/Frameworks/Python.framework/ (MacPorts installation)
So there are at least two useless/redundant versions: 2.5 and the redundant 2.6.
Additionally, the pre-installed Python is giving me severe problems because some of the pre-installed libraries (in particular, scipy, numpy and matplotlib) don’t work properly.
I am sorely tempted to purge the complete /Library/Frameworks/Python.framework path, as well as the MacPorts Python installation. After that, I’ll start from a clean slate by installing a properly configured Python, e.g. that from Enthought.
Am I running headlong into trouble? Or is this a sane undertaking?
(In particular, I need a working Python in the next few days and if I end up with a non-working Python this would be a catastrophe of medium proportions. On the other hand, some features I need from matplotlib aren’t working now.)
| [
"Macports only installs into /opt/local (for python and related).\nApple's python uses /Library/Frameworks/Python.framework/2.x 2.5 from Leopard and 2.6 for Snow Leopard but just puts a site-packages install in there on install\nThus I think you can get rid of /Library/Frameworks/Python.framework\nI would the use the macports python and install numpy etc through that as I find that the easiest way for installing packages that have C dependencies\nAlternatives are to install python for python.org and install numpy etc from that\n"
] | [
2
] | [] | [] | [
"macos",
"osx_snow_leopard",
"python"
] | stackoverflow_0002793747_macos_osx_snow_leopard_python.txt |
Q:
Can I db.put models without db.getting them first?
I tried to do something like
ss = Screenshot(key=db.Key.from_path('myapp_screenshot', 123), name='flowers')
db.put([ss, ...])
It seems to work on my dev_appserver, but on live I get this traceback:
05-07 09:50PM 19.964 File "/base/data/home/apps/quixeydev3/12.341796548761906563/common/appenginepatch/appenginepatcher/patch.py",
line 600, in put
E 05-07 09:50PM 19.964 result = old_db_put(models, *args, **kwargs)
GAE bug is actually extremely minor. It seems to be due to the fact that I called something l
E 05-07 09:50PM 19.964 File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/init.py",
line 1278, in put
E 05-07 09:50PM 19.964 keys = datastore.Put(entities, rpc=rpc)
E 05-07 09:50PM 19.964 File "/base/python_runtime/python_lib/versions/1/google/appengine/api/datastore.py",
line 284, in Put
E 05-07 09:50PM 19.965 raise _ToDatastoreError(err)
E 05-07 09:50PM 19.965 InternalError: the new entity or index
you tried to insert already exists
I happen to know just the ID of an existing Screenshot entity I want to update; that's why I was manually constructing its key. Am I doing it wrong?
Update: I filed this as Google App Engine issue 3209.
Update 2: It looks like the ike db.put([ss, ss2, ss]), i.e. the call just fails when the list references the same model twice.
Update 3: OK, I think I finally know what's going on here, and I'm updating this question because right now it's the only Google result for "the new entity or index you tried to insert already exists".
This InternalError seems to arise when the Datastore attempts two writes of a BigTable row for the same entity key, within the same Remote Procedure Call. This can happen if you manually give two entities the same key, or if you put() two new entities without specifying a key, and the same ID gets allocated to both entities in parallel. In the latter case, the solution is to use db.allocate_ids().
A:
This is a bug - you should be able to do exactly what you describe. As a workaround until we can fix it, using key names (even if they're numeric) instead of IDs should work fine.
A:
I am fairly certain you can just ss.save()
Basically your db entity already exists so you just save changes to it, db.put is used for adding a new entity. Hope that helps.
Apparently this is a bug. I did more research on it and found some reference to Entity groups, which allow multiple entity modifications in a single transaction, but they state that they do not not have a significant impact on the speed of queries.
A:
If you want to update just one entity, you can use Model.put() instead of db.put(). This will create the entity if it doesn't already exist, or update it if it does.
So you would do ss.put().
| Can I db.put models without db.getting them first? | I tried to do something like
ss = Screenshot(key=db.Key.from_path('myapp_screenshot', 123), name='flowers')
db.put([ss, ...])
It seems to work on my dev_appserver, but on live I get this traceback:
05-07 09:50PM 19.964 File "/base/data/home/apps/quixeydev3/12.341796548761906563/common/appenginepatch/appenginepatcher/patch.py",
line 600, in put
E 05-07 09:50PM 19.964 result = old_db_put(models, *args, **kwargs)
GAE bug is actually extremely minor. It seems to be due to the fact that I called something l
E 05-07 09:50PM 19.964 File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/init.py",
line 1278, in put
E 05-07 09:50PM 19.964 keys = datastore.Put(entities, rpc=rpc)
E 05-07 09:50PM 19.964 File "/base/python_runtime/python_lib/versions/1/google/appengine/api/datastore.py",
line 284, in Put
E 05-07 09:50PM 19.965 raise _ToDatastoreError(err)
E 05-07 09:50PM 19.965 InternalError: the new entity or index
you tried to insert already exists
I happen to know just the ID of an existing Screenshot entity I want to update; that's why I was manually constructing its key. Am I doing it wrong?
Update: I filed this as Google App Engine issue 3209.
Update 2: It looks like the ike db.put([ss, ss2, ss]), i.e. the call just fails when the list references the same model twice.
Update 3: OK, I think I finally know what's going on here, and I'm updating this question because right now it's the only Google result for "the new entity or index you tried to insert already exists".
This InternalError seems to arise when the Datastore attempts two writes of a BigTable row for the same entity key, within the same Remote Procedure Call. This can happen if you manually give two entities the same key, or if you put() two new entities without specifying a key, and the same ID gets allocated to both entities in parallel. In the latter case, the solution is to use db.allocate_ids().
| [
"This is a bug - you should be able to do exactly what you describe. As a workaround until we can fix it, using key names (even if they're numeric) instead of IDs should work fine.\n",
"I am fairly certain you can just ss.save()\nBasically your db entity already exists so you just save changes to it, db.put is used for adding a new entity. Hope that helps.\nApparently this is a bug. I did more research on it and found some reference to Entity groups, which allow multiple entity modifications in a single transaction, but they state that they do not not have a significant impact on the speed of queries.\n",
"If you want to update just one entity, you can use Model.put() instead of db.put(). This will create the entity if it doesn't already exist, or update it if it does.\nSo you would do ss.put().\n"
] | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002792999_google_app_engine_python.txt |
Q:
Python code formatting
In response to another question of mine, someone suggested that I avoid long lines in the code and to use PEP-8 rules when writing Python code. One of the PEP-8 rules suggested avoiding lines which are longer than 80 characters. I changed a lot of my code to comply with this requirement without any problems. However, changing the following line in the manner shown below breaks the code. Any ideas why? Does it have to do with the fact that what follows return command has to be in a single line?
The line longer that 80 characters:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
The line changed by using Enter key and Spaces as necessary:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg +
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
A:
A multiline string would be more readable:
def __str__(self):
return '''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)
To maintain visually meaningful indentation levels, use textwrap.dedent:
import textwrap
def __str__(self):
return textwrap.dedent('''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price))
A:
You can solve the problem by putting the expression in parenthesis:
def __str__(self):
return ("Car Type \n"+"mpg: %.1f \n" % self.mpg +
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price))
However, I'd consider writing it more like this: (code untested)
def __str__(self):
return """\
Car Type
mpg: %(mpg).1f
hp: %(hp).2f
pc: %(pc)i
unit cost: $%(cost).2f
price: $%(price).2f """ % self.__dict__
A:
Python doesn't let you end a line inside an expression like that; the simplest workaround is to end the line with a backslash.
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg + \
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + \
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
In this case, the backslash must be the last character on the line. Essentially, it means "ignore the fact that there's a newline here". Or in other words, you're escaping the newline, since it would normally be a significant break.
You can escape an otherwise significant newline at any time with a backslash. It would be silly, but you could even do
def foo():
return \
1
so that foo() would return 1. If you didn't have the backslash there, the 1 by itself would cause a syntax error.
A:
It require a little extra setup, but a data-driven approach (with a good dose of vertical alignment) is easy to grok and modify as a project evolves. And it indirectly eliminates the problem of long lines of code.
def __str__(self):
dd = (
("Car Type %s", ''),
(" mpg: %.1f", self.mpg),
(" hp: %.2f", self.hp),
(" pc: %i", self.pc),
(" unit cost: $%.2f", self.cost),
(" price: $%.2f", self.price),
)
fmt = ''.join("%s\n" % t[0] for t in dd)
return fmt % tuple(t[1] for t in dd)
| Python code formatting | In response to another question of mine, someone suggested that I avoid long lines in the code and to use PEP-8 rules when writing Python code. One of the PEP-8 rules suggested avoiding lines which are longer than 80 characters. I changed a lot of my code to comply with this requirement without any problems. However, changing the following line in the manner shown below breaks the code. Any ideas why? Does it have to do with the fact that what follows return command has to be in a single line?
The line longer that 80 characters:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
The line changed by using Enter key and Spaces as necessary:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg +
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
| [
"A multiline string would be more readable:\ndef __str__(self):\n return '''\\\nCar Type\nmpg: %.1f\nhp: %.2f \npc: %i \nunit cost: $%.2f\nprice: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)\n\nTo maintain visually meaningful indentation levels, use textwrap.dedent:\nimport textwrap\ndef __str__(self):\n return textwrap.dedent('''\\\n Car Type\n mpg: %.1f\n hp: %.2f\n pc: %i\n unit cost: $%.2f\n price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price))\n\n",
"You can solve the problem by putting the expression in parenthesis:\ndef __str__(self):\n return (\"Car Type \\n\"+\"mpg: %.1f \\n\" % self.mpg + \n \"hp: %.2f \\n\" %(self.hp) + \"pc: %i \\n\" %self.pc +\n \"unit cost: $%.2f \\n\" %(self.cost) + \"price: $%.2f \"%(self.price))\n\nHowever, I'd consider writing it more like this: (code untested)\ndef __str__(self):\n return \"\"\"\\\nCar Type \nmpg: %(mpg).1f \nhp: %(hp).2f\npc: %(pc)i \nunit cost: $%(cost).2f \nprice: $%(price).2f \"\"\" % self.__dict__\n\n",
"Python doesn't let you end a line inside an expression like that; the simplest workaround is to end the line with a backslash.\ndef __str__(self):\n return \"Car Type \\n\"+\"mpg: %.1f \\n\" % self.mpg + \\\n \"hp: %.2f \\n\" %(self.hp) + \"pc: %i \\n\" %self.pc + \\\n \"unit cost: $%.2f \\n\" %(self.cost) + \"price: $%.2f \"%(self.price)\n\nIn this case, the backslash must be the last character on the line. Essentially, it means \"ignore the fact that there's a newline here\". Or in other words, you're escaping the newline, since it would normally be a significant break.\nYou can escape an otherwise significant newline at any time with a backslash. It would be silly, but you could even do \ndef foo():\n return \\\n 1\n\nso that foo() would return 1. If you didn't have the backslash there, the 1 by itself would cause a syntax error.\n",
"It require a little extra setup, but a data-driven approach (with a good dose of vertical alignment) is easy to grok and modify as a project evolves. And it indirectly eliminates the problem of long lines of code.\ndef __str__(self):\n dd = (\n (\"Car Type %s\", ''),\n (\" mpg: %.1f\", self.mpg),\n (\" hp: %.2f\", self.hp),\n (\" pc: %i\", self.pc),\n (\" unit cost: $%.2f\", self.cost),\n (\" price: $%.2f\", self.price),\n )\n\n fmt = ''.join(\"%s\\n\" % t[0] for t in dd)\n return fmt % tuple(t[1] for t in dd)\n\n"
] | [
13,
6,
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0002792887_python.txt |
Q:
Load resources? - wxPython / Python
I am using wxPython and Py2exe to create my application and my only problem is loading for example bitmaps.
Ok so lets say I want to add an image to my application, and thats fairly easy using wxPython, and lets say it is on the same directory of my .py so for example:
image = wx.StaticBitmap(self, -1, wx.Bitmap('image.bmp')
Now, this works obviously fine, problem is when I convert to Py2exe, I would like to use the resources from the dlls that I included in the Py2Exe compilation.
So basically what I want to do is to instead of including the images on the same folder as my application in order to work, I would like to use it from the resources so people won't see the images on the folder.
A:
Have a look at img2py. This tool is designed to convert images into python files you can import and package using py2exe.
| Load resources? - wxPython / Python | I am using wxPython and Py2exe to create my application and my only problem is loading for example bitmaps.
Ok so lets say I want to add an image to my application, and thats fairly easy using wxPython, and lets say it is on the same directory of my .py so for example:
image = wx.StaticBitmap(self, -1, wx.Bitmap('image.bmp')
Now, this works obviously fine, problem is when I convert to Py2exe, I would like to use the resources from the dlls that I included in the Py2Exe compilation.
So basically what I want to do is to instead of including the images on the same folder as my application in order to work, I would like to use it from the resources so people won't see the images on the folder.
| [
"Have a look at img2py. This tool is designed to convert images into python files you can import and package using py2exe.\n"
] | [
4
] | [] | [] | [
"python",
"resources",
"wxpython"
] | stackoverflow_0002792463_python_resources_wxpython.txt |
Q:
how to make the StringListProperty's value unique in google-app-engine
the next code is error:
class Thread(db.Model):
members = db.StringListProperty(unique =True)
thanks
A:
There is no unique parameter for the constructor of a property. This is why your code crashes.
There is unfortunately no built-in mechanism on the datastore level. You will need to implement that in your code.
A:
You can make a single property unique to a kind and entity group by making it the entity's key_name. The datastore will not enforce uniqueness for you in any other way.
| how to make the StringListProperty's value unique in google-app-engine | the next code is error:
class Thread(db.Model):
members = db.StringListProperty(unique =True)
thanks
| [
"There is no unique parameter for the constructor of a property. This is why your code crashes.\nThere is unfortunately no built-in mechanism on the datastore level. You will need to implement that in your code.\n",
"You can make a single property unique to a kind and entity group by making it the entity's key_name. The datastore will not enforce uniqueness for you in any other way.\n"
] | [
3,
1
] | [] | [] | [
"google_app_engine",
"python",
"unique"
] | stackoverflow_0002793294_google_app_engine_python_unique.txt |
Q:
Duplicate an AppEngine Query object to create variations of a filter without affecting the base query
In my AppEngine project I have a need to use a certain filter as a base then apply various different extra filters to the end, retrieving the different result sets separately. e.g.:
base_query = MyModel.all().filter('mainfilter', 123)
Then I need to use the results of various sub queries separately:
subquery1 = basequery.filter('subfilter1', 'xyz')
#Do something with subquery1 results here
subquery2 = basequery.filter('subfilter2', 'abc')
#Do something with subquery2 results here
Unfortunately 'filter()' affects the state of the basequery Query instance, rather than just returning a modified version. Is there any way to duplicate the Query object and use it as a base? Is there perhaps a standard Python way of duping an object that could be used?
The extra filters are actually applied by the results of different forms dynamically within a wizard, and they use the 'running total' of the query in their branch to assess whether to ask further questions.
Obviously I could pass around a rudimentary stack of filter criteria, but I'd rather use the Query itself if possible, as it adds simplicity and elegance to the solution.
A:
There's no officially approved (Eg, not likely to break) way to do this. Simply creating the query afresh from the parameters when you need it is your best option.
A:
As Nick has said, you better create the query again, but you can still avoid repeating yourself. A good way to do that would be like this:
#inside a request handler
def create_base_query():
return MyModel.all().filter('mainfilter', 123)
subquery1 = create_base_query().filter('subfilter1', 'xyz')
#Do something with subquery1 results here
subquery2 = create_base_query().filter('subfilter2', 'abc')
#Do something with subquery2 results here
| Duplicate an AppEngine Query object to create variations of a filter without affecting the base query | In my AppEngine project I have a need to use a certain filter as a base then apply various different extra filters to the end, retrieving the different result sets separately. e.g.:
base_query = MyModel.all().filter('mainfilter', 123)
Then I need to use the results of various sub queries separately:
subquery1 = basequery.filter('subfilter1', 'xyz')
#Do something with subquery1 results here
subquery2 = basequery.filter('subfilter2', 'abc')
#Do something with subquery2 results here
Unfortunately 'filter()' affects the state of the basequery Query instance, rather than just returning a modified version. Is there any way to duplicate the Query object and use it as a base? Is there perhaps a standard Python way of duping an object that could be used?
The extra filters are actually applied by the results of different forms dynamically within a wizard, and they use the 'running total' of the query in their branch to assess whether to ask further questions.
Obviously I could pass around a rudimentary stack of filter criteria, but I'd rather use the Query itself if possible, as it adds simplicity and elegance to the solution.
| [
"There's no officially approved (Eg, not likely to break) way to do this. Simply creating the query afresh from the parameters when you need it is your best option.\n",
"As Nick has said, you better create the query again, but you can still avoid repeating yourself. A good way to do that would be like this:\n#inside a request handler\n\ndef create_base_query():\n return MyModel.all().filter('mainfilter', 123)\n\nsubquery1 = create_base_query().filter('subfilter1', 'xyz')\n#Do something with subquery1 results here\n\nsubquery2 = create_base_query().filter('subfilter2', 'abc')\n#Do something with subquery2 results here\n\n"
] | [
2,
2
] | [] | [] | [
"filtering",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002793734_filtering_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I use Python to make a HTTPS request to this? and get the ACCESS_TOKN back?
https://graph.facebook.com/
I need to make an HTTPS request to that. And then get the params back. How to do that?
A:
Use libhttp2:
import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("https://graph.facebook.com/", "GET")
>>> import httplib2
>>> h = httplib2.Http(".cache")
>>> resp, content = h.request("https://graph.facebook.com/", "GET")
>>> print resp
{'status': '200', 'content-length': '26244', 'content-location': 'http://developers.facebook.com/docs/api', 'transfer-encoding': 'chunked', 'set-cookie': 'PHPSESSID=d3cc7702c0fa0ea30eb9fd82cd93aa10; path=/, datr=1273298829-77768393a90862aba5e814235278103be75902e4150eea9368624; expires=Mon, 07-May-2012 06:07:09 GMT; path=/; domain=.facebook.com', 'expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'server': 'Apache/1.3.41.fb2', 'connection': 'close', '-content-encoding': 'gzip', 'pragma': 'no-cache', 'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'date': 'Sat, 08 May 2010 06:07:09 GMT', 'p3p': 'CP="DSP LAW"', 'content-type': 'text/html; charset=utf-8'}
A:
import urllib2
r = urllib2.urlopen('https://graph.facebook.com')
print r.info()
html = r.read()
| How do I use Python to make a HTTPS request to this? and get the ACCESS_TOKN back? | https://graph.facebook.com/
I need to make an HTTPS request to that. And then get the params back. How to do that?
| [
"Use libhttp2:\nimport httplib2\nh = httplib2.Http(\".cache\")\nresp, content = h.request(\"https://graph.facebook.com/\", \"GET\")\n\n\n>>> import httplib2\n>>> h = httplib2.Http(\".cache\")\n>>> resp, content = h.request(\"https://graph.facebook.com/\", \"GET\")\n>>> print resp\n{'status': '200', 'content-length': '26244', 'content-location': 'http://developers.facebook.com/docs/api', 'transfer-encoding': 'chunked', 'set-cookie': 'PHPSESSID=d3cc7702c0fa0ea30eb9fd82cd93aa10; path=/, datr=1273298829-77768393a90862aba5e814235278103be75902e4150eea9368624; expires=Mon, 07-May-2012 06:07:09 GMT; path=/; domain=.facebook.com', 'expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'server': 'Apache/1.3.41.fb2', 'connection': 'close', '-content-encoding': 'gzip', 'pragma': 'no-cache', 'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'date': 'Sat, 08 May 2010 06:07:09 GMT', 'p3p': 'CP=\"DSP LAW\"', 'content-type': 'text/html; charset=utf-8'}\n\n",
"import urllib2\n\nr = urllib2.urlopen('https://graph.facebook.com')\nprint r.info()\nhtml = r.read()\n\n"
] | [
0,
0
] | [] | [] | [
"http",
"https",
"python",
"url"
] | stackoverflow_0002793113_http_https_python_url.txt |
Q:
Python Array problem
I have an array that I have to add a new value to array value. I am new to arrays.
how do I loop thru the array and add to the value in the existing array.
A:
>>> print [x+2 for x in [1,2,3]]
[3, 4, 5]
>>>
Learn about Python lists and list comprehensions
A:
a = [2, 3, 4]
for i in range(0, len(a)):
a[i] += 3
print a #prints [5, 6, 7]
A:
If you are working with arrays and need to do some math I would definitely recommend you numpy. Numpy was made for this purpose. Another hint (to all what I know): try to avoid loops where you can.
Reason: The code reads more clearly and is very likely to be faster.
Here an example what numpy can do:
In [1]: import numpy as np
In [2]: x = np.array([4,5,6,7,8])
In [3]: x+3
Out[3]: array([ 7, 8, 9, 10, 11])
In [4]: x**2
Out[4]: array([16, 25, 36, 49, 64])
In [5]: x>=6
Out[5]: array([False, False, True, True, True], dtype=bool)
For further reading I recommend the numpy tutorial.
| Python Array problem | I have an array that I have to add a new value to array value. I am new to arrays.
how do I loop thru the array and add to the value in the existing array.
| [
">>> print [x+2 for x in [1,2,3]]\n[3, 4, 5]\n>>> \n\nLearn about Python lists and list comprehensions\n",
"a = [2, 3, 4]\nfor i in range(0, len(a)):\n a[i] += 3\nprint a #prints [5, 6, 7]\n\n",
"If you are working with arrays and need to do some math I would definitely recommend you numpy. Numpy was made for this purpose. Another hint (to all what I know): try to avoid loops where you can.\nReason: The code reads more clearly and is very likely to be faster.\nHere an example what numpy can do:\nIn [1]: import numpy as np\n\nIn [2]: x = np.array([4,5,6,7,8])\n\nIn [3]: x+3\nOut[3]: array([ 7, 8, 9, 10, 11])\n\nIn [4]: x**2\nOut[4]: array([16, 25, 36, 49, 64])\n\nIn [5]: x>=6\nOut[5]: array([False, False, True, True, True], dtype=bool)\n\nFor further reading I recommend the numpy tutorial.\n"
] | [
3,
0,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0002789075_arrays_python.txt |
Q:
Does python have a session variable concept?
I have a datetime.date variable in python.I need to pass it to a function do operations according to the date given and then increment the date for the next set of operations.The problem is I have to do the operations in diff pages and hence I need the date as a variable which can go from page to page. Can we do this in python.......
This is to be done in .py scripts and not any web related work........
A:
Sessions have nothing to do with Python per se. See your web framework's documentation for how it handles sessions.
A:
You could build a global dict of "sessions" and update that dict when appropriate.
A:
Python itself does not handle sessions. Sessions are a concept that is handled by the web server. For example Apache can handle sessions. Python can access the sessions variables with mod_python, mod_wsgi, or through cgi. Furthermore, web frameworks built on top of these technologies (ex: Django) can access session variables.
A:
If you are interested in a custom session solution, you may want to check out this module used in a web-enabled Bible Verse quizzing program.
| Does python have a session variable concept? | I have a datetime.date variable in python.I need to pass it to a function do operations according to the date given and then increment the date for the next set of operations.The problem is I have to do the operations in diff pages and hence I need the date as a variable which can go from page to page. Can we do this in python.......
This is to be done in .py scripts and not any web related work........
| [
"Sessions have nothing to do with Python per se. See your web framework's documentation for how it handles sessions.\n",
"You could build a global dict of \"sessions\" and update that dict when appropriate.\n",
"Python itself does not handle sessions. Sessions are a concept that is handled by the web server. For example Apache can handle sessions. Python can access the sessions variables with mod_python, mod_wsgi, or through cgi. Furthermore, web frameworks built on top of these technologies (ex: Django) can access session variables.\n",
"If you are interested in a custom session solution, you may want to check out this module used in a web-enabled Bible Verse quizzing program.\n"
] | [
5,
2,
1,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002794362_datetime_python.txt |
Q:
How do I assign functions in a dictionary?
I'm having a problem with a simple program I wrote, I want to perform a certain function according to the users input. I've already used a dictionary as a replacement for a switch to do assignment but when I try to assign functions to the dictionary it doesn't execute them...
The code:
def PrintValuesArea():
## do this
def PrintValuesLength():
## do that
def PrintValuesTime():
## do third
PrintTables={"a":PrintValuesArea,"l":PrintValuesLength,"t":PrintValuesTime}
PrintTables.get(ans.lower()) ## ans is the user input
what did I do wrong? It looks the same as all the examples I've seen....
A:
You forgot to call it.
PrintTables.get(ans.lower())()
or
PrintTables[ans.lower()]()
| How do I assign functions in a dictionary? | I'm having a problem with a simple program I wrote, I want to perform a certain function according to the users input. I've already used a dictionary as a replacement for a switch to do assignment but when I try to assign functions to the dictionary it doesn't execute them...
The code:
def PrintValuesArea():
## do this
def PrintValuesLength():
## do that
def PrintValuesTime():
## do third
PrintTables={"a":PrintValuesArea,"l":PrintValuesLength,"t":PrintValuesTime}
PrintTables.get(ans.lower()) ## ans is the user input
what did I do wrong? It looks the same as all the examples I've seen....
| [
"You forgot to call it.\nPrintTables.get(ans.lower())()\n\nor\nPrintTables[ans.lower()]()\n\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0002794631_python.txt |
Q:
Python's subprocess.Popen object hangs gathering child output when child process does not exit
When a process exits abnormally or not at all, I still want to be able to gather what output it may have generated up until that point.
The obvious solution to this example code is to kill the child process with an os.kill, but in my real code, the child is hung waiting for NFS and does not respond to a SIGKILL.
#!/usr/bin/python
import subprocess
import os
import time
import signal
import sys
child_script = """
#!/bin/bash
i=0
while [ 1 ]; do
echo "output line $i"
i=$(expr $i \+ 1)
sleep 1
done
"""
childFile = open("/tmp/childProc.sh", 'w')
childFile.write(child_script)
childFile.close()
cmd = ["bash", "/tmp/childProc.sh"]
finish = time.time() + 3
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
while p.poll() is None:
time.sleep(0.05)
if finish < time.time():
print "timed out and killed child, collecting what output exists so far"
out, err = p.communicate()
print "got it"
sys.exit(0)
In this case, the print statement about timing out appears and the python script never exits or progresses. Does anybody know how I can do this differently and still get output from my child processe
A:
Problem is that bash doesn't answer to CTRL-C when not connected with a terminal.
Switching to SIGHUP or SIGTERM seems to do the trick:
cmd = ["bash", 'childProc.sh']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True)
time.sleep(3)
print 'killing pid', p.pid
os.kill(p.pid, signal.SIGTERM)
print "timed out and killed child, collecting what output exists so far"
out = p.communicate()[0]
print "got it", out
Outputs:
killing pid 5844
timed out and killed child, collecting what output exists so far
got it output line 0
output line 1
output line 2
A:
Here's a POSIX way of doing it without the temporary file. I realize that subprocess is a little superfluous here, but since the original question used it...
import subprocess
import os
import time
import signal
import sys
pr, pw = os.pipe()
pid = os.fork ()
if pid: #parent
os.close(pw)
cmd = ["bash"]
finish = time.time() + 3
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=pr, close_fds=True)
while p.poll() is None:
time.sleep(0.05)
if finish < time.time():
os.kill(p.pid, signal.SIGTERM)
print "timed out and killed child, collecting what output exists so far"
out, err = p.communicate()
print "got it: ", out
sys.exit(0)
else: #child
os.close(pr)
child_script = """
#!/bin/bash
while [ 1 ]; do
((++i))
echo "output line $i"
sleep 1
done
"""
os.write(pw, child_script)
A:
There are good tips in another stackoverflow question: How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
Most of the hints in there work with pipe.readline() instead of pipe.communicate() because the latter only returns at the end of the process.
A:
I had the exact same problem. I ended up fixing the issue (after scouring Google and finding many related problems) by simply setting the following parameters when calling subprocess.Popen (or .call):
stdout=None
and
stderr=None
There are many problems with these functions but in my specific case I believe stdout was being filled up by the process I was calling and then resulting in a blocking condition. By setting these to None (opposed to something like subprocess.PIPE) I believe this is avoided.
Hope this helps someone.
| Python's subprocess.Popen object hangs gathering child output when child process does not exit | When a process exits abnormally or not at all, I still want to be able to gather what output it may have generated up until that point.
The obvious solution to this example code is to kill the child process with an os.kill, but in my real code, the child is hung waiting for NFS and does not respond to a SIGKILL.
#!/usr/bin/python
import subprocess
import os
import time
import signal
import sys
child_script = """
#!/bin/bash
i=0
while [ 1 ]; do
echo "output line $i"
i=$(expr $i \+ 1)
sleep 1
done
"""
childFile = open("/tmp/childProc.sh", 'w')
childFile.write(child_script)
childFile.close()
cmd = ["bash", "/tmp/childProc.sh"]
finish = time.time() + 3
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
while p.poll() is None:
time.sleep(0.05)
if finish < time.time():
print "timed out and killed child, collecting what output exists so far"
out, err = p.communicate()
print "got it"
sys.exit(0)
In this case, the print statement about timing out appears and the python script never exits or progresses. Does anybody know how I can do this differently and still get output from my child processe
| [
"Problem is that bash doesn't answer to CTRL-C when not connected with a terminal.\nSwitching to SIGHUP or SIGTERM seems to do the trick:\ncmd = [\"bash\", 'childProc.sh']\np = subprocess.Popen(cmd, stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT, \n close_fds=True)\ntime.sleep(3)\nprint 'killing pid', p.pid\nos.kill(p.pid, signal.SIGTERM)\nprint \"timed out and killed child, collecting what output exists so far\"\nout = p.communicate()[0]\nprint \"got it\", out\n\nOutputs:\nkilling pid 5844\ntimed out and killed child, collecting what output exists so far\ngot it output line 0\noutput line 1\noutput line 2\n\n",
"Here's a POSIX way of doing it without the temporary file. I realize that subprocess is a little superfluous here, but since the original question used it...\nimport subprocess\nimport os\nimport time\nimport signal\nimport sys\n\npr, pw = os.pipe()\npid = os.fork () \n\nif pid: #parent\n os.close(pw)\n cmd = [\"bash\"]\n finish = time.time() + 3\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=pr, close_fds=True)\n while p.poll() is None:\n time.sleep(0.05)\n if finish < time.time():\n os.kill(p.pid, signal.SIGTERM)\n print \"timed out and killed child, collecting what output exists so far\"\n out, err = p.communicate()\n print \"got it: \", out\n sys.exit(0)\n\nelse: #child\n os.close(pr)\n child_script = \"\"\"\n #!/bin/bash\n while [ 1 ]; do\n ((++i))\n echo \"output line $i\"\n sleep 1\n done\n \"\"\"\n os.write(pw, child_script)\n\n",
"There are good tips in another stackoverflow question: How do I get 'real-time' information back from a subprocess.Popen in python (2.5)\nMost of the hints in there work with pipe.readline() instead of pipe.communicate() because the latter only returns at the end of the process.\n",
"I had the exact same problem. I ended up fixing the issue (after scouring Google and finding many related problems) by simply setting the following parameters when calling subprocess.Popen (or .call):\nstdout=None\n\nand\nstderr=None\n\nThere are many problems with these functions but in my specific case I believe stdout was being filled up by the process I was calling and then resulting in a blocking condition. By setting these to None (opposed to something like subprocess.PIPE) I believe this is avoided.\nHope this helps someone.\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"freeze",
"python",
"subprocess"
] | stackoverflow_0002151640_freeze_python_subprocess.txt |
Q:
Indent guide plugin for gedit (python)
screenshot http://www.activestate.com/padfiles/komodo_edit/komodo_edit_linux.png
See the indent guides? They're damn helpful when writing Python code. Any chance I could get something similar for gedit? I wouldn't mind having to write my own plugin, as long as it's in Python... So:
Is there a plugin for this which works with gedit?
If not, would it be possible to write one in Python.
A:
There's a huge list of GEdit plugins here:
https://wiki.gnome.org/Apps/Gedit/Plugins
I haven't looked through them in a while, but I don't remember any implementing indentation guides. Many plugins are written in Python, so there are some good examples if you want to implement your own.
| Indent guide plugin for gedit (python) | screenshot http://www.activestate.com/padfiles/komodo_edit/komodo_edit_linux.png
See the indent guides? They're damn helpful when writing Python code. Any chance I could get something similar for gedit? I wouldn't mind having to write my own plugin, as long as it's in Python... So:
Is there a plugin for this which works with gedit?
If not, would it be possible to write one in Python.
| [
"There's a huge list of GEdit plugins here:\nhttps://wiki.gnome.org/Apps/Gedit/Plugins\nI haven't looked through them in a while, but I don't remember any implementing indentation guides. Many plugins are written in Python, so there are some good examples if you want to implement your own.\n"
] | [
3
] | [] | [] | [
"indentation",
"komodo",
"plugins",
"python"
] | stackoverflow_0002794741_indentation_komodo_plugins_python.txt |
Q:
Can't iterate over nestled dict in django
Im trying to iterate over a nestled dict list. The first level works fine. But the second level is treated like a string not dict.
In my template I have this:
{% for product in Products %}
<li>
<p>{{ product }}</p>
{% for partType in product.parts %}
<p>{{ partType }}</p>
{% for part in partType %}
<p>{{ part }}</p>
{% endfor %}
{% endfor %}
</li>
{% endfor %}
It's the {{ part }} that just list 1 char at the time based on partType. And it seams that it's treated like a string. I can however via dot notation reach all dict but not with a for loop. The current output looks like this:
Color
C
o
l
o
r
Style
S
.....
The Products object looks like this in the log:
[{'product': <models.Products.Product object at 0x1076ac9d0>, 'parts': {u'Color': {'default': u'Red', 'optional': [u'Red', u'Blue']}, u'Style': {'default': u'Nice', 'optional': [u'Nice']}, u'Size': {'default': u'8', 'optional': [u'8', u'8.5']}}}]
What I trying to do is to pair together a dict/list for a product from a number of different SQL queries.
The web handler looks like this:
typeData = Products.ProductPartTypes.all()
productData = Products.Product.all()
langCode = 'en'
productList = []
for product in productData:
typeDict = {}
productDict = {}
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
productDict['product'] = product
productDict['parts'] = typeDict
defaultPartsData = Products.ProductParts.gql('WHERE __key__ IN :key', key = product.defaultParts)
optionalPartsData = Products.ProductParts.gql('WHERE __key__ IN :key', key = product.optionalParts)
for defaultPart in defaultPartsData:
label = Products.ProductPartLabels.gql('WHERE __key__ IN :key AND partLangCode = :langCode', key = defaultPart.partLabelList, langCode = langCode).get()
productDict['parts'][defaultPart.type.typeId]['default'] = label.partLangLabel
for optionalPart in optionalPartsData:
label = Products.ProductPartLabels.gql('WHERE __key__ IN :key AND partLangCode = :langCode', key = optionalPart.partLabelList, langCode = langCode).get()
productDict['parts'][optionalPart.type.typeId]['optional'].append(label.partLangLabel)
productList.append(productDict)
logging.info(productList)
templateData = { 'Languages' : Settings.Languges.all().order('langCode'), 'ProductPartTypes' : typeData, 'Products' : productList }
I've tried making the dict in a number of different ways. Like first making a list, then a dict, used tulpes anything I could think of.
Any help is welcome!
Bouns: If someone have an other approach to the SQL quires, that is more then welcome. I feel that it kinda stupid to run that amount of quires. What is happening that each product part has a different label base on langCode.
..fredrik
A:
Iterating over a dict yields the keys. You want either the iteritems() or itervalues() method.
{% for partName, partType in product.parts.iteritems %}
<p>{{ partName }}</p>
{% for part in partType %}
<p>{{ part }}</p>
{% endfor %}
....
| Can't iterate over nestled dict in django | Im trying to iterate over a nestled dict list. The first level works fine. But the second level is treated like a string not dict.
In my template I have this:
{% for product in Products %}
<li>
<p>{{ product }}</p>
{% for partType in product.parts %}
<p>{{ partType }}</p>
{% for part in partType %}
<p>{{ part }}</p>
{% endfor %}
{% endfor %}
</li>
{% endfor %}
It's the {{ part }} that just list 1 char at the time based on partType. And it seams that it's treated like a string. I can however via dot notation reach all dict but not with a for loop. The current output looks like this:
Color
C
o
l
o
r
Style
S
.....
The Products object looks like this in the log:
[{'product': <models.Products.Product object at 0x1076ac9d0>, 'parts': {u'Color': {'default': u'Red', 'optional': [u'Red', u'Blue']}, u'Style': {'default': u'Nice', 'optional': [u'Nice']}, u'Size': {'default': u'8', 'optional': [u'8', u'8.5']}}}]
What I trying to do is to pair together a dict/list for a product from a number of different SQL queries.
The web handler looks like this:
typeData = Products.ProductPartTypes.all()
productData = Products.Product.all()
langCode = 'en'
productList = []
for product in productData:
typeDict = {}
productDict = {}
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
productDict['product'] = product
productDict['parts'] = typeDict
defaultPartsData = Products.ProductParts.gql('WHERE __key__ IN :key', key = product.defaultParts)
optionalPartsData = Products.ProductParts.gql('WHERE __key__ IN :key', key = product.optionalParts)
for defaultPart in defaultPartsData:
label = Products.ProductPartLabels.gql('WHERE __key__ IN :key AND partLangCode = :langCode', key = defaultPart.partLabelList, langCode = langCode).get()
productDict['parts'][defaultPart.type.typeId]['default'] = label.partLangLabel
for optionalPart in optionalPartsData:
label = Products.ProductPartLabels.gql('WHERE __key__ IN :key AND partLangCode = :langCode', key = optionalPart.partLabelList, langCode = langCode).get()
productDict['parts'][optionalPart.type.typeId]['optional'].append(label.partLangLabel)
productList.append(productDict)
logging.info(productList)
templateData = { 'Languages' : Settings.Languges.all().order('langCode'), 'ProductPartTypes' : typeData, 'Products' : productList }
I've tried making the dict in a number of different ways. Like first making a list, then a dict, used tulpes anything I could think of.
Any help is welcome!
Bouns: If someone have an other approach to the SQL quires, that is more then welcome. I feel that it kinda stupid to run that amount of quires. What is happening that each product part has a different label base on langCode.
..fredrik
| [
"Iterating over a dict yields the keys. You want either the iteritems() or itervalues() method.\n{% for partName, partType in product.parts.iteritems %}\n <p>{{ partName }}</p>\n {% for part in partType %}\n <p>{{ part }}</p>\n {% endfor %}\n ....\n\n"
] | [
7
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002794833_django_google_app_engine_python.txt |
Q:
What mutex/locking/waiting mechanism to use when writing a Chat application with Tornado Web Framework
We're implementing a Chat server using Tornado.
The premise is simple, a user makes open an HTTP ajax connection to the Tornado server, and the Tornado server answers only when a new message appears in the chat-room. Whenever the connection closes, regardless if a new message came in or an error/timeout occurred, the client reopens the connection.
Looking at Tornado, the question arises of what library can we use to allow us to have these calls wait on some central object that would signal them - A_NEW_MESSAGE_HAS_ARRIVED_ITS_TIME_TO_SEND_BACK_SOME_DATA.
To describe this in Win32 terms, each async call would be represented as a thread that would be hanging on a WaitForSingleObject(...) on some central Mutex/Event/etc.
We will be operating in a standard Python environment (Tornado), is there something built-in we can use, do we need an external library/server, is there something Tornado recommends?
Thanks
A:
I'm looking into the best options for developing a chat application and was looking into tornado as well. This rough cuts Building the Realtime User Experience has a chapter on building a chat application with tornado that might be useful to you. Best of luck :)
A:
Tornado has a "chat" example which uses long polling. It contains everything you need (or actually, probably more than you need since it includes a 3rd-party login)
| What mutex/locking/waiting mechanism to use when writing a Chat application with Tornado Web Framework | We're implementing a Chat server using Tornado.
The premise is simple, a user makes open an HTTP ajax connection to the Tornado server, and the Tornado server answers only when a new message appears in the chat-room. Whenever the connection closes, regardless if a new message came in or an error/timeout occurred, the client reopens the connection.
Looking at Tornado, the question arises of what library can we use to allow us to have these calls wait on some central object that would signal them - A_NEW_MESSAGE_HAS_ARRIVED_ITS_TIME_TO_SEND_BACK_SOME_DATA.
To describe this in Win32 terms, each async call would be represented as a thread that would be hanging on a WaitForSingleObject(...) on some central Mutex/Event/etc.
We will be operating in a standard Python environment (Tornado), is there something built-in we can use, do we need an external library/server, is there something Tornado recommends?
Thanks
| [
"I'm looking into the best options for developing a chat application and was looking into tornado as well. This rough cuts Building the Realtime User Experience has a chapter on building a chat application with tornado that might be useful to you. Best of luck :)\n",
"Tornado has a \"chat\" example which uses long polling. It contains everything you need (or actually, probably more than you need since it includes a 3rd-party login)\n"
] | [
2,
0
] | [] | [] | [
"asynchronous",
"python",
"tornado"
] | stackoverflow_0002262039_asynchronous_python_tornado.txt |
Q:
Python: replace urls with title names from a string
I would like to remove urls from a string and replace them with their titles of the original contents.
For example:
mystring = "Ah I like this site: http://www.stackoverflow.com. Also I must say I like http://www.digg.com"
sanitize(mystring) # it becomes "Ah I like this site: Stack Overflow. Also I must say I like Digg - The Latest News Headlines, Videos and Images"
For replacing url with the title, I have written this snipplet:
#get_title: string -> string
def get_title(url):
"""Returns the title of the input URL"""
output = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
return output.title.string
I somehow need to apply this function to strings where it catches the urls and converts to titles via get_title.
A:
Here is a question with information for validating a url in Python: How do you validate a URL with a regular expression in Python?
urlparse module is probably your best bet. You will still have to decide what constitutes a valid url in the context of your application.
To check the string for a url you will want to iterate over each word in the string check it and then replace the valid url with the title.
example code (you will need to write valid_url):
def sanitize(mystring):
for word in mystring.split(" "):
if valid_url(word):
mystring = mystring.replace(word, get_title(word))
return mystring
A:
You can probably solve this using regular expressions and substitution (re.sub accepts a function, which will be passed the Match object for each occurence and returns the string to replace it with):
url = re.compile("http:\/\/(.*?)/")
text = url.sub(get_title, text)
The difficult thing is creating a regexp that matches an URL, not more, not less.
| Python: replace urls with title names from a string | I would like to remove urls from a string and replace them with their titles of the original contents.
For example:
mystring = "Ah I like this site: http://www.stackoverflow.com. Also I must say I like http://www.digg.com"
sanitize(mystring) # it becomes "Ah I like this site: Stack Overflow. Also I must say I like Digg - The Latest News Headlines, Videos and Images"
For replacing url with the title, I have written this snipplet:
#get_title: string -> string
def get_title(url):
"""Returns the title of the input URL"""
output = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
return output.title.string
I somehow need to apply this function to strings where it catches the urls and converts to titles via get_title.
| [
"Here is a question with information for validating a url in Python: How do you validate a URL with a regular expression in Python?\nurlparse module is probably your best bet. You will still have to decide what constitutes a valid url in the context of your application.\nTo check the string for a url you will want to iterate over each word in the string check it and then replace the valid url with the title.\nexample code (you will need to write valid_url):\ndef sanitize(mystring):\n for word in mystring.split(\" \"):\n if valid_url(word):\n mystring = mystring.replace(word, get_title(word))\n return mystring\n\n",
"You can probably solve this using regular expressions and substitution (re.sub accepts a function, which will be passed the Match object for each occurence and returns the string to replace it with):\nurl = re.compile(\"http:\\/\\/(.*?)/\")\ntext = url.sub(get_title, text)\n\nThe difficult thing is creating a regexp that matches an URL, not more, not less. \n"
] | [
3,
2
] | [] | [] | [
"python",
"replace",
"title",
"url"
] | stackoverflow_0002794974_python_replace_title_url.txt |
Q:
Passing a multi-line string as an argument to a script in Windows
I have a simple python script like so:
import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?
Of course, this works:
import sys
lines = """This is a string
It has multiple lines
there are three total"""
for line in lines.splitlines():
print line
But I need to be able to process an argument line-by-line.
EDIT: This is probably more of a Windows command-line problem than a Python problem.
EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.
A:
I know this thread is pretty old, but I came across it while trying to solve a similar problem, and others might as well, so let me show you how I solved it.
This works at least on Windows XP Pro, with Zack's code in a file called
"C:\Scratch\test.py":
C:\Scratch>test.py "This is a string"^
More?
More? "It has multiple lines"^
More?
More? "There are three total"
This is a string
It has multiple lines
There are three total
C:\Scratch>
This is a little more readable than Romulo's solution above.
A:
Just enclose the argument in quotes:
$ python args.py "This is a string
> It has multiple lines
> there are three total"
This is a string
It has multiple lines
there are three total
A:
The following might work:
C:\> python something.py "This is a string^
More?
More? It has multiple lines^
More?
More? There are three total"
A:
This is the only thing which worked for me:
C:\> python a.py This" "is" "a" "string^
More?
More? It" "has" "multiple" "lines^
More?
More? There" "are" "three" "total
For me Johannes' solution invokes the python interpreter at the end of the first line, so I don't have the chance to pass additional lines.
But you said you are calling the python script from another process, not from the command line. Then why don't you use dbr' solution? This worked for me as a Ruby script:
puts `python a.py "This is a string\nIt has multiple lines\nThere are three total"`
And in what language are you writing the program which calls the python script? The issue you have is with argument passing, not with the windows shell, not with Python...
Finally, as mattkemp said, I also suggest you use the standard input to read your multi-line argument, avoiding command line magic.
A:
Not sure about the Windows command-line, but would the following work?
> python myscript.py "This is a string\nIt has multiple lines\there are three total"
..or..
> python myscript.py "This is a string\
It has [...]\
there are [...]"
If not, I would suggest installing Cygwin and using a sane shell!
A:
Have you tried setting you multiline text as a variable and then passing the expansion of that into your script. For example:
set Text="This is a string
It has multiple lines
there are three total"
python args.py %Text%
Alternatively, instead of reading an argument you could read from standard in.
import sys
for line in iter(sys.stdin.readline, ''):
print line
On Linux you would pipe the multiline text to the standard input of args.py.
$ <command-that-produces-text> | python args.py
| Passing a multi-line string as an argument to a script in Windows | I have a simple python script like so:
import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?
Of course, this works:
import sys
lines = """This is a string
It has multiple lines
there are three total"""
for line in lines.splitlines():
print line
But I need to be able to process an argument line-by-line.
EDIT: This is probably more of a Windows command-line problem than a Python problem.
EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.
| [
"I know this thread is pretty old, but I came across it while trying to solve a similar problem, and others might as well, so let me show you how I solved it.\nThis works at least on Windows XP Pro, with Zack's code in a file called\n\"C:\\Scratch\\test.py\":\nC:\\Scratch>test.py \"This is a string\"^\nMore?\nMore? \"It has multiple lines\"^\nMore?\nMore? \"There are three total\"\nThis is a string\nIt has multiple lines\nThere are three total\n\nC:\\Scratch>\n\nThis is a little more readable than Romulo's solution above.\n",
"Just enclose the argument in quotes:\n$ python args.py \"This is a string\n> It has multiple lines\n> there are three total\"\nThis is a string\nIt has multiple lines\nthere are three total\n\n",
"The following might work:\nC:\\> python something.py \"This is a string^\nMore?\nMore? It has multiple lines^\nMore?\nMore? There are three total\"\n\n",
"This is the only thing which worked for me:\nC:\\> python a.py This\" \"is\" \"a\" \"string^\nMore?\nMore? It\" \"has\" \"multiple\" \"lines^\nMore?\nMore? There\" \"are\" \"three\" \"total\n\nFor me Johannes' solution invokes the python interpreter at the end of the first line, so I don't have the chance to pass additional lines.\nBut you said you are calling the python script from another process, not from the command line. Then why don't you use dbr' solution? This worked for me as a Ruby script:\nputs `python a.py \"This is a string\\nIt has multiple lines\\nThere are three total\"`\n\nAnd in what language are you writing the program which calls the python script? The issue you have is with argument passing, not with the windows shell, not with Python...\nFinally, as mattkemp said, I also suggest you use the standard input to read your multi-line argument, avoiding command line magic.\n",
"Not sure about the Windows command-line, but would the following work?\n> python myscript.py \"This is a string\\nIt has multiple lines\\there are three total\"\n\n..or..\n> python myscript.py \"This is a string\\\nIt has [...]\\\nthere are [...]\"\n\nIf not, I would suggest installing Cygwin and using a sane shell!\n",
"Have you tried setting you multiline text as a variable and then passing the expansion of that into your script. For example:\nset Text=\"This is a string\nIt has multiple lines\nthere are three total\"\npython args.py %Text%\n\nAlternatively, instead of reading an argument you could read from standard in.\nimport sys\n\nfor line in iter(sys.stdin.readline, ''):\n print line\n\nOn Linux you would pipe the multiline text to the standard input of args.py.\n$ <command-that-produces-text> | python args.py\n"
] | [
4,
2,
1,
1,
0,
0
] | [] | [] | [
"batch_file",
"dos",
"python",
"string",
"windows"
] | stackoverflow_0000749049_batch_file_dos_python_string_windows.txt |
Q:
Get node name with minidom
Is it possible to get the name of a node using minidom?
For example I have a node:
<heading><![CDATA[5 year]]></heading>
What I'm trying to do, is store the value heading so that I can use it as a key in a dictionary.
The closest I can get is something like:
[<DOM Element: heading at 0x11e6d28>]
I'm sure I'm overlooking something very simple here, thanks.
A:
Is this what you mean?
tag= node.tagName
d[tag]= node
tagName is defined in DOM Level 1 Core, the basic standard that minidom (mostly) implements.
| Get node name with minidom | Is it possible to get the name of a node using minidom?
For example I have a node:
<heading><![CDATA[5 year]]></heading>
What I'm trying to do, is store the value heading so that I can use it as a key in a dictionary.
The closest I can get is something like:
[<DOM Element: heading at 0x11e6d28>]
I'm sure I'm overlooking something very simple here, thanks.
| [
"Is this what you mean?\ntag= node.tagName\nd[tag]= node\n\ntagName is defined in DOM Level 1 Core, the basic standard that minidom (mostly) implements.\n"
] | [
13
] | [] | [] | [
"minidom",
"python"
] | stackoverflow_0002795462_minidom_python.txt |
Q:
How to see Microsoft Speech Recognition language and if it's active using Python?
I'm using windows 7 english and I want to know how to see the microsoft speech language and to see if the speech recognition is active.
How can I do it using python?
Solved with:
x=_winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER)
try:
y= _winreg.OpenKey(x, r"Software\Microsoft\Speech\Preferences")
if _winreg.QueryValueEx(y,'en-US_CompletedSpeechConfiguration')[0]:
self.recognitionMode = True
else:
self.recognitionMode = False
except EnvironmentError:
self.recognitionMode = False
A:
If you know the registry key you could use the Python _winreg API
| How to see Microsoft Speech Recognition language and if it's active using Python? | I'm using windows 7 english and I want to know how to see the microsoft speech language and to see if the speech recognition is active.
How can I do it using python?
Solved with:
x=_winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER)
try:
y= _winreg.OpenKey(x, r"Software\Microsoft\Speech\Preferences")
if _winreg.QueryValueEx(y,'en-US_CompletedSpeechConfiguration')[0]:
self.recognitionMode = True
else:
self.recognitionMode = False
except EnvironmentError:
self.recognitionMode = False
| [
"If you know the registry key you could use the Python _winreg API\n"
] | [
2
] | [] | [] | [
"python",
"speech_recognition"
] | stackoverflow_0002795358_python_speech_recognition.txt |
Q:
Making py2exe produce `.py` files
Is there any way to make py2exe output .py source files instead of byte-compiled .pyc files in the library?
A:
I did it long ago, so I hope I remember correctly:
Set compressed to False, so py2exe won't create a Zip'd library file.
Set optimize to zero, so py2exe will write pyc files.
UPDATE: Ram Rachum is right, use the skip_archive option instead of compressed.
You won't be able to modify your main Python file, since it will be embedded into the main executable, so keep that to a minimum. Then you'll be able to replace the pyc files with your py files manually in your distribution as needed. No reason to replace the standard libraries, however, only your own code.
(It is not optimal for debugging, but I guess you want to fix some problem happening only to the release build of your software this way.)
Please let me know if it does not work and I'll try to help.
UPDATE:
I've just read the relevant parts of the py2exe source code. It seems that py2exe does not support it out of the box. So we've left with the option to touch its source code.
You can easily modify py2exe to support this mode. See the byte_compile function in build_exe.py. There's a call to the compile built-in function in it, which you can replace with a copy_file. Don't forget to modify the destination file name (dfile) to have the extension .py instead of .pyc or .pyo. I know that it is patchwork, but I don't see any other possibility to solve your problem.
You can also add a new py2exe option or introduce a new optimize value for this if you're curious. It would be an open-source contribution to py2exe, actually. ;)
| Making py2exe produce `.py` files | Is there any way to make py2exe output .py source files instead of byte-compiled .pyc files in the library?
| [
"I did it long ago, so I hope I remember correctly:\n\nSet compressed to False, so py2exe won't create a Zip'd library file.\nSet optimize to zero, so py2exe will write pyc files.\n\nUPDATE: Ram Rachum is right, use the skip_archive option instead of compressed.\nYou won't be able to modify your main Python file, since it will be embedded into the main executable, so keep that to a minimum. Then you'll be able to replace the pyc files with your py files manually in your distribution as needed. No reason to replace the standard libraries, however, only your own code.\n(It is not optimal for debugging, but I guess you want to fix some problem happening only to the release build of your software this way.)\nPlease let me know if it does not work and I'll try to help.\nUPDATE:\nI've just read the relevant parts of the py2exe source code. It seems that py2exe does not support it out of the box. So we've left with the option to touch its source code.\nYou can easily modify py2exe to support this mode. See the byte_compile function in build_exe.py. There's a call to the compile built-in function in it, which you can replace with a copy_file. Don't forget to modify the destination file name (dfile) to have the extension .py instead of .pyc or .pyo. I know that it is patchwork, but I don't see any other possibility to solve your problem.\nYou can also add a new py2exe option or introduce a new optimize value for this if you're curious. It would be an open-source contribution to py2exe, actually. ;)\n"
] | [
1
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0002793702_py2exe_python.txt |
Q:
How can i do this using a Python Regex?
I am trying to properly extract methods definitions that are generated by comtypes for Com Interfaces using a regex. Furthermore some of them are blank which causes even more problems for me.
Basically i have this:
IXMLSerializerAlt._methods_ = [
COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',
( ['in'], BSTR, 'XML' ),
( ['in'], BSTR, 'TypeName' ),
( ['in'], BSTR, 'TypeNamespaceURI' ),
( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),
]
class EnvironmentManager(CoClass):
u'Singleton object that manages different environments (collections of configuration information).'
_reg_clsid_ = GUID('{8A626D49-5F5E-47D9-9463-0B802E9C4167}')
_idlflags_ = []
_typelib_path_ = typelib_path
_reg_typelib_ = ('{5E1F7BC3-67C5-4AEE-8EC6-C4B73AAC42ED}', 1, 0)
INumberFormat._methods_ = [
]
I want to extract both the IXMLSerializerAlt and INumberFormat methods definitions however i cant figure out a proper regex. E.g. for IXMLSerializer i want to extract this:
IXMLSerializerAlt._methods_ = [
COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',
( ['in'], BSTR, 'XML' ),
( ['in'], BSTR, 'TypeName' ),
( ['in'], BSTR, 'TypeNamespaceURI' ),
( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),
]
This regex in my mind this should work:
^\w+\._methods_\s=\s\[$
(^.+$)*
^]$
Im checking my regex's using kodos however i cannot figure out a way to make this work.
A:
You're missing the newline characters between $ and ^, and may not be using the re.MULTILINE flag which allows those to anchor at the start and end of lines. The following (compiled with re.MULTILINE) would match:
\w+\._methods_\s=\s\[$(?:\n^.+$)*\n^\]$
However, here's a slightly simpliifed regex that will also match your examples:
>>> s = '''...\nIXMLSerializerAlt._methods_ = [\n COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',\n ( ['in'], BSTR, 'XML' ),\n ( ['in'], BSTR, 'TypeName' ),\n ( ['in'], BSTR, 'TypeNamespaceURI' ),\n ( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),\n]\n...'''
>>> import re
>>> re.findall(r'^\w+\._methods_\s=\s\[$.*?^\]$', s, re.DOTALL | re.MULTILINE)
["IXMLSerializerAlt._methods_ = [\n COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',\n ( ['in'], BSTR, 'XML' ),\n ( ['in'], BSTR, 'TypeName' ),\n ( ['in'], BSTR, 'TypeNamespaceURI' ),\n ( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),\n]"]
A:
import re
interface_definitions = '''
IXMLSerializerAlt._methods_ = [
COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',
( ['in'], BSTR, 'XML' ),
( ['in'], BSTR, 'TypeName' ),
( ['in'], BSTR, 'TypeNamespaceURI' ),
( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),
]
class EnvironmentManager(CoClass):
u'Singleton object that manages different environments (collections of configuration information).'
_reg_clsid_ = GUID('{8A626D49-5F5E-47D9-9463-0B802E9C4167}')
_idlflags_ = []
_typelib_path_ = typelib_path
_reg_typelib_ = ('{5E1F7BC3-67C5-4AEE-8EC6-C4B73AAC42ED}', 1, 0)
INumberFormat._methods_ = [
]
'''
RX_METHODS = re.compile(
r'(\w+)\._methods_\s=\s\[('
r'.*?'
r'(?:\[.*?\].*?)*'
r')\]',
re.DOTALL)
for match in RX_METHODS.finditer(interface_definitions):
print match.groups()
| How can i do this using a Python Regex? | I am trying to properly extract methods definitions that are generated by comtypes for Com Interfaces using a regex. Furthermore some of them are blank which causes even more problems for me.
Basically i have this:
IXMLSerializerAlt._methods_ = [
COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',
( ['in'], BSTR, 'XML' ),
( ['in'], BSTR, 'TypeName' ),
( ['in'], BSTR, 'TypeNamespaceURI' ),
( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),
]
class EnvironmentManager(CoClass):
u'Singleton object that manages different environments (collections of configuration information).'
_reg_clsid_ = GUID('{8A626D49-5F5E-47D9-9463-0B802E9C4167}')
_idlflags_ = []
_typelib_path_ = typelib_path
_reg_typelib_ = ('{5E1F7BC3-67C5-4AEE-8EC6-C4B73AAC42ED}', 1, 0)
INumberFormat._methods_ = [
]
I want to extract both the IXMLSerializerAlt and INumberFormat methods definitions however i cant figure out a proper regex. E.g. for IXMLSerializer i want to extract this:
IXMLSerializerAlt._methods_ = [
COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',
( ['in'], BSTR, 'XML' ),
( ['in'], BSTR, 'TypeName' ),
( ['in'], BSTR, 'TypeNamespaceURI' ),
( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),
]
This regex in my mind this should work:
^\w+\._methods_\s=\s\[$
(^.+$)*
^]$
Im checking my regex's using kodos however i cannot figure out a way to make this work.
| [
"You're missing the newline characters between $ and ^, and may not be using the re.MULTILINE flag which allows those to anchor at the start and end of lines. The following (compiled with re.MULTILINE) would match:\n\\w+\\._methods_\\s=\\s\\[$(?:\\n^.+$)*\\n^\\]$\n\nHowever, here's a slightly simpliifed regex that will also match your examples:\n>>> s = '''...\\nIXMLSerializerAlt._methods_ = [\\n COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',\\n ( ['in'], BSTR, 'XML' ),\\n ( ['in'], BSTR, 'TypeName' ),\\n ( ['in'], BSTR, 'TypeNamespaceURI' ),\\n ( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),\\n]\\n...'''\n>>> import re\n>>> re.findall(r'^\\w+\\._methods_\\s=\\s\\[$.*?^\\]$', s, re.DOTALL | re.MULTILINE)\n[\"IXMLSerializerAlt._methods_ = [\\n COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',\\n ( ['in'], BSTR, 'XML' ),\\n ( ['in'], BSTR, 'TypeName' ),\\n ( ['in'], BSTR, 'TypeNamespaceURI' ),\\n ( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),\\n]\"]\n\n",
"import re\n\ninterface_definitions = '''\nIXMLSerializerAlt._methods_ = [\n COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',\n ( ['in'], BSTR, 'XML' ),\n ( ['in'], BSTR, 'TypeName' ),\n ( ['in'], BSTR, 'TypeNamespaceURI' ),\n ( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),\n]\n\nclass EnvironmentManager(CoClass):\n u'Singleton object that manages different environments (collections of configuration information).'\n _reg_clsid_ = GUID('{8A626D49-5F5E-47D9-9463-0B802E9C4167}')\n _idlflags_ = []\n _typelib_path_ = typelib_path\n _reg_typelib_ = ('{5E1F7BC3-67C5-4AEE-8EC6-C4B73AAC42ED}', 1, 0)\n\nINumberFormat._methods_ = [\n]\n'''\n\nRX_METHODS = re.compile(\n r'(\\w+)\\._methods_\\s=\\s\\[('\n r'.*?'\n r'(?:\\[.*?\\].*?)*'\n r')\\]',\n re.DOTALL)\n\nfor match in RX_METHODS.finditer(interface_definitions):\n print match.groups()\n\n"
] | [
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002796020_python_regex.txt |
Q:
django admin app error (Model with property field): global name 'full_name' is not defined
This is my model:
class Author(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
middle_name = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return full_name
def _get_full_name(self):
"Returns the person's full name."
if self.middle_name == '':
return "%s %s" % (self.first_name, self.last_name)
else:
return "%s %s %s" % (self.first_name, self.middle_name, self.last_name)
full_name = property(_get_full_name)
Everything is fine except when I go into admin interface, I see
TemplateSyntaxError at /bibbase2/admin/bibbase2/author/
Caught an exception while rendering: global name 'full_name' is not defined
It seems like the built-in admin app doesn't work with a property field. Is there something wrong with my code?
A:
def __unicode__(self):
return full_name
Should be:
def __unicode__(self):
return self.full_name
| django admin app error (Model with property field): global name 'full_name' is not defined | This is my model:
class Author(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
middle_name = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return full_name
def _get_full_name(self):
"Returns the person's full name."
if self.middle_name == '':
return "%s %s" % (self.first_name, self.last_name)
else:
return "%s %s %s" % (self.first_name, self.middle_name, self.last_name)
full_name = property(_get_full_name)
Everything is fine except when I go into admin interface, I see
TemplateSyntaxError at /bibbase2/admin/bibbase2/author/
Caught an exception while rendering: global name 'full_name' is not defined
It seems like the built-in admin app doesn't work with a property field. Is there something wrong with my code?
| [
"def __unicode__(self):\n return full_name\n\nShould be:\ndef __unicode__(self):\n return self.full_name\n\n"
] | [
7
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0002796117_django_django_admin_django_models_python.txt |
Q:
Navigating cursor rows in SQLite (Can we rewind/reset the cursor i.e. go back to first row for example?)
I am trying to understand how the following builtin functions work when sequentially processing cursor rows. The descriptions come from the Python 3.1 manual (using SQLite3)
Cursor.fetchone()
Fetches the next row of a query result set, returning a single sequence.
Cursor.fetchmany()
Fetches the next set of rows of a query result, returning a list.
Cursor.fetchall()
Fetches all (remaining) rows of a query result, returning a list.
So if I have a loop in which I am processing one row at a time using cursor.fetchone(), and some later code requires that I return to the first row, or fetch all rows using fetchall(), how do I do it?
The concept is a bit strange to me, especially coming from a Foxpro background which has the concept of a record pointer which can be moved to the 1st or last row in a cursor (go top/bottom), or go to the nth row (go n)
Any help would be appreciated.
Alan
A:
The SQLite interface in Python 3.1 is based on PEP 249, which only specifies that cursors have to support sequential access to the records of a query result. There's no way to go back. If you need to return to a previously fetched row, you should save it when you first fetch it, e.g. create a list of the fetched data (or actually, just use fetchall). Then you can work with the list and go back and forth between rows as much as you want.
The idea behind the design of the DB API is to support efficient execution of code where you only need to process each row once. A typical loop looks like this:
for a,b,c in cursor.fetchone():
# process it
This way, the cursor can discard the references to each row's data once the corresponding iteration of the loop is finished. It doesn't really lose anything because if you want to keep all the data, you can always make a list out of it, but applications dealing with large data sets still have the ability to process rows one at a time. It's kind of like the reasoning behind using generator expressions rather than lists when you need to process elements of an iterable one by one.
| Navigating cursor rows in SQLite (Can we rewind/reset the cursor i.e. go back to first row for example?) | I am trying to understand how the following builtin functions work when sequentially processing cursor rows. The descriptions come from the Python 3.1 manual (using SQLite3)
Cursor.fetchone()
Fetches the next row of a query result set, returning a single sequence.
Cursor.fetchmany()
Fetches the next set of rows of a query result, returning a list.
Cursor.fetchall()
Fetches all (remaining) rows of a query result, returning a list.
So if I have a loop in which I am processing one row at a time using cursor.fetchone(), and some later code requires that I return to the first row, or fetch all rows using fetchall(), how do I do it?
The concept is a bit strange to me, especially coming from a Foxpro background which has the concept of a record pointer which can be moved to the 1st or last row in a cursor (go top/bottom), or go to the nth row (go n)
Any help would be appreciated.
Alan
| [
"The SQLite interface in Python 3.1 is based on PEP 249, which only specifies that cursors have to support sequential access to the records of a query result. There's no way to go back. If you need to return to a previously fetched row, you should save it when you first fetch it, e.g. create a list of the fetched data (or actually, just use fetchall). Then you can work with the list and go back and forth between rows as much as you want.\nThe idea behind the design of the DB API is to support efficient execution of code where you only need to process each row once. A typical loop looks like this:\nfor a,b,c in cursor.fetchone():\n # process it\n\nThis way, the cursor can discard the references to each row's data once the corresponding iteration of the loop is finished. It doesn't really lose anything because if you want to keep all the data, you can always make a list out of it, but applications dealing with large data sets still have the ability to process rows one at a time. It's kind of like the reasoning behind using generator expressions rather than lists when you need to process elements of an iterable one by one.\n"
] | [
9
] | [] | [] | [
"fetch",
"python",
"sqlite"
] | stackoverflow_0002796517_fetch_python_sqlite.txt |
Q:
Are there any concerns I should have about storing a Python Lock object in a Beaker session?
There is a certain page on my website where I want to prevent the same user from visiting it twice in a row. To prevent this, I plan to create a Lock object (from Python's threading library). However, I would need to store that across sessions. Is there anything I should watch out for when trying to store a Lock object in a session (specifically a Beaker session)?
A:
Storing a threading.Lock instance in a session (or anywhere else that needs serialization) is a terrible idea, and presumably you'll get an exception if you try to (since such an object cannot be serialized, e.g., it cannot be pickled). A traditional approach for cooperative serialization of processes relies on file locking (on "artificial" files e.g. in a directory such as /tmp/locks/<username> if you want the locking to be per-user, as you indicate). I believe the wikipedia entry does a good job of describing the general area; if you tell us what OS you're running order, we might suggest something more specific (unfortunately I do not believe there is a cross-platform solution for this).
A:
I just realized that this was a terrible question since locking a lock and saving it to the session takes two steps thus defeating the purpose of the lock's atomic actions.
| Are there any concerns I should have about storing a Python Lock object in a Beaker session? | There is a certain page on my website where I want to prevent the same user from visiting it twice in a row. To prevent this, I plan to create a Lock object (from Python's threading library). However, I would need to store that across sessions. Is there anything I should watch out for when trying to store a Lock object in a session (specifically a Beaker session)?
| [
"Storing a threading.Lock instance in a session (or anywhere else that needs serialization) is a terrible idea, and presumably you'll get an exception if you try to (since such an object cannot be serialized, e.g., it cannot be pickled). A traditional approach for cooperative serialization of processes relies on file locking (on \"artificial\" files e.g. in a directory such as /tmp/locks/<username> if you want the locking to be per-user, as you indicate). I believe the wikipedia entry does a good job of describing the general area; if you tell us what OS you're running order, we might suggest something more specific (unfortunately I do not believe there is a cross-platform solution for this).\n",
"I just realized that this was a terrible question since locking a lock and saving it to the session takes two steps thus defeating the purpose of the lock's atomic actions.\n"
] | [
1,
0
] | [] | [] | [
"beaker",
"concurrency",
"pylons",
"python"
] | stackoverflow_0002794829_beaker_concurrency_pylons_python.txt |
Q:
Learn Actionscript 3.0+Flash Vs. C#
I have a background in python and I'm looking for a new language. I am almost only intrested in making games.
I have come to 2 languages. C# and Action Script.
C# because Microsoft allows you to make Indie XBLA games programmed in C# ONLY.
Action Script so I can make flash games for new grounds and ect.
What do you think is better to learn in the long run?
A:
I would say C#. You'll learn the basics and then be able to write games for the Desktop (XNA), XBox (XNA), Mobile Devices (XNA and XNA Touch for the iPhone), the Web (via Silverlight), etc.
Flash only gets you limited exposure to each.
A:
I have zero experience with C#, but I'll speak to AS3/Flash's #1 advantage:
For learning game development, Flash lets you make games very quickly, but more importantly lets you get feedback from a large number of users faster than any other environment (except possibly Ajax only). I started Flash programming a little over two years ago. In my first three months I learned AS3 and wrote a TD-style game that was eventually played by over a million people. During beta testing and after release I was getting constant feedback and tweaking the game mechanics and interface with multiple "releases" a day.
While not every game out there gets that much play, with Flash it is much easier to make something and have a large number of people actually play it and tell you what they like and what they don't. Learning how to make good games is harder than learning a different programming language.
A:
To give a comparison of the two:
Action Script is useable only in Flash games (mostly run through web browser), which may be fun for some time, but it limits what you can do. On the other hand, it is probably the best way for developing web-based games.
C# and .NET allows you to write all sorts of different games (and is also more generally useful language in case you wanted to switch from game development to some other field, including web site development and various business applications). Regarding games, you can use it on:
Web based games (similar to Flash) using Silverlight
Desktop/XBox/Zune games using XNA Game Studio
iPhone games using MonoTouch (although there are some licensing issues recently)
By learning C#, you'll also learn .NET Framework (in general), which is (I think) a useful knowledge that you can benefit from in many situations (e.g. when looking for a job :-))
A:
Why not learn both? I think programming a good game is harder than adapting to a new programming environment.
Also, if you get into Flash game dev, you'll probably want to check out Flixel.
A:
C# is the nicer language (although AS3 and C# are similar) and has a wider range of uses than Flash but since you mentioned games only I would tend to say start with ActionScript 3.0 then move to C#.
Firstly we can ignore the fact that C# is useful for writing business apps since that is not relevant to this question.
C# offers game programming via XNA, SilverLight, and Unity3D compared to ActionScript 3.0 with Flash.
So why do I recommend AS3 to start with? Firstly 2D games are where you should start off and I think this is where Flash excels. The development lifecycle of 2D games is much shorter and tend to produce better gameplay. A lot of indie 3D games suck since they fall short of realising what they started out developing. It is relativly simple to get a 2D game up and running and there is a lot of game engines, physics engines and tutorials available. It is also the platform of choice for artists (that can make all the lovely looking levels, characters etc). Second, the flash platform is the most accessible to your audience. No point making a great game that people never play. Third, AS3 is faily simple to come to terms with.
From my experience the web games that I come across that I think are noteworthy tend to be made in Flash. Checkout Scary Girl and Machinarium.
For 3D or anything that you need the power of the GPU then C# with XNA or Unity3D is what you should be looking at.
I will add that if you are interested in very fast action style 2D games then avoid Flash.
| Learn Actionscript 3.0+Flash Vs. C# | I have a background in python and I'm looking for a new language. I am almost only intrested in making games.
I have come to 2 languages. C# and Action Script.
C# because Microsoft allows you to make Indie XBLA games programmed in C# ONLY.
Action Script so I can make flash games for new grounds and ect.
What do you think is better to learn in the long run?
| [
"I would say C#. You'll learn the basics and then be able to write games for the Desktop (XNA), XBox (XNA), Mobile Devices (XNA and XNA Touch for the iPhone), the Web (via Silverlight), etc.\nFlash only gets you limited exposure to each.\n",
"I have zero experience with C#, but I'll speak to AS3/Flash's #1 advantage:\nFor learning game development, Flash lets you make games very quickly, but more importantly lets you get feedback from a large number of users faster than any other environment (except possibly Ajax only). I started Flash programming a little over two years ago. In my first three months I learned AS3 and wrote a TD-style game that was eventually played by over a million people. During beta testing and after release I was getting constant feedback and tweaking the game mechanics and interface with multiple \"releases\" a day.\nWhile not every game out there gets that much play, with Flash it is much easier to make something and have a large number of people actually play it and tell you what they like and what they don't. Learning how to make good games is harder than learning a different programming language.\n",
"To give a comparison of the two:\nAction Script is useable only in Flash games (mostly run through web browser), which may be fun for some time, but it limits what you can do. On the other hand, it is probably the best way for developing web-based games.\nC# and .NET allows you to write all sorts of different games (and is also more generally useful language in case you wanted to switch from game development to some other field, including web site development and various business applications). Regarding games, you can use it on:\n\nWeb based games (similar to Flash) using Silverlight\nDesktop/XBox/Zune games using XNA Game Studio\niPhone games using MonoTouch (although there are some licensing issues recently)\n\nBy learning C#, you'll also learn .NET Framework (in general), which is (I think) a useful knowledge that you can benefit from in many situations (e.g. when looking for a job :-))\n",
"Why not learn both? I think programming a good game is harder than adapting to a new programming environment.\nAlso, if you get into Flash game dev, you'll probably want to check out Flixel.\n",
"C# is the nicer language (although AS3 and C# are similar) and has a wider range of uses than Flash but since you mentioned games only I would tend to say start with ActionScript 3.0 then move to C#.\nFirstly we can ignore the fact that C# is useful for writing business apps since that is not relevant to this question. \nC# offers game programming via XNA, SilverLight, and Unity3D compared to ActionScript 3.0 with Flash. \nSo why do I recommend AS3 to start with? Firstly 2D games are where you should start off and I think this is where Flash excels. The development lifecycle of 2D games is much shorter and tend to produce better gameplay. A lot of indie 3D games suck since they fall short of realising what they started out developing. It is relativly simple to get a 2D game up and running and there is a lot of game engines, physics engines and tutorials available. It is also the platform of choice for artists (that can make all the lovely looking levels, characters etc). Second, the flash platform is the most accessible to your audience. No point making a great game that people never play. Third, AS3 is faily simple to come to terms with.\nFrom my experience the web games that I come across that I think are noteworthy tend to be made in Flash. Checkout Scary Girl and Machinarium.\nFor 3D or anything that you need the power of the GPU then C# with XNA or Unity3D is what you should be looking at.\nI will add that if you are interested in very fast action style 2D games then avoid Flash.\n"
] | [
2,
2,
0,
0,
0
] | [] | [] | [
"actionscript_3",
"c#",
"python"
] | stackoverflow_0002792425_actionscript_3_c#_python.txt |
Q:
Installing PySide - OSX
Anyone had success installing and using PySide on OSX? I am following the install instructions on the PySide site, though I'm running into issues building the API Extractor. I run cmake on the CMakeLists.txt file inside the api extractor dir and:
This error is thrown-
CMake Error at /Applications/CMake 2.8-0.app/Contents/share/cmake-2.8/Modules/FindBoost.cmake:894 (message):
Unable to find the requested Boost libraries.
Unable to find the Boost header files. Please set BOOST_ROOT to the root
directory containing Boost or BOOST_INCLUDEDIR to the directory containing
Boost's headers.
Call Stack (most recent call first):
CMakeLists.txt:5 (find_package)
I am new to building source w/ cmake and I'm not event really sure what Boost is. Any light you might shed on the set up process would be great.
Thanks
A:
You may want to check the newest release of PySide, out very recently, I believe the dependency on the Boost libraries has been removed.
A:
It's a set of quite widespread C++ libraries, they're probably needed by PySide, even though I've never tried it.
Download them from there:
http://sourceforge.net/projects/boost/files/boost/1.42.0/
Otherwise, you can install them from macports: http://www.macports.org once you've installed macports, just run "sudo port install boost". Unluckily, pyside itself doesn't seem to be in macports yet.
| Installing PySide - OSX | Anyone had success installing and using PySide on OSX? I am following the install instructions on the PySide site, though I'm running into issues building the API Extractor. I run cmake on the CMakeLists.txt file inside the api extractor dir and:
This error is thrown-
CMake Error at /Applications/CMake 2.8-0.app/Contents/share/cmake-2.8/Modules/FindBoost.cmake:894 (message):
Unable to find the requested Boost libraries.
Unable to find the Boost header files. Please set BOOST_ROOT to the root
directory containing Boost or BOOST_INCLUDEDIR to the directory containing
Boost's headers.
Call Stack (most recent call first):
CMakeLists.txt:5 (find_package)
I am new to building source w/ cmake and I'm not event really sure what Boost is. Any light you might shed on the set up process would be great.
Thanks
| [
"You may want to check the newest release of PySide, out very recently, I believe the dependency on the Boost libraries has been removed.\n",
"It's a set of quite widespread C++ libraries, they're probably needed by PySide, even though I've never tried it.\nDownload them from there:\nhttp://sourceforge.net/projects/boost/files/boost/1.42.0/\nOtherwise, you can install them from macports: http://www.macports.org once you've installed macports, just run \"sudo port install boost\". Unluckily, pyside itself doesn't seem to be in macports yet.\n"
] | [
4,
2
] | [] | [] | [
"c++",
"cmake",
"pyside",
"python"
] | stackoverflow_0002196300_c++_cmake_pyside_python.txt |
Q:
Unit testing aspect-oriented features
I'd like to know what would you propose as the best way to unit test aspect-oriented application features (well, perhaps that's not the best name, but it's the best I was able to come up with :-) ) such as logging or security?
These things are sort of omni-present in the application, so how to test them properly?
E.g. say that I'm writing a Cherrypy web server in Python. I can use a decorator to check whether the logged-in user has the permission to access a given page. But then I'd need to write a test for every page to see whether it works oK (or more like to see that I had not forgotten to check security perms for that page).
This could maybe (emphasis on maybe) be bearable if logging and/or security were implemented during the web server "normal business implementation". However, security and logging usually tend to be added to the app as an afterthough (or maybe that's just my experience, I'm usually given a server and then asked to implement security model :-) ).
Any thoughts on this are very welcome. I have currently 'solved' this issue by, well - not testing this at all.
Thanks.
A:
IMHO, the way of testing users permissions to the pages depends on the design of your app and design of the framework you're using.
Generally, it's probably enough to cover your permission checker decorator with unit tests to make sure it always works as expected and then write a test that cycles through your 'views' (or whatever term cherrypy uses, haven't used it for a very long time) and just check if these functions are decorated with appropriate decorator.
As for logging it's not quite clear what you want test specifically. Anyway, why isn't it possible to stub the logging functionality and check what's going on there?
A:
Well... let's see. In my opinion you are testing three different things here (sorry for the "Java AOP jargon"):
the features implemented by the interceptors (i.e. the methods that implement the functions activated at the cutpoints)
the coverage of the filters (i.e. whether the intended cutpoints are activated correctly or not)
the interaction between the cutpoints and the interceptors (with the side effects)
You are unit testing (strictly speaking) if you can handle these three layers separatedly. You can actually unit test the first; you can use a coverage tool and some skeleton crew application with mock objects to test the second; but the third is not exactly unit testing, so you may have to setup a test environment, design an end-to-end test and write some scripts to input data in your application and gather the results (if it was a web app you could use Selenium, for example).
A:
My answer is for the specific example you give, not for the possible problems with bolted-on security. Decorators are just regular functions, and you can test them as such. For instance:
# ... inside included module ...
def require_admin(function):
if (admin):
return function
else:
return None
@require_admin
def func1(arg1, arg2):
pass
# ... inside unit test ...
def test_require_admin(self):
admin = False
f = lambda x: x
g = require_admin(f)
assert_equal(g, None)
admin = True
g = require_admin(f)
assert_equal(g, f)
Note: this is a really terrible way to do a security check, but it gets the point across about testing decorators. That's one of the nice things about Python: it's REALLY consistent. The following expressions are equivalent:
@g
def f(x):
return x
and
def f(x):
return x
f = g(f)
| Unit testing aspect-oriented features | I'd like to know what would you propose as the best way to unit test aspect-oriented application features (well, perhaps that's not the best name, but it's the best I was able to come up with :-) ) such as logging or security?
These things are sort of omni-present in the application, so how to test them properly?
E.g. say that I'm writing a Cherrypy web server in Python. I can use a decorator to check whether the logged-in user has the permission to access a given page. But then I'd need to write a test for every page to see whether it works oK (or more like to see that I had not forgotten to check security perms for that page).
This could maybe (emphasis on maybe) be bearable if logging and/or security were implemented during the web server "normal business implementation". However, security and logging usually tend to be added to the app as an afterthough (or maybe that's just my experience, I'm usually given a server and then asked to implement security model :-) ).
Any thoughts on this are very welcome. I have currently 'solved' this issue by, well - not testing this at all.
Thanks.
| [
"IMHO, the way of testing users permissions to the pages depends on the design of your app and design of the framework you're using.\nGenerally, it's probably enough to cover your permission checker decorator with unit tests to make sure it always works as expected and then write a test that cycles through your 'views' (or whatever term cherrypy uses, haven't used it for a very long time) and just check if these functions are decorated with appropriate decorator.\nAs for logging it's not quite clear what you want test specifically. Anyway, why isn't it possible to stub the logging functionality and check what's going on there?\n",
"Well... let's see. In my opinion you are testing three different things here (sorry for the \"Java AOP jargon\"):\n\nthe features implemented by the interceptors (i.e. the methods that implement the functions activated at the cutpoints)\nthe coverage of the filters (i.e. whether the intended cutpoints are activated correctly or not)\nthe interaction between the cutpoints and the interceptors (with the side effects)\n\nYou are unit testing (strictly speaking) if you can handle these three layers separatedly. You can actually unit test the first; you can use a coverage tool and some skeleton crew application with mock objects to test the second; but the third is not exactly unit testing, so you may have to setup a test environment, design an end-to-end test and write some scripts to input data in your application and gather the results (if it was a web app you could use Selenium, for example).\n",
"My answer is for the specific example you give, not for the possible problems with bolted-on security. Decorators are just regular functions, and you can test them as such. For instance:\n# ... inside included module ...\ndef require_admin(function):\n if (admin):\n return function\n else:\n return None\n\n@require_admin\ndef func1(arg1, arg2):\n pass\n\n# ... inside unit test ...\ndef test_require_admin(self):\n admin = False\n f = lambda x: x\n g = require_admin(f)\n assert_equal(g, None)\n\n admin = True\n g = require_admin(f)\n assert_equal(g, f)\n\nNote: this is a really terrible way to do a security check, but it gets the point across about testing decorators. That's one of the nice things about Python: it's REALLY consistent. The following expressions are equivalent:\n@g\ndef f(x):\n return x\n\nand\ndef f(x):\n return x\nf = g(f)\n\n"
] | [
1,
0,
0
] | [] | [] | [
"aop",
"python",
"unit_testing"
] | stackoverflow_0002401789_aop_python_unit_testing.txt |
Q:
Lucene: Fastest way to return the document occurance of a phrase?
I am trying to use Lucene (actually PyLucene!) to find out how many documents contain my exact phrase. My code currently looks like this... but it runs rather slow. Does anyone know a faster way to return document counts?
phraseList = ["some phrase 1", "some phrase 2"] #etc, a list of phrases...
countsearcher = IndexSearcher(SimpleFSDirectory(File(STORE_DIR)), True)
analyzer = StandardAnalyzer(Version.LUCENE_CURRENT)
for phrase in phraseList:
query = QueryParser(Version.LUCENE_CURRENT, "contents", analyzer).parse("\"" + phrase + "\"")
scoreDocs = countsearcher.search(query, 200).scoreDocs
print "count is: " + str(len(scoreDocs))
A:
Typically, writing custom hit collector is the fastest way to count the number of hits using a bitset as illustrated in javadoc of Collector.
Other method is to get TopDocs with number of results specified as one.
TopDocs topDocs = searcher.search(query, filter, 1);
topDocs.totalHits will give you the total number of results. I'm not sure if this is as fast as it involves calculating scores, which is skipped in aforementioned method.
These solutions are applicable for Java. You have to check equivalent technique in Python.
| Lucene: Fastest way to return the document occurance of a phrase? | I am trying to use Lucene (actually PyLucene!) to find out how many documents contain my exact phrase. My code currently looks like this... but it runs rather slow. Does anyone know a faster way to return document counts?
phraseList = ["some phrase 1", "some phrase 2"] #etc, a list of phrases...
countsearcher = IndexSearcher(SimpleFSDirectory(File(STORE_DIR)), True)
analyzer = StandardAnalyzer(Version.LUCENE_CURRENT)
for phrase in phraseList:
query = QueryParser(Version.LUCENE_CURRENT, "contents", analyzer).parse("\"" + phrase + "\"")
scoreDocs = countsearcher.search(query, 200).scoreDocs
print "count is: " + str(len(scoreDocs))
| [
"Typically, writing custom hit collector is the fastest way to count the number of hits using a bitset as illustrated in javadoc of Collector. \nOther method is to get TopDocs with number of results specified as one.\nTopDocs topDocs = searcher.search(query, filter, 1);\n\ntopDocs.totalHits will give you the total number of results. I'm not sure if this is as fast as it involves calculating scores, which is skipped in aforementioned method.\nThese solutions are applicable for Java. You have to check equivalent technique in Python.\n"
] | [
6
] | [] | [] | [
"lucene",
"python",
"search"
] | stackoverflow_0002796660_lucene_python_search.txt |
Q:
How to add packages into .exe file using py2exe?
I have an app with two packages..
My setup.py is like this:
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "SoundLog.py"}],
zipfile = None,
)
After creating the .exe I have to put the packages in the same folder as the .exe file.
How can I include them in the .exe?
Thanks in advance!
A:
I was searching for .py files in a folder to see how many there were in the code.
That was why I needed that folder!
The code that I presented in the question is correct!
| How to add packages into .exe file using py2exe? | I have an app with two packages..
My setup.py is like this:
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "SoundLog.py"}],
zipfile = None,
)
After creating the .exe I have to put the packages in the same folder as the .exe file.
How can I include them in the .exe?
Thanks in advance!
| [
"I was searching for .py files in a folder to see how many there were in the code.\nThat was why I needed that folder!\nThe code that I presented in the question is correct!\n"
] | [
0
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0002753369_py2exe_python.txt |
Q:
Python decorator question
decorator 1:
def dec(f):
def wrap(obj, *args, **kwargs):
f(obj, *args,**kwargs)
return wrap
decorator 2:
class dec:
def __init__(self, f):
self.f = f
def __call__(self, obj, *args, **kwargs):
self.f(obj, *args, **kwargs)
A sample class,
class Test:
@dec
def disp(self, *args, **kwargs):
print(*args,**kwargs)
The follwing code works with decorator 1 but not with decorator 2.
a = Test()
a.disp("Message")
I dont understand why decorator 2 is not working here. Can someone help me with this?
A:
When you decorate with the dec class, your disp method is no more an instance method, but an instance of class dec. So a.disp is just a plain member of Test, which happens to be callable because it has a __call__ method, and in the self passed as the first argument of its f instance is "Message" (it is by no way bound to the "test" instance).
with the decorator function:
a = Test()
print a.disp
# disp <bound method Test.wrap of <__main__.Test instance at 0xb739df0c>>
with the decorator class:
a = Test()
print a.disp
# disp <__main__.dec instance at 0xb739deec>
edit
That should answer your question far better and clearer than I did:
http://irrepupavel.com/documents/python/instancemethod/
| Python decorator question | decorator 1:
def dec(f):
def wrap(obj, *args, **kwargs):
f(obj, *args,**kwargs)
return wrap
decorator 2:
class dec:
def __init__(self, f):
self.f = f
def __call__(self, obj, *args, **kwargs):
self.f(obj, *args, **kwargs)
A sample class,
class Test:
@dec
def disp(self, *args, **kwargs):
print(*args,**kwargs)
The follwing code works with decorator 1 but not with decorator 2.
a = Test()
a.disp("Message")
I dont understand why decorator 2 is not working here. Can someone help me with this?
| [
"When you decorate with the dec class, your disp method is no more an instance method, but an instance of class dec. So a.disp is just a plain member of Test, which happens to be callable because it has a __call__ method, and in the self passed as the first argument of its f instance is \"Message\" (it is by no way bound to the \"test\" instance).\nwith the decorator function:\na = Test()\nprint a.disp\n# disp <bound method Test.wrap of <__main__.Test instance at 0xb739df0c>>\n\nwith the decorator class:\na = Test()\nprint a.disp\n# disp <__main__.dec instance at 0xb739deec>\n\nedit\nThat should answer your question far better and clearer than I did:\nhttp://irrepupavel.com/documents/python/instancemethod/\n"
] | [
2
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002797070_decorator_python.txt |
Q:
Processing forms that generate many rows in DB
I'm wondering what the best approach to take here is. I've got a form that people use to register for a class and a lot of times the manager of a company will register multiple people for the class at the same time. Presently, they'd have to go through the registration process multiple times and resubmit the form once for every person they want to register.
What I want to do is give the user a form that has a single <input/> for one person to register with, along with all the other fields they'll need to fill out (Email, phone number, etc); if they want to add more people, they'll be able to press a button and a new <input/> will be generated. This part I know how to do, but I'm including it to best describe what I'm aiming to do.
The part I don't know how to approach is processing that data the form submits, I need some way of making a new row in the Registrant table for every <input/> that's added and include the same contact information (phone, email, etc) as the first row with that row. For the record, I'm using the Django framework for my back-end code.
What's the best approach here? Should it just POST the form x times for x people, or is there a less "brute force" way of handling this?
A:
Django includes FormSet for dealing with exactly these challenges. Using a FormSet you can create multiple forms for creating or updating information. There's even possible to generate the FormSets from a Model. http://docs.djangoproject.com/en/dev/topics/forms/formsets/ and http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1 are great resources.
Now, for creating more forms on the fly, you need some javascript magic. I've done this on work projects using jQuery which made it a lot simpler. The basic idea is create a new form with the correct inputs and change the hidden metadata in the formset form so it will now how many forms to process. The admin implements this when using multiple inline forms so I suggest looking there for code as it is a bit tricky to get right.
| Processing forms that generate many rows in DB | I'm wondering what the best approach to take here is. I've got a form that people use to register for a class and a lot of times the manager of a company will register multiple people for the class at the same time. Presently, they'd have to go through the registration process multiple times and resubmit the form once for every person they want to register.
What I want to do is give the user a form that has a single <input/> for one person to register with, along with all the other fields they'll need to fill out (Email, phone number, etc); if they want to add more people, they'll be able to press a button and a new <input/> will be generated. This part I know how to do, but I'm including it to best describe what I'm aiming to do.
The part I don't know how to approach is processing that data the form submits, I need some way of making a new row in the Registrant table for every <input/> that's added and include the same contact information (phone, email, etc) as the first row with that row. For the record, I'm using the Django framework for my back-end code.
What's the best approach here? Should it just POST the form x times for x people, or is there a less "brute force" way of handling this?
| [
"Django includes FormSet for dealing with exactly these challenges. Using a FormSet you can create multiple forms for creating or updating information. There's even possible to generate the FormSets from a Model. http://docs.djangoproject.com/en/dev/topics/forms/formsets/ and http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1 are great resources.\nNow, for creating more forms on the fly, you need some javascript magic. I've done this on work projects using jQuery which made it a lot simpler. The basic idea is create a new form with the correct inputs and change the hidden metadata in the formset form so it will now how many forms to process. The admin implements this when using multiple inline forms so I suggest looking there for code as it is a bit tricky to get right.\n"
] | [
4
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0002797184_django_forms_python.txt |
Q:
Django - partially validating form
I'm new to Django, trying to process some forms.
I have this form for entering information (creating a new ad) in one template:
class Ad(models.Model):
...
category = models.CharField("Category",max_length=30, choices=CATEGORIES)
sub_category = models.CharField("Subcategory",max_length=4, choices=SUBCATEGORIES)
location = models.CharField("Location",max_length=30, blank=True)
title = models.CharField("Title",max_length=50)
...
-----------------------------------
class AdForm(forms.ModelForm):
class Meta:
model = Ad
...
I validate it with "is_valid()" and all is fine.
Basically for the second validation (another template) I want to validate only against "category" and "sub_category":
In another template (with another method from views.py), I want to use 2 fields from the same form ("category" and "sub_category") for filtering information - and now the "is_valid()" method would not work correctly, cause it validates the entire form, and I need to validate only 2 fields. I have tried with the following:
...
if request.method == 'POST': # If a filter for data has been submitted:
form = AdForm(request.POST)
try:
form = form.clean()
category = form.category
sub_category = form.sub_category
latest_ads_list = Ad.objects.filter(category=category)
except ValidationError:
latest_ads_list = Ad.objects.all().order_by('pub_date')
else:
latest_ads_list = Ad.objects.all().order_by('pub_date')
form = AdForm()
...
but it doesn't work.
EDIT:
Solved it by adding:
class FilterForm(forms.ModelForm):
class Meta:
model = Ad
fields = ('category', 'sub_category')
and validating this form with "is_valid()" etc., which worked just fine.
A:
Have you tried subclassing AdForm and modifying the fields in the inner Meta class? Something like this:
class AdFormLite(AdForm):
class Meta:
fields = ['category', 'sub_category']
From the documentation for ModelForm on changing the order of fields:
The fields attribute defines the
subset of model fields that will be
rendered, and the order in which they
will be rendered.will be rendered.
| Django - partially validating form | I'm new to Django, trying to process some forms.
I have this form for entering information (creating a new ad) in one template:
class Ad(models.Model):
...
category = models.CharField("Category",max_length=30, choices=CATEGORIES)
sub_category = models.CharField("Subcategory",max_length=4, choices=SUBCATEGORIES)
location = models.CharField("Location",max_length=30, blank=True)
title = models.CharField("Title",max_length=50)
...
-----------------------------------
class AdForm(forms.ModelForm):
class Meta:
model = Ad
...
I validate it with "is_valid()" and all is fine.
Basically for the second validation (another template) I want to validate only against "category" and "sub_category":
In another template (with another method from views.py), I want to use 2 fields from the same form ("category" and "sub_category") for filtering information - and now the "is_valid()" method would not work correctly, cause it validates the entire form, and I need to validate only 2 fields. I have tried with the following:
...
if request.method == 'POST': # If a filter for data has been submitted:
form = AdForm(request.POST)
try:
form = form.clean()
category = form.category
sub_category = form.sub_category
latest_ads_list = Ad.objects.filter(category=category)
except ValidationError:
latest_ads_list = Ad.objects.all().order_by('pub_date')
else:
latest_ads_list = Ad.objects.all().order_by('pub_date')
form = AdForm()
...
but it doesn't work.
EDIT:
Solved it by adding:
class FilterForm(forms.ModelForm):
class Meta:
model = Ad
fields = ('category', 'sub_category')
and validating this form with "is_valid()" etc., which worked just fine.
| [
"Have you tried subclassing AdForm and modifying the fields in the inner Meta class? Something like this:\nclass AdFormLite(AdForm):\n class Meta:\n fields = ['category', 'sub_category']\n\nFrom the documentation for ModelForm on changing the order of fields:\n\nThe fields attribute defines the\n subset of model fields that will be\n rendered, and the order in which they\n will be rendered.will be rendered. \n\n"
] | [
2
] | [] | [] | [
"django",
"python",
"validation"
] | stackoverflow_0002796982_django_python_validation.txt |
Q:
Python using methods from other classes
If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?
A:
There are two options:
instanciate an object in your class, then call the desired method on it
use @classmethod to turn a function into a class method
Example:
class A(object):
def a1(self):
""" This is an instance method. """
print "Hello from an instance of A"
@classmethod
def a2(cls):
""" This a classmethod. """
print "Hello from class A"
class B(object):
def b1(self):
print A().a1() # => prints 'Hello from an instance of A'
print A.a2() # => 'Hello from class A'
Or use inheritance, if appropriate:
class A(object):
def a1(self):
print "Hello from Superclass"
class B(A):
pass
B().a1() # => prints 'Hello from Superclass'
A:
There are several approaches:
Inheritance
Delegation
Super-sneaky delegation
The following examples use each for sharing a function that prints a member.
Inheritance
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(Common):
def __init__(self):
Common.__init__(self,"Alpha")
class Bravo(Common):
def __init__(self):
Common.__init__(self,"Bravo")
Delegation
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(object):
def __init__(self):
self.common = Common("Alpha")
def sharedMethod(self):
self.common.sharedMethod()
class Bravo(object):
def __init__(self):
self.common = Common("Bravo")
def sharedMethod(self):
self.common.sharedMethod()
Super-sneaky Delegation
This solution is based off of the fact that there is nothing special about Python member functions; you can use any function or callable object so long as the first parameter is interpreted as the instance of the class.
def commonPrint(self):
print self.x
class Alpha(object):
def __init__(self):
self.x = "Alpha"
sharedMethod = commonPrint
class Bravo(object):
def __init__(self):
self.x = "Bravo"
sharedMethod = commonPrint
Or, a similarly sneaky way of achieving delegation is to use a callable object:
class Printable(object):
def __init__(self,x):
self.x = x
def __call__(self):
print self.x
class Alpha(object):
def __init__(self):
self.sharedMethod = Printable("Alpha")
class Bravo(object):
def __init__(self):
self.sharedMethod = Printable("Bravo")
A:
you create a class from which both classes inherit.
There is multiple inheritance, so if they already have a parent it's not a problem.
class master ():
def stuff (self):
pass
class first (master):
pass
class second (master):
pass
ichi=first()
ni=second()
ichi.stuff()
ni.stuff()
| Python using methods from other classes | If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?
| [
"There are two options:\n\ninstanciate an object in your class, then call the desired method on it\nuse @classmethod to turn a function into a class method\n\nExample:\nclass A(object):\n def a1(self):\n \"\"\" This is an instance method. \"\"\"\n print \"Hello from an instance of A\"\n\n @classmethod\n def a2(cls):\n \"\"\" This a classmethod. \"\"\"\n print \"Hello from class A\"\n\nclass B(object):\n def b1(self):\n print A().a1() # => prints 'Hello from an instance of A'\n print A.a2() # => 'Hello from class A'\n\nOr use inheritance, if appropriate:\nclass A(object):\n def a1(self):\n print \"Hello from Superclass\"\n\nclass B(A):\n pass\n\nB().a1() # => prints 'Hello from Superclass'\n\n",
"There are several approaches:\n\nInheritance\nDelegation\nSuper-sneaky delegation\n\nThe following examples use each for sharing a function that prints a member.\nInheritance\nclass Common(object):\n def __init__(self,x):\n self.x = x\n def sharedMethod(self):\n print self.x\n\nclass Alpha(Common):\n def __init__(self):\n Common.__init__(self,\"Alpha\")\n\nclass Bravo(Common):\n def __init__(self):\n Common.__init__(self,\"Bravo\")\n\nDelegation\nclass Common(object):\n def __init__(self,x):\n self.x = x\n def sharedMethod(self):\n print self.x\n\nclass Alpha(object):\n def __init__(self):\n self.common = Common(\"Alpha\")\n def sharedMethod(self):\n self.common.sharedMethod()\n\nclass Bravo(object):\n def __init__(self):\n self.common = Common(\"Bravo\")\n def sharedMethod(self):\n self.common.sharedMethod()\n\nSuper-sneaky Delegation\nThis solution is based off of the fact that there is nothing special about Python member functions; you can use any function or callable object so long as the first parameter is interpreted as the instance of the class.\ndef commonPrint(self):\n print self.x\n\nclass Alpha(object):\n def __init__(self):\n self.x = \"Alpha\"\n sharedMethod = commonPrint\n\nclass Bravo(object):\n def __init__(self):\n self.x = \"Bravo\"\n sharedMethod = commonPrint\n\nOr, a similarly sneaky way of achieving delegation is to use a callable object:\nclass Printable(object):\n def __init__(self,x):\n self.x = x\n def __call__(self):\n print self.x\n\nclass Alpha(object):\n def __init__(self):\n self.sharedMethod = Printable(\"Alpha\")\n\nclass Bravo(object):\n def __init__(self):\n self.sharedMethod = Printable(\"Bravo\")\n\n",
"you create a class from which both classes inherit.\nThere is multiple inheritance, so if they already have a parent it's not a problem.\nclass master ():\n def stuff (self):\n pass\n\nclass first (master):\n pass\n\n\nclass second (master):\n pass\n\n\nichi=first()\nni=second()\n\nichi.stuff()\nni.stuff()\n\n"
] | [
45,
30,
7
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0002797139_class_methods_python.txt |
Q:
Python references
Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
A:
The best explanation I ever read is here:
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
A:
Because integers are immutable, while list are mutable. You can see from the syntax. In x = x + 1 you are actually assigning a new value to x (it is alone on the LHS). In x[0] = 4, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to x.__setitem__(0, 4), which is obviously changing the original object, not creating a new one.
A:
If you do y = x, y and x are the reference to the same object. But integers are immutable and when you do x + 1, the new integer is created:
>>> x = 1
>>> id(x)
135720760
>>> x += 1
>>> id(x)
135720748
>>> x -= 1
>>> id(x)
135720760
When you have a mutable object (e.g. list, classes defined by yourself), x is changed whenever y is changed, because they point to a single object.
A:
That's because when you have a list or a tuple in python you create a reference to an object.
When you say that y = x you reference to the same object with y as x does.
So when you edit the object of x y changes with it.
A:
As the previous answers said the code you wrote assigns the same object to different names such aliases.
If you want to assign a copy of the original list to the new variable (object actually)
use this solution:
>>> x=[1,2,3]
>>> y=x[:] #this makes a new list
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
>>> x[0]=4
>>> x
[4, 2, 3]
>>> y
[1, 2, 3]
| Python references | Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
| [
"The best explanation I ever read is here:\nhttp://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables \n",
"Because integers are immutable, while list are mutable. You can see from the syntax. In x = x + 1 you are actually assigning a new value to x (it is alone on the LHS). In x[0] = 4, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to x.__setitem__(0, 4), which is obviously changing the original object, not creating a new one.\n",
"If you do y = x, y and x are the reference to the same object. But integers are immutable and when you do x + 1, the new integer is created:\n>>> x = 1\n>>> id(x)\n135720760\n>>> x += 1\n>>> id(x)\n135720748\n>>> x -= 1\n>>> id(x)\n135720760\n\nWhen you have a mutable object (e.g. list, classes defined by yourself), x is changed whenever y is changed, because they point to a single object.\n",
"That's because when you have a list or a tuple in python you create a reference to an object.\nWhen you say that y = x you reference to the same object with y as x does.\nSo when you edit the object of x y changes with it.\n",
"As the previous answers said the code you wrote assigns the same object to different names such aliases.\nIf you want to assign a copy of the original list to the new variable (object actually)\nuse this solution:\n>>> x=[1,2,3]\n>>> y=x[:] #this makes a new list\n>>> x\n[1, 2, 3]\n>>> y\n[1, 2, 3]\n>>> x[0]=4\n>>> x\n[4, 2, 3]\n>>> y\n[1, 2, 3]\n\n"
] | [
9,
8,
4,
0,
0
] | [] | [] | [
"immutability",
"python"
] | stackoverflow_0002797114_immutability_python.txt |
Q:
Why is Python 3.1 throwing a SyntaxError when printing after loop?
I'm trying to run this snippet in Python 3.1 console and I'm getting SyntaxError:
>>> while True:
... a=5
... if a<6:
... break
... print("hello")
File "<stdin>", line 5
print("hello")
^
SyntaxError: invalid syntax
>>>
(This is just shortened code to make a point.)
Am I missing something? Is there some other Magic I don't know about?
A:
You have to input an empty line into the REPL to complete the current block before you can enter a new, unindented line of code.
A:
It's working, if you put the whole thing in a function:
def test():
while True:
a=5
if a<6:
break
print("hello")
If you try to do it outside a function (just in the interpreter), it does not know how to evaulate the whole thing, since it can only handle one statement at a time in the interpreter. Your while loop is such a statement, and your print stuff is such a statement, such you have two statements, but the interpreter takes only one.
| Why is Python 3.1 throwing a SyntaxError when printing after loop? | I'm trying to run this snippet in Python 3.1 console and I'm getting SyntaxError:
>>> while True:
... a=5
... if a<6:
... break
... print("hello")
File "<stdin>", line 5
print("hello")
^
SyntaxError: invalid syntax
>>>
(This is just shortened code to make a point.)
Am I missing something? Is there some other Magic I don't know about?
| [
"You have to input an empty line into the REPL to complete the current block before you can enter a new, unindented line of code.\n",
"It's working, if you put the whole thing in a function:\ndef test():\n while True:\n a=5\n if a<6:\n break\n print(\"hello\")\n\nIf you try to do it outside a function (just in the interpreter), it does not know how to evaulate the whole thing, since it can only handle one statement at a time in the interpreter. Your while loop is such a statement, and your print stuff is such a statement, such you have two statements, but the interpreter takes only one.\n"
] | [
9,
7
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0002797364_python_syntax_error.txt |
Q:
How to generate random html document
I'd like to generate completely random piece of html source, possibly from a grammar. I want to do this in python but I'm not sure how to proceed -- is there a library that takes a grammar and just randomly follows its rules, printing the path?
Ideas?
A:
import urllib
html = urllib.urlopen('http://random.yahoo.com/bin/ryl').read()
I think that pulling a random page is much easier to implement and will be far more random than anything you could program yourself. Any program designed to produce random pages will still have to adhere to whatever rules defining the structure of html. Since humans are much better and breaking rules than machines, a random page from the web is more likely to contain structures you won't get from a randomizer.
You don't have to use yahoo, there are probably other random link generators, or you could build your own.
A:
It's quite easy to roll your own random html generator that looks very much like a top-down parser. Here's a base!
def RandomHtml():
yield '<html><body>'
yield '<body>'
yield RandomBody()
yield '</body></html>'
def RandomBody():
yield RandomSection()
if random.randrange(2) == 0:
yield RandomBody()
def RandomSection():
yield '<h1>'
yield RandomSentence()
yield '</h1>'
sentences = random.randrange(5, 20)
for _ in xrange(sentences):
yield RandomSentence()
def RandomSentence():
words = random.randrange(5, 15)
yield (' '.join(RandomWord() for _ in xrange(words)) + '.').capitalize()
def RandomWord():
chars = random.randrange(2, 10)
return ''.join(random.choice(string.ascii_lowercase) for _ in xrange(chars))
def Output(generator):
if isinstance(generator, str):
print generator
else:
for g in generator: Output(g)
Output(RandomHtml())
| How to generate random html document | I'd like to generate completely random piece of html source, possibly from a grammar. I want to do this in python but I'm not sure how to proceed -- is there a library that takes a grammar and just randomly follows its rules, printing the path?
Ideas?
| [
"import urllib\n\nhtml = urllib.urlopen('http://random.yahoo.com/bin/ryl').read()\n\nI think that pulling a random page is much easier to implement and will be far more random than anything you could program yourself. Any program designed to produce random pages will still have to adhere to whatever rules defining the structure of html. Since humans are much better and breaking rules than machines, a random page from the web is more likely to contain structures you won't get from a randomizer.\nYou don't have to use yahoo, there are probably other random link generators, or you could build your own.\n",
"It's quite easy to roll your own random html generator that looks very much like a top-down parser. Here's a base!\ndef RandomHtml():\n yield '<html><body>'\n yield '<body>'\n yield RandomBody()\n yield '</body></html>'\n\ndef RandomBody():\n yield RandomSection()\n if random.randrange(2) == 0:\n yield RandomBody()\n\ndef RandomSection():\n yield '<h1>'\n yield RandomSentence()\n yield '</h1>'\n sentences = random.randrange(5, 20)\n for _ in xrange(sentences):\n yield RandomSentence()\n\ndef RandomSentence():\n words = random.randrange(5, 15)\n yield (' '.join(RandomWord() for _ in xrange(words)) + '.').capitalize()\n\ndef RandomWord():\n chars = random.randrange(2, 10)\n return ''.join(random.choice(string.ascii_lowercase) for _ in xrange(chars))\n\ndef Output(generator):\n if isinstance(generator, str):\n print generator\n else:\n for g in generator: Output(g)\n\nOutput(RandomHtml())\n\n"
] | [
7,
3
] | [] | [] | [
"grammar",
"html",
"python",
"random"
] | stackoverflow_0002795134_grammar_html_python_random.txt |
Q:
Python Finding all packages inside a package, even when in an egg
Given a Python package, how can I automatically find all its sub-packages?
I used to have a function that would just browse the file system, looking for folders that have an __init__.py* file in them, but now I need a method that would work even if the whole package is in an egg.
A:
pkgutil could be helpfull.
Also see this SO question., this is a code example form that question.
kaizer.se
import pkgutil
# this is the package we are inspecting -- for example 'email' from stdlib
import email
package = email
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
print "Found submodule %s (is a package: %s)" % (modname, ispkg)
~unutbu
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
print(modname)
| Python Finding all packages inside a package, even when in an egg | Given a Python package, how can I automatically find all its sub-packages?
I used to have a function that would just browse the file system, looking for folders that have an __init__.py* file in them, but now I need a method that would work even if the whole package is in an egg.
| [
"pkgutil could be helpfull.\nAlso see this SO question., this is a code example form that question.\nkaizer.se\nimport pkgutil\n# this is the package we are inspecting -- for example 'email' from stdlib\nimport email\npackage = email\nfor importer, modname, ispkg in pkgutil.iter_modules(package.__path__):\n print \"Found submodule %s (is a package: %s)\" % (modname, ispkg)\n\n~unutbu\nimport pkgutil\nfor importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):\n print(modname)\n\n"
] | [
0
] | [] | [] | [
"egg",
"import",
"package",
"python",
"setuptools"
] | stackoverflow_0002797680_egg_import_package_python_setuptools.txt |
Q:
Shaders with pygtkglext
Do someone know how to get glsl shaders work in gtk-opengl window? With glut all glCreateProgram etc. functions works, but when I tried to put the same gl code into pygtkglext window, its complaining about NullReference:
OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgram, check for bool(glCreateProgram) before calling
So then I from OpenGL.GL.ARB.shader_objects import *, but the result is similar:
OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgramObjectARB, check for bool(glCreateProgramObjectARB) before calling
Any idea will be useful.
A:
The answer is its not supported yet. Simply pygtkglext doesn't set glCreateProgram. However git version does.
A:
OpenGL entry points are obtained using GetProcAddress routine. I suppose the NULL pointer is the function pointer glCreateProgramObjectARB.
This is strictly related with libraries installed with the driver. Which OpenGL version is running on the host? Maybe the driver doesn't implements the glCreateProgramObjectARB.
| Shaders with pygtkglext | Do someone know how to get glsl shaders work in gtk-opengl window? With glut all glCreateProgram etc. functions works, but when I tried to put the same gl code into pygtkglext window, its complaining about NullReference:
OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgram, check for bool(glCreateProgram) before calling
So then I from OpenGL.GL.ARB.shader_objects import *, but the result is similar:
OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgramObjectARB, check for bool(glCreateProgramObjectARB) before calling
Any idea will be useful.
| [
"The answer is its not supported yet. Simply pygtkglext doesn't set glCreateProgram. However git version does.\n",
"OpenGL entry points are obtained using GetProcAddress routine. I suppose the NULL pointer is the function pointer glCreateProgramObjectARB.\nThis is strictly related with libraries installed with the driver. Which OpenGL version is running on the host? Maybe the driver doesn't implements the glCreateProgramObjectARB.\n"
] | [
1,
0
] | [] | [] | [
"glsl",
"pygtk",
"python",
"shader"
] | stackoverflow_0001893641_glsl_pygtk_python_shader.txt |
Q:
Different line widths with canvas.create_line?
Does anyone have any idea why I get different line widths on the canvas in the following example?
from Tkinter import *
bigBoxSize = 150
class cFrame(Frame):
def __init__(self, master, cwidth=450, cheight=450):
Frame.__init__(self, master, relief=RAISED, height=550, width=600, bg = "grey")
self.canvasWidth = cwidth
self.canvasHeight = cheight
self.canvas = Canvas(self, bg="white", width=cwidth, height=cheight, border =0)
self.drawGridLines()
self.canvas.pack(side=TOP, pady=20, padx=20)
def drawGridLines(self, linewidth = 10):
self.canvas.create_line(0, 0, self.canvasWidth, 0, width= linewidth )
self.canvas.create_line(0, 0, 0, self.canvasHeight, width= linewidth )
self.canvas.create_line(0, self.canvasHeight, self.canvasWidth + 2, self.canvasHeight, width= linewidth )
self.canvas.create_line(self.canvasWidth, self.canvasHeight, self.canvasWidth, 1, width= linewidth )
self.canvas.create_line(0, bigBoxSize, self.canvasWidth, bigBoxSize, width= linewidth )
self.canvas.create_line(0, bigBoxSize * 2, self.canvasWidth, bigBoxSize * 2, width= linewidth)
root = Tk()
C = cFrame(root)
C.pack()
root.mainloop()
It's really frustrating me as I have no idea what's happening. If anyone can help me out then that'd be fantastic. Thanks!
A:
After some experimentation I think I see what's happening - some of the line on the left is being drawn outside the canvas which I think is really retarded. Is there anyway to draw the line so that the outer most bit of it is on the canvas? Alternatively, is there any easier way to draw a border around a widget or on the canvas?
A:
When you draw a line with a width greater than 1, the extra pixels have to be drawn somewhere. As you observed in your own followup post, some of those pixels are being drawn off screen. All you need to do is adjust your original coordinates to take into account the width of the line.
| Different line widths with canvas.create_line? | Does anyone have any idea why I get different line widths on the canvas in the following example?
from Tkinter import *
bigBoxSize = 150
class cFrame(Frame):
def __init__(self, master, cwidth=450, cheight=450):
Frame.__init__(self, master, relief=RAISED, height=550, width=600, bg = "grey")
self.canvasWidth = cwidth
self.canvasHeight = cheight
self.canvas = Canvas(self, bg="white", width=cwidth, height=cheight, border =0)
self.drawGridLines()
self.canvas.pack(side=TOP, pady=20, padx=20)
def drawGridLines(self, linewidth = 10):
self.canvas.create_line(0, 0, self.canvasWidth, 0, width= linewidth )
self.canvas.create_line(0, 0, 0, self.canvasHeight, width= linewidth )
self.canvas.create_line(0, self.canvasHeight, self.canvasWidth + 2, self.canvasHeight, width= linewidth )
self.canvas.create_line(self.canvasWidth, self.canvasHeight, self.canvasWidth, 1, width= linewidth )
self.canvas.create_line(0, bigBoxSize, self.canvasWidth, bigBoxSize, width= linewidth )
self.canvas.create_line(0, bigBoxSize * 2, self.canvasWidth, bigBoxSize * 2, width= linewidth)
root = Tk()
C = cFrame(root)
C.pack()
root.mainloop()
It's really frustrating me as I have no idea what's happening. If anyone can help me out then that'd be fantastic. Thanks!
| [
"After some experimentation I think I see what's happening - some of the line on the left is being drawn outside the canvas which I think is really retarded. Is there anyway to draw the line so that the outer most bit of it is on the canvas? Alternatively, is there any easier way to draw a border around a widget or on the canvas?\n",
"When you draw a line with a width greater than 1, the extra pixels have to be drawn somewhere. As you observed in your own followup post, some of those pixels are being drawn off screen. All you need to do is adjust your original coordinates to take into account the width of the line. \n"
] | [
0,
0
] | [] | [] | [
"python",
"tkinter_canvas"
] | stackoverflow_0002796306_python_tkinter_canvas.txt |
Q:
Programming an Event listener for files in a directory on Linux
On Ubuntu linux, when you watch a flash video, it gets saved temporarily in the /tmp as flv files while the video buffers. I use vlc to directly play these files.
Currently, I have scripted a shortcut that directly scans and opens the latest file in /tmp with vlc, when clicked.
But, I want to program a Java application that will continually monitor this /tmp directory for any new flv files, and open it in vlc automatically. I know I can use Runtime.exec() to open the VLC application with the flv files. But, I DO NOT want to run a while(true) loop (with sleep) to scan for files.
How can I make use of Event Handling (Java or any other language) on Linux to complete this task?
Edit:
I am also wondering if Java is the right way to approach this. As someone suggested below, Python and QT seem more appropriate.
A:
For Python, use pyinotify: http://trac.dbzteam.org/pyinotify. It's a simple, standalone library; there's no need for an ugly Qt dependency for this.
A:
Have you seen JNotify ? It's a Java library that uses OS-specific code to listen for filesystem events.
I wouldn't rule out polling the file system, however, unless you're dealing with a huge number of files/directories.
A:
In Linux there something called FAM (File Alteration Monitor) which does a better job than the sleep/poll thing.
There's a python package for it as well: Python FAM
It is probably going to be a lot less to depend on than for example QT.
A:
I would recommend Qt and Python.
I've used PyQt for a similar project before. Qt has a file system watcher that monitors directories and files for updates, which trigger events that you can catch and do stuff (like open vlc).
QFileSystemWatcher
If this is something you just want to always run in the background, Qt also has a feature that allows you to run your program in the System Tray. This is what I did, and just added a menu or two to make modifications.
QSystemTrayIcon
A:
For Python, you can try this this, I find it simpler than pyinotify.
| Programming an Event listener for files in a directory on Linux | On Ubuntu linux, when you watch a flash video, it gets saved temporarily in the /tmp as flv files while the video buffers. I use vlc to directly play these files.
Currently, I have scripted a shortcut that directly scans and opens the latest file in /tmp with vlc, when clicked.
But, I want to program a Java application that will continually monitor this /tmp directory for any new flv files, and open it in vlc automatically. I know I can use Runtime.exec() to open the VLC application with the flv files. But, I DO NOT want to run a while(true) loop (with sleep) to scan for files.
How can I make use of Event Handling (Java or any other language) on Linux to complete this task?
Edit:
I am also wondering if Java is the right way to approach this. As someone suggested below, Python and QT seem more appropriate.
| [
"For Python, use pyinotify: http://trac.dbzteam.org/pyinotify. It's a simple, standalone library; there's no need for an ugly Qt dependency for this.\n",
"Have you seen JNotify ? It's a Java library that uses OS-specific code to listen for filesystem events.\nI wouldn't rule out polling the file system, however, unless you're dealing with a huge number of files/directories.\n",
"In Linux there something called FAM (File Alteration Monitor) which does a better job than the sleep/poll thing.\nThere's a python package for it as well: Python FAM\nIt is probably going to be a lot less to depend on than for example QT.\n",
"I would recommend Qt and Python.\nI've used PyQt for a similar project before. Qt has a file system watcher that monitors directories and files for updates, which trigger events that you can catch and do stuff (like open vlc).\nQFileSystemWatcher\nIf this is something you just want to always run in the background, Qt also has a feature that allows you to run your program in the System Tray. This is what I did, and just added a menu or two to make modifications.\nQSystemTrayIcon\n",
"For Python, you can try this this, I find it simpler than pyinotify.\n"
] | [
2,
1,
1,
0,
0
] | [] | [] | [
"c#",
"event_handling",
"java",
"linux",
"python"
] | stackoverflow_0002795420_c#_event_handling_java_linux_python.txt |
Q:
How to add a context processor from a Django app
Say I'm writing a Django app, and all the templates in the app require a certain variable.
The "classic" way to deal with this, afaik, is to write a context processor and add it to TEMPLATE_CONTEXT_PROCESSORS in the settings.py.
My question is, is this the right way to do it, considering that apps are supposed to be "independent" from the actual project using them?
In other words, when deploying that app to a new project, is there any way to avoid the project having to explicitly mess around with its settings?
A:
Context processors are very useful and I wouldn't be too shy in using them, but in some situations it doesn't make sense.
This is a technique I use when I need to include something simple to all views in an app. I cannot attest that this is the 'proper' way to do things, but it works for our team:
I'll declare a global dictionary template_vars at the top of the file. Every view would add its own variables to this dictionary and pass it to the template, and it returns template_vars in the render_to_response shortcut.
It looks something like this:
template_vars = {
'spam': 'eggs',
}
def gallery(request):
"""
portfolio gallery
"""
template_vars['projects'] = Projects.objects.all()
return render_to_response('portfolio/gallery.html', template_vars, context_instance=RequestContext(request))
A:
Your assumption that apps can just be added in a project without touching the project's settings is not correct.
If you add an application to a project, you have to edit the settings, since you must add it in the INSTALLED_APPS tuple.
So why not edit the context processor list?
| How to add a context processor from a Django app | Say I'm writing a Django app, and all the templates in the app require a certain variable.
The "classic" way to deal with this, afaik, is to write a context processor and add it to TEMPLATE_CONTEXT_PROCESSORS in the settings.py.
My question is, is this the right way to do it, considering that apps are supposed to be "independent" from the actual project using them?
In other words, when deploying that app to a new project, is there any way to avoid the project having to explicitly mess around with its settings?
| [
"Context processors are very useful and I wouldn't be too shy in using them, but in some situations it doesn't make sense.\nThis is a technique I use when I need to include something simple to all views in an app. I cannot attest that this is the 'proper' way to do things, but it works for our team:\nI'll declare a global dictionary template_vars at the top of the file. Every view would add its own variables to this dictionary and pass it to the template, and it returns template_vars in the render_to_response shortcut.\nIt looks something like this:\ntemplate_vars = {\n 'spam': 'eggs',\n }\n\ndef gallery(request):\n \"\"\"\n portfolio gallery\n \"\"\"\n\n template_vars['projects'] = Projects.objects.all()\n return render_to_response('portfolio/gallery.html', template_vars, context_instance=RequestContext(request))\n\n",
"Your assumption that apps can just be added in a project without touching the project's settings is not correct.\nIf you add an application to a project, you have to edit the settings, since you must add it in the INSTALLED_APPS tuple.\nSo why not edit the context processor list?\n"
] | [
1,
1
] | [
"Yeah, adding a context processor is the most recommended approach to achieve this.\n"
] | [
-1
] | [
"django",
"django_apps",
"python"
] | stackoverflow_0002797878_django_django_apps_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.