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?
Thank... | 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 b... | 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 f... | [
"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 circl... | [
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 fi... | 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... | 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 ... | [
"\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 th... | [
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://dom... | 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/... | [
"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 do... | [
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 instan... | 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 ... | [
"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 t... | [
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 Eng... | 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 o... | [
"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.or... | [
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... | 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 a... | [
"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 libr... | 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 ma... | [
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 ... | 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/... | [
"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 P... | [
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 ... | 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...)\... | [
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 ... | 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 up... | [
"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... | [
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 ... | 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 contain... | [
"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... | [
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 t... | 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 app... | [
"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" ... | 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 diffe... | [
"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... | 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 nick... | [
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)
b... | 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\Googl... | [
"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)\ne... | [
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 ... | 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 deseriali... | [
"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 f... | 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 met... | [
"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 ... | [
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 '... | 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 b... | [
"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 oth... | [
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 proc... | 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 " ' " ... | [
"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 bes... | [
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.... | 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-... | [
"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 th... | [
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' :... | 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 th... | [
"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 ... | [
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... | 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>>>\... | [
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 ... | 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 ... | [
"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 installati... | [
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... | 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... | [
"(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
... | 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... | [
"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 p... | [
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 ... | 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... | [
"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 testin... | [
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 ... | 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... | [
"\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... | [
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 sor... | 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... | [
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 even... | 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 indi... | [
"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): ... | [
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 ... | 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 i... | [
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... | 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 ... | [
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.... | 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)\nasse... | [
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
... | 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 pattern... | [
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.")
... | 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()
... | [
"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\nI... | [
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 t... | 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... | [
"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://1... | [
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")... | 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_RET... | [
"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 = String... | [
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(fa... | 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])
... | [
"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... | [
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):
... | 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 ... | [
"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.\ncla... | [
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 + datet... | 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 functio... | 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 ... | [
"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:\... | [
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 ... | 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",
... | [
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 comprehensio... | 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 ... | [
"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... | [
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 stat... | 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 th... | [
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 differen... | 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 ke... | [
"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 priorit... | [
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 cal... | 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 ... | [
"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 ... | [
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 "Ke... | 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 wi... | [
"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 re... | [
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 th... | 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
succ... | [
"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 ... | [
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... | [
-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 th... | 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 configuratio... | 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 d... | [
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 ... | 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 ... | [
"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... | [
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 mis... | 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 inte... | [
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... | 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_de... | [
"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 metho... | [
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... | 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 ... | [
"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 s... | [
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 arbitra... | 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... | [
"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... | [
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 eleme... | 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 n... | [
"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:\nimp... | [
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 responsibili... | 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... | [
"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 choic... | [
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 se... | 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(iter... | [
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 i... | 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 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 ... | [
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.341... | 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/p... | [
"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 us... | [
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 with... | 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, c... | [
"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__(sel... | [
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 = w... | 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... | [
"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 mech... | 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_na... | [
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().fil... | 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 = baseq... | [
"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#ins... | [
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... | 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'... | [
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(... | 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 ... | [
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 variabl... | 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 i... | [
"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. Fo... | [
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 the... | 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 ... | [
"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.ki... | 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... | [
"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=T... | [
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.... | 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 wor... | [
"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>{{ ... | 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... | [
"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-r... | 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 c... | [
"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 lon... | [
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 l... | 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 Dig... | [
"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 ... | [
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... | 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
... | [
"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?... | [
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 0x... | 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 overlook... | [
"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_US... | 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 _wi... | [
"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... | 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, s... | [
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'... | 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.')], HRESU... | [
"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 ... | [
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 __unic... | 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... | [
"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... | 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... | [
"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 d... | [
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 sto... | 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 obj... | [
"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 f... | [
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 gam... | 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 t... | [
"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 advant... | [
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 /Appli... | 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/Conte... | [
"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/projec... | [
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 appli... | 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. ... | [
"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 'vi... | [
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 ... | 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 = IndexS... | [
"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... | [
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 s... | 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... | [
"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... | 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, *... | [
"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... | [
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 registratio... | 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 ... | [
"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/to... | [
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("Subc... | 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=SUBCATEGO... | [
"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... | [
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 tur... | 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 @class... | [
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
... | 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 L... | [
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... | 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 someth... | [
"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... | [
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 =... | 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... | [
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 ... | 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 prin... | [
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 ... | 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 bo... | [
"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 th... | [
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, ... | 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.can... | [
"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... | [
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 ... | 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 applicati... | [
"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,... | [
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... | 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 "i... | [
"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... | [
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.