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:
Google-App Engine logging problem
I'm wondering if anyone has experienced problems with Google-App Engine's logging facility. Everything was working fine for me until this morning, I ran my local server and no logging messages were being displayed (well, none of my logging messages, the server GET messages etc.. a... | Google-App Engine logging problem | I'm wondering if anyone has experienced problems with Google-App Engine's logging facility. Everything was working fine for me until this morning, I ran my local server and no logging messages were being displayed (well, none of my logging messages, the server GET messages etc.. are being displayed). Even errors are no... | [
"Thanks Abdul you made me realize what the problem is. I had changed a URL in my application to point to the application that I had deployed to Google-App Engine. It should have been pointing to my local application. I had myapp.appspot.com/move instead of localhost/move\n",
"In Dev server The only one and best w... | [
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0005612390_django_google_app_engine_python.txt |
Q:
How do you map a fully qualified class name to its class object in Python?
You can get the fully qualified class name of a Python object like this (see this question):
>>> import Queue
>>> q = Queue.PriorityQueue()
>>> def fullname(o):
return o.__module__ + "." + o.__class__.__name__
...
>>> fullname(q)
'... | How do you map a fully qualified class name to its class object in Python? | You can get the fully qualified class name of a Python object like this (see this question):
>>> import Queue
>>> q = Queue.PriorityQueue()
>>> def fullname(o):
return o.__module__ + "." + o.__class__.__name__
...
>>> fullname(q)
'Queue.PriorityQueue'
>>>
How do you do the inverse, ie, map a fully qualified ... | [
"You can use importlib in 2.7:\nfrom importlib import import_module\n\nname = 'xml.etree.ElementTree.ElementTree'\nparts = name.rsplit('.', 1)\nElementTree = getattr(import_module(parts[0]), parts[1])\ntree = ElementTree()\n\nIn older versions you can use the __import__ function. It defaults to returning the top le... | [
11,
1,
0
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0007218865_introspection_python.txt |
Q:
python, without method overloading, howto?
I want to write a function named size() which will accept either a file name or a list of filenames and return the size of the file or sum of its sizes respectively. How to do this without function overloading which is not available in python?
thanks
suresh
A:
def size(... | python, without method overloading, howto? | I want to write a function named size() which will accept either a file name or a list of filenames and return the size of the file or sum of its sizes respectively. How to do this without function overloading which is not available in python?
thanks
suresh
| [
"def size(*files):\n for file in files:\n print file\n\n*files is a special argument type which will catch all arguments into a list. Thus, if you call size like this:\nsize(\"file1.txt\", \"file2.xml\")\n\nfiles will be a list containing file1.txt and file2.xml. If you call it with only one argument, it ... | [
5,
3,
1,
1
] | [] | [] | [
"overloading",
"python"
] | stackoverflow_0007219550_overloading_python.txt |
Q:
The regex in my python class is always returning false
class MyTest:
a = re.compile('abc')
def testthis(self, fname):
print fname
if self.a.match(fname):
return 'yes'
else:
return 'no'
If I pass 'testabc' to testthis() then it prints no. If I change the re... | The regex in my python class is always returning false | class MyTest:
a = re.compile('abc')
def testthis(self, fname):
print fname
if self.a.match(fname):
return 'yes'
else:
return 'no'
If I pass 'testabc' to testthis() then it prints no. If I change the regex to .*abc then it prints yes. What's going on? Is it tryi... | [
"From the docs (emphasis mine):\n\nre.match(pattern, string[, flags])\nIf zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.\... | [
4,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007219622_python_regex.txt |
Q:
Adjusting one image's exposure / white balance to match another (with PIL?)
I have a cheap stereo camera rig that I use for diving. Sometimes each camera white balances or sets exposure differently. Example:
http://www.chrisevans3d.com/temp/forums/left.jpg
http://www.chrisevans3d.com/temp/forums/right.jpg
Is ther... | Adjusting one image's exposure / white balance to match another (with PIL?) | I have a cheap stereo camera rig that I use for diving. Sometimes each camera white balances or sets exposure differently. Example:
http://www.chrisevans3d.com/temp/forums/left.jpg
http://www.chrisevans3d.com/temp/forums/right.jpg
Is there a way to do this with getting im.histogram() of each, making a diff or LUT then... | [
"Matching white balance is not a trivial task. A very basic method is to assume a gray world and scale the RGB channels of one image to match the average RGB values of another. This will fail easily when the scenes are biased towards a color (instead of gray). You can improve it further by rejecting dark/bright pix... | [
4,
0
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library",
"stereo_3d"
] | stackoverflow_0006533170_image_processing_python_python_imaging_library_stereo_3d.txt |
Q:
Python difflib gnu patch compatibility
It's possible to create patch with python module difflib which is compatible with GNU patch?
I tried to use unified_diff and context_diff and also tried to specify lineterm as "\n" but I'm still gettings this error:
[intense@Singularity Desktop]$ patch diff.patch test.txt
pa... | Python difflib gnu patch compatibility | It's possible to create patch with python module difflib which is compatible with GNU patch?
I tried to use unified_diff and context_diff and also tried to specify lineterm as "\n" but I'm still gettings this error:
[intense@Singularity Desktop]$ patch diff.patch test.txt
patch unexpectedly ends in middle of line
patc... | [
"\nTry to use python-patch instead of the GNU patch utility to apply unified diffs,\nOR use diff -rNau dir-v1/ dir-v2/ > 1-2.patch instead of difflib.\n\n",
"I'd use mercurials bdiff module, which is considerably faster than difflib.\n"
] | [
0,
0
] | [] | [] | [
"compatibility",
"difflib",
"patch",
"python"
] | stackoverflow_0007217716_compatibility_difflib_patch_python.txt |
Q:
Optionmenu/Entry combination in Tkinter
Hej, I want to produce an entry field (for directory paths) that also has the dropdown ability of an optionmenu (stating the 5 last used directories). It is basically supposed to look like the solution MATLAB uses. How do I go about that? I need the ability to manually chang... | Optionmenu/Entry combination in Tkinter | Hej, I want to produce an entry field (for directory paths) that also has the dropdown ability of an optionmenu (stating the 5 last used directories). It is basically supposed to look like the solution MATLAB uses. How do I go about that? I need the ability to manually change the path, so a plain optionmenu with a brow... | [
"Use ttk.Combobox widget, http://www.tkdocs.com/tutorial/widgets.html#combobox (or http://www.tcl.tk/man/tcl/TkCmd/ttk_combobox.htm). Using this you can set default values, but you are also able to write in the entry a new value.\ncombobox = ttk.Combobox(parent)\ncombobox['values'] = five_last_dirs_tuple\ncombobox[... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007202912_python_tkinter.txt |
Q:
Python and Ubuntu file not found
I have been running several versions of Python on my Ubuntu 10.10 for a while but I was having some issues with python2.5 (for Google app-engine)
So I blew the 2.5 install away(and removed the site-packages directory along with the Python2.5 directory) and re-installed... got the s... | Python and Ubuntu file not found | I have been running several versions of Python on my Ubuntu 10.10 for a while but I was having some issues with python2.5 (for Google app-engine)
So I blew the 2.5 install away(and removed the site-packages directory along with the Python2.5 directory) and re-installed... got the same error,, a file not found that was ... | [
"When you import it, it goes through the Python path to find it, but when you enter:\npython2.5 virtualenv.py\n\nthat assumes it's in the current directory.\n",
"A good starting point for tracing such WTF's is to run the process under strace which will report (copiously) the system calls made and the results of e... | [
2,
1
] | [] | [] | [
"python",
"ubuntu",
"virtualenv"
] | stackoverflow_0007216471_python_ubuntu_virtualenv.txt |
Q:
Is it normal behaviour for python?
In the latest Python (3.2):
>>> l = [{}]*2
>>> l[1]['key'] = 'value'
>>> l
[{'key': 'value'}, {'key': 'value'}]
I expected l to be [{}, {'key': 'value'}] after this operation. Is it normal behaviour or a bug?
A:
Normal. Try using l = [{} for x in range(2)] instead.
[{}]*2 does... | Is it normal behaviour for python? | In the latest Python (3.2):
>>> l = [{}]*2
>>> l[1]['key'] = 'value'
>>> l
[{'key': 'value'}, {'key': 'value'}]
I expected l to be [{}, {'key': 'value'}] after this operation. Is it normal behaviour or a bug?
| [
"Normal. Try using l = [{} for x in range(2)] instead.\n[{}]*2 does not actually make 2 different dictionaries - it makes a list with two references to the same dictionary. Thus, updating that dictionary makes changes show up for both items in the list, because both items are actually the same dictionary, just refe... | [
12,
3,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0007220555_dictionary_list_python.txt |
Q:
Ordering by multiplication of several values in Django ORM?
Possible Duplicate:
Django QuerySet ordering by expression
If I had a model with 3 integer fields, a,b,c, is it possible to do an order_by() on the value of abc within the ORM?
A:
Absolutely. Use .extra(select=..., order_by=...), using the same name f... | Ordering by multiplication of several values in Django ORM? |
Possible Duplicate:
Django QuerySet ordering by expression
If I had a model with 3 integer fields, a,b,c, is it possible to do an order_by() on the value of abc within the ORM?
| [
"Absolutely. Use .extra(select=..., order_by=...), using the same name for both.\n",
"Yes, although the syntax isn't pretty.\nYou can do this:\nYourModel.objects.extra(\n select={'total': 'a * b * c'},\n order_by=['total'],\n)\n\n"
] | [
1,
0
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0007220593_django_orm_python.txt |
Q:
Python. Project Euler Q35. Got a solution but I don't understand why other method doesn't work.
def rot_dig(x):
y=''
output=[x]
listing=list(x)
for i in range(1,len(x)):
listing.append(listing[0])
del(listing[0])
for i in listing:
y=y+i
output.append(y)
... | Python. Project Euler Q35. Got a solution but I don't understand why other method doesn't work. | def rot_dig(x):
y=''
output=[x]
listing=list(x)
for i in range(1,len(x)):
listing.append(listing[0])
del(listing[0])
for i in listing:
y=y+i
output.append(y)
y=''
return output
import math
def prime_is(x,prime):
for m in prime:
if m<=... | [
"It's probably because your outer loop is for x in primestr: and the marked code removes items from primestr. You don't want to change primestr while looping over it that way. You could use a loop like while i < len(primestr) instead.\nSome other improvements would be to compute sqrt outside the loop; to use a list... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007220565_python.txt |
Q:
Converting Python String to Date
I need to convert the Python string "Mon Aug 29 2011 18:30:00 GMT+0530 (IST)" into "20110829T183000Z" and "20110829T173000Z" (Date + 1 hour).
Never have been good at remembering datetime APIs, would appreciate the help here!
A:
google it. increasing your google skills is always b... | Converting Python String to Date | I need to convert the Python string "Mon Aug 29 2011 18:30:00 GMT+0530 (IST)" into "20110829T183000Z" and "20110829T173000Z" (Date + 1 hour).
Never have been good at remembering datetime APIs, would appreciate the help here!
| [
"google it. increasing your google skills is always better than being lazy.\n\nhttp://docs.python.org/library/datetime.html#datetime.datetime.strptime\nclassmethod datetime.strptime(date_string, format)\nReturn a datetime corresponding to date_string, parsed according to format.\n This is equivalent to datetime(*(... | [
2
] | [] | [] | [
"date",
"datetime",
"python"
] | stackoverflow_0007220708_date_datetime_python.txt |
Q:
Retrieve binary operator called on an instance
I've been mucking around with class special methods to overload numeric operators via object.__add__(self,other) etc.
Is there a generic way to find out which binary operator was called though?
For unary operators you can use __getattr__, e.g:
class Test():
def __ge... | Retrieve binary operator called on an instance | I've been mucking around with class special methods to overload numeric operators via object.__add__(self,other) etc.
Is there a generic way to find out which binary operator was called though?
For unary operators you can use __getattr__, e.g:
class Test():
def __getattr__(self, name):
print name
t = Test()
~t #... | [
"t+t calls __coerce__ and then __add__. __coerce__ is supposed to convert (numeric) types to a common class, for example 1.0 + 2 first coerces both numbers to floats.\nIf you want to do something special you can return proxy objects from __coerce__ that see the following operator.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007220746_python.txt |
Q:
Undefined Symbols with Python.h
I'm trying to embed a Python script into a C++ application. Before I do such a thing though, I'm trying to run the example script.
Here's my code:
#include <Python/Python.h>
int main(int argc, char *argv[]) {
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
... | Undefined Symbols with Python.h | I'm trying to embed a Python script into a C++ application. Before I do such a thing though, I'm trying to run the example script.
Here's my code:
#include <Python/Python.h>
int main(int argc, char *argv[]) {
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(... | [
"You need to link to the python libraries, e.g. libpython.a for static linkage.\n",
"This answer is old and yucky (static, eww).\ndistutils is the answer for most cases.\nIf you really insist on DIY, add this to your ~/.profile:\n# Works on Lion\n\nalias pygcc='gcc -I/System/Library/Frameworks/Python.framework/Ve... | [
4,
1,
0
] | [] | [] | [
"c++",
"python",
"python_2.7"
] | stackoverflow_0006578258_c++_python_python_2.7.txt |
Q:
How to prune subtree in python
I am (still) dealing with a tree structure in a Python program.
Each node in a tree has a dictionary "children", whose keys hold arc information, and values
are the child nodes. (And each node has a (parent, parent_arc) pair, where parent is its parent node and parent_arc is the arc ... | How to prune subtree in python | I am (still) dealing with a tree structure in a Python program.
Each node in a tree has a dictionary "children", whose keys hold arc information, and values
are the child nodes. (And each node has a (parent, parent_arc) pair, where parent is its parent node and parent_arc is the arc by which the parent node link this n... | [
"When A -> B and B -> A you have reference cycles. A good way to get around that is to have the children use weak references to point back to the parent. Something like this:\nimport weakref\nclass Node():\n parent = None\n child = None\n @property\n def parent(self):\n parent = self._parent()\... | [
2
] | [] | [] | [
"python",
"reduce",
"tree"
] | stackoverflow_0007220614_python_reduce_tree.txt |
Q:
Beginner Python Question RE: String Formatting Type and repr() function
So I have this code:
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
And I get this output:
1 2 3 4
'one' 'two' 'three' 'four'
My question is:
Why does the second line of outp... | Beginner Python Question RE: String Formatting Type and repr() function | So I have this code:
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
And I get this output:
1 2 3 4
'one' 'two' 'three' 'four'
My question is:
Why does the second line of output have single quotes around it? I'm not quite sure how the %r conversion typ... | [
"With the expression 'abc%rdef' % obj , the part '%r' is replaced with repr(obj)\nWith the expression 'ABC%sDEF' % obj , the part '%s' is replaced with str(obj)\n.\nrepr() is a function that , for common objects, returns a string that is the same as the one you would write in a script to define the object passed as... | [
2,
0
] | [] | [] | [
"python",
"string_conversion"
] | stackoverflow_0007221131_python_string_conversion.txt |
Q:
Python: check if an object is NOT an "array-type"
I'm looking for a way to test if an object is not of a "list-ish" type, that is - not only that the object is not iterable (e.g. - you can also run iter on a string, or on a simple object that implements iter) but that the object is not in the list family. I define... | Python: check if an object is NOT an "array-type" | I'm looking for a way to test if an object is not of a "list-ish" type, that is - not only that the object is not iterable (e.g. - you can also run iter on a string, or on a simple object that implements iter) but that the object is not in the list family. I define the "list" family as list/tuple/set/frozenset, or anyt... | [
"There is no term 'list-ish' and there is no magic build-in check_if_value_is_an_instance_of_some_i_dont_know_what_set_of_types.\nYou solution with not isinstance( value, (frozenset, list, set, tuple,) ) is pretty good - it is clear and explicit.\n",
"There is no such family – it's not well-defined, and naturally... | [
6,
3
] | [] | [] | [
"arrays",
"iterable",
"list",
"python"
] | stackoverflow_0007221404_arrays_iterable_list_python.txt |
Q:
python+security
what would be a good way to implement an authentication in python? something that already exists is fine too.
I need it for auth over an untrusted network connection. It doesn't need to be advanced, just enough to get a common password over securely.
i have looked at the ssl module. but that module... | python+security | what would be a good way to implement an authentication in python? something that already exists is fine too.
I need it for auth over an untrusted network connection. It doesn't need to be advanced, just enough to get a common password over securely.
i have looked at the ssl module. but that module confuses me like the... | [
"Obviously HTTPS is a good choice, if you do not need encryption, HMAC can provide a secure authentication alternative, and seems to be supported in python.\n"
] | [
2
] | [] | [] | [
"python",
"security",
"sockets"
] | stackoverflow_0007216205_python_security_sockets.txt |
Q:
data table in Python
I've got a 2D list in Python like this:
[['Something', 'Something else', 'Another thing'],
['Other things', 'More data', 'Element'],
['Stuff', 'data', 'etc']]
I want it to be printed out like this:
Something Something else Another thing
Other things More data Element
St... | data table in Python | I've got a 2D list in Python like this:
[['Something', 'Something else', 'Another thing'],
['Other things', 'More data', 'Element'],
['Stuff', 'data', 'etc']]
I want it to be printed out like this:
Something Something else Another thing
Other things More data Element
Stuff data ... | [
"l = [['Something', 'Something else', 'Another thing'],\n ['Other things', 'More data', 'Element'],\n ['Stuff', 'data', 'etc']]\nsub1 = [\n [s.ljust(max(len(i) for i in column)) for s in column]\n for column in zip(*l)]\nfor p in [\" \".join(row) for row in zip(*sub1)]: print p\n\nHere, first the list... | [
7,
2,
1,
0,
0
] | [
"print '\\n'.join([line+' ' for line in l])\n\n"
] | [
-1
] | [
"formatting",
"python"
] | stackoverflow_0007136432_formatting_python.txt |
Q:
Python: convert Chinese characters into pinyin with CJKLIB
I'm trying to convert a bunch of Chinese characters into pinyin, reading the characters from one file and writing the pinyin into another. I'm working with the CJKLIB functions to do this.
Here's the code,
from cjklib.characterlookup import CharacterLooku... | Python: convert Chinese characters into pinyin with CJKLIB | I'm trying to convert a bunch of Chinese characters into pinyin, reading the characters from one file and writing the pinyin into another. I'm working with the CJKLIB functions to do this.
Here's the code,
from cjklib.characterlookup import CharacterLookup
source_file = 'cities_test.txt'
dest_file = 'output.txt'
s =... | [
"Your bug is that you are not decoding the input stream, and yet you are turning around and re-encoding it as though it were UTF-8. That’s going the wrong way.\nYou have two choices.\nYou can codecs.open the input file with an explicit encoding so you always get back regular Unicode strings whenever you read fro... | [
1
] | [] | [] | [
"cjk",
"python",
"unicode"
] | stackoverflow_0007221764_cjk_python_unicode.txt |
Q:
Using AJP to perform requests from Python to Java webserver
I have to implement a Python web application which operates on data available through web-services (API with GET requests and JSON responses).
The API server is implemented in Java. Preliminarily tests show significant overhead if API calls are made throu... | Using AJP to perform requests from Python to Java webserver | I have to implement a Python web application which operates on data available through web-services (API with GET requests and JSON responses).
The API server is implemented in Java. Preliminarily tests show significant overhead if API calls are made through urllib2 (connection is opened and closed for each request).
I... | [
"I have no idea what's AJP is. Also you did not open what goes to \"sigfinicant overhead\", so I might be a poor person to answer to this question.\nBut if I were you I would first try to few tricks:\nEnable HTTP 1.1 keep-alive on urllib2\n(here is an example using another library Python urllib2 with keep alive )\n... | [
1
] | [] | [] | [
"ajp",
"java",
"python"
] | stackoverflow_0007221446_ajp_java_python.txt |
Q:
## in python using notepad++ syntax coloring
In my editor (notepad++) in Python script edit mode, a line
## is this a special comment or what?
Turns a different color (yellow) than a normal #comment.
What's special about a ##comment vs a #comment?
A:
From the Python point of view, there's no difference. Howeve... | ## in python using notepad++ syntax coloring | In my editor (notepad++) in Python script edit mode, a line
## is this a special comment or what?
Turns a different color (yellow) than a normal #comment.
What's special about a ##comment vs a #comment?
| [
"From the Python point of view, there's no difference. However, Notepad++'s highlighter considers the ## sequence as a STRINGEOL, which is why it colours it this way. See this thread.\n",
"I thought the difference had something to do with usage:\n#this is a code block header\n\nvs.\n##this is a comment\n\nI know ... | [
6,
3,
0
] | [] | [] | [
"comments",
"python"
] | stackoverflow_0001410063_comments_python.txt |
Q:
save data from form with custom foreign key field in django
I have the following Model classes:
class ContactPerson(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Appartment(models.Model):
contact_person = models.ForeignKey(Cont... | save data from form with custom foreign key field in django | I have the following Model classes:
class ContactPerson(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Appartment(models.Model):
contact_person = models.ForeignKey(ContactPerson)
Problem: In template file I want a user to fill conta... | [
"I think the code that you are putting in your view would be better suited to the ModelForm's validation.\nOverride the model form's clean_contact_person method and add the code there so that it a) checks that the name is valid and if so, b) sets the form field's value to the actual ContactPerson instance.\nSomethi... | [
1,
0
] | [] | [] | [
"django",
"foreign_keys",
"forms",
"python"
] | stackoverflow_0007218970_django_foreign_keys_forms_python.txt |
Q:
Clear Tkinter Entry text - so new text looks new?
I want to modify the code below to clear the Entry text prior to new text being written. Basically I want to delete text, wait one second, then write new text. This should give the appearance of "NEW" text being written.
Any ideas? TIA - Brad
import thread, ... | Clear Tkinter Entry text - so new text looks new? | I want to modify the code below to clear the Entry text prior to new text being written. Basically I want to delete text, wait one second, then write new text. This should give the appearance of "NEW" text being written.
Any ideas? TIA - Brad
import thread, Queue, time, random, poster
from Tkinter import *
... | [
"Since there are potentially many threads writing to the queue (one for every time the button is pressed) it is a little unclear when text should be deleted and new text should be inserted. For example, if text has just been written and new text arrives, should the new text be written immediately or should it be ad... | [
1,
0
] | [] | [] | [
"message_queue",
"multithreading",
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0007205394_message_queue_multithreading_python_tkinter_tkinter_entry.txt |
Q:
Is there a way to have something execute for every view in django?
I'm new to Django and coming from Rails, so that may explain my odd questions below:
I have a main layout that has a sidebar that lists the latest updates to the site. That main layout is used for every page in my webapp so every template that is c... | Is there a way to have something execute for every view in django? | I'm new to Django and coming from Rails, so that may explain my odd questions below:
I have a main layout that has a sidebar that lists the latest updates to the site. That main layout is used for every page in my webapp so every template that is created extends main.html.
For the latest updates section, I just want to... | [
"Django 1.3 added the render shortcut which is the same as render_to_response but with RequestContext automatically used.\n",
"Templates is a appropriate place for this: the variant with custom tag and template inheritance is simple and convenient. To avoid string appending use mini-template just for your tag: i... | [
4,
3,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007222367_django_python.txt |
Q:
python PIL and Image scaling
I want to make sure an image that will be saved stays inside the border of my specific dimensions and scales down if any of its dimensions exceed these specific dimensions.
I will be using a gallery for my website using django and the width and height of it is certain, If I use crop wh... | python PIL and Image scaling | I want to make sure an image that will be saved stays inside the border of my specific dimensions and scales down if any of its dimensions exceed these specific dimensions.
I will be using a gallery for my website using django and the width and height of it is certain, If I use crop while saving an image to keep dimens... | [
"You should really look at http://thumbnail.sorl.net/ (especially http://thumbnail.sorl.net/template.html#options), it will solve this and many other problems that you may encounter later.\n"
] | [
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0007140883_python_python_imaging_library.txt |
Q:
What are the iteration class methods next() and __next__() for, and what is the difference?
I am a little bit lost on python iterators. I occasionally use them, but I don't remember creating one myself. I read from somewhere that I don't remember where, a code like this:
class Foo(object):
def __init__(self):
... | What are the iteration class methods next() and __next__() for, and what is the difference? | I am a little bit lost on python iterators. I occasionally use them, but I don't remember creating one myself. I read from somewhere that I don't remember where, a code like this:
class Foo(object):
def __init__(self):
self.something = "initial_value"
def __iter__(self):
return self
def next... | [
"PEP 3114 renamed iterator.next() to iterator.__next__(). This was implemented in version 3.0. The link above contains all the gory details.\n",
"next has been renamed to __next__ in Python 3. As for what it does, it should return the next item, or raise StopIteration if there are no more.\n"
] | [
18,
8
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0007223183_iterator_python.txt |
Q:
What does [...] (an ellipsis) in a list mean in Python?
I just got some weird output of a python script:
[[(7, 6), (6, 4), (7, 2)], [...], [...], [...], [(7, 6), (8, 4), (7, 2)], [...], [...], [...], [...], [...], [...], [...]]
The output should be a list of lists of tuples. But I have no idea why [...] appears.
... | What does [...] (an ellipsis) in a list mean in Python? | I just got some weird output of a python script:
[[(7, 6), (6, 4), (7, 2)], [...], [...], [...], [(7, 6), (8, 4), (7, 2)], [...], [...], [...], [...], [...], [...], [...]]
The output should be a list of lists of tuples. But I have no idea why [...] appears.
What does [...] mean?
I don't think its an empty list, as an... | [
"It is a recursive reference. Your list contains itself, or at least there is some kind of cycle.\nExample:\nx = []\nx.insert(0, x)\n# now the repr(x) is '[[...]]'.\n\nThe built-in repr for lists detects this situation and does not attempt to recurse on the sub-list (as it normally would), because that would lead t... | [
27
] | [] | [] | [
"python"
] | stackoverflow_0007223222_python.txt |
Q:
Install mysql python lib for XAMPP
I want to query my XAMPP mysql database with python. However, it seems like that I cannot install MySQL-python without having a "real" mysql database installed on my machine.
When I install it with easy install I get the following error output
File "setup.py", line 15, in <module... | Install mysql python lib for XAMPP | I want to query my XAMPP mysql database with python. However, it seems like that I cannot install MySQL-python without having a "real" mysql database installed on my machine.
When I install it with easy install I get the following error output
File "setup.py", line 15, in <module>
File "/tmp/easy_install-qQJSHH/MySQL-p... | [
"After extracting the MySQL-python-X.X.X tar ball, edit the file site.cfg.\nLook for the line:\n# mysql_config = /usr/local/bin/mysql_config\n\nuncomment the line and replace with:\nmysql_config = /opt/lampp/bin/mysql_config\n\nThis is assuming you installed XAMPP in /opt/lampp.\n"
] | [
1
] | [] | [] | [
"mysql",
"python",
"xampp"
] | stackoverflow_0006943150_mysql_python_xampp.txt |
Q:
How do I get the link and title from this (part of) html string in python
I'm writing a plugin for xbmc in python. I have got a list of strings in the format:
<a href="/www.link.to/something">name of link</a>
By using beautiful stone soup (the relevant part of the code):
soup = BeautifulStoneSoup(link, convertEnt... | How do I get the link and title from this (part of) html string in python | I'm writing a plugin for xbmc in python. I have got a list of strings in the format:
<a href="/www.link.to/something">name of link</a>
By using beautiful stone soup (the relevant part of the code):
soup = BeautifulStoneSoup(link, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
programs = soup('ul')
i = 0
... | [
"Why not let BeautifulSoup give you the href attribute and the element contents?\n",
"The easiest way is to use lxml: \nfrom lxml.html import fromstring\n\nelem = fromstring(link.string)\nprint elem.attrib[\"href\"]\nprint elem.text\n\n"
] | [
2,
0
] | [] | [] | [
"html_parsing",
"python",
"xbmc"
] | stackoverflow_0007223498_html_parsing_python_xbmc.txt |
Q:
Custom Python Twisted protocol : good practices and complexity?
I am currently working on a control system for Arduino type devices using Twisted,and have a bit of a design issue
Here is how things are currently: (sorry in advance, might be a bit long)
to handle different type of devices (each having a different ... | Custom Python Twisted protocol : good practices and complexity? | I am currently working on a control system for Arduino type devices using Twisted,and have a bit of a design issue
Here is how things are currently: (sorry in advance, might be a bit long)
to handle different type of devices (each having a different firmware & communication protocol ) i have a designed a "driver" sys... | [
"I'll try my best at answering a, well, quite general question.\n1) The interface that make up a Twisted protocol has only 4 methods:\nhttp://twistedmatrix.com/documents/11.0.0/api/twisted.internet.interfaces.IProtocol.html\nSo this will be where all the interaction between your protocol implementations and Twisted... | [
3
] | [] | [] | [
"complexity_theory",
"protocols",
"python",
"twisted"
] | stackoverflow_0007134170_complexity_theory_protocols_python_twisted.txt |
Q:
Invalid Python syntax using file.write
Trying to learn some geospatial python. More or less following the class notes here.
My Code
#!/usr/bin/python
# import modules
import ogr, sys, os
# set working dir
os.chdir('/home/jacques/misc/pythongis/data')
# create the text file we're writing to
file = open('data_exp... | Invalid Python syntax using file.write | Trying to learn some geospatial python. More or less following the class notes here.
My Code
#!/usr/bin/python
# import modules
import ogr, sys, os
# set working dir
os.chdir('/home/jacques/misc/pythongis/data')
# create the text file we're writing to
file = open('data_export.txt', 'w')
# import the required driver... | [
"Previous line is missing a close parenthesis:\ny = str(geometry.GetY())\n\nAlso, just a style comment: it's a good idea to avoid using the variable name file in python because it actually has a meaning. Try opening a new python session and running help(file)\n"
] | [
6
] | [
"1)write should shouldn't be upper case in your code (Python is case sensitive)\n2)make sure id is a string; if it's isn't use str(id) in your term, same for \"cover\" and \"x\" and \"y\"\n"
] | [
-1
] | [
"geospatial",
"python"
] | stackoverflow_0007223570_geospatial_python.txt |
Q:
Python: Add function to an array in a FOR loop
Maybe this is a simple issue, but I could not find any information about it so far.
For an optimization in numpy I need an array of functions. The number of functions I need depends on the current object which shall be optimized.
I have already figured out how to crea... | Python: Add function to an array in a FOR loop | Maybe this is a simple issue, but I could not find any information about it so far.
For an optimization in numpy I need an array of functions. The number of functions I need depends on the current object which shall be optimized.
I have already figured out how to create these functions dynamically, but now I would like... | [
"Ah, I get it. You really do mean an array of functions. \nThe type mismatch error arises because the call to zeros creates an array of floats by default. So your original would work if instead you did myArray = numpy.empty(x, dtype=numpy.object) (note that empty makes more sense than zeros here). The slightly mor... | [
3,
1,
1,
1
] | [] | [] | [
"arrays",
"function",
"metaprogramming",
"python"
] | stackoverflow_0007222318_arrays_function_metaprogramming_python.txt |
Q:
Can't find the function name
I'm creating a webservice for appengine, and I've created two functions inside the class WebService.py. And I'm trying to register these functions in a SimpleXMLRPCServer object. But When I pass the function names to the parameters, it says undefined variable.
Here is the code:
import... | Can't find the function name | I'm creating a webservice for appengine, and I've created two functions inside the class WebService.py. And I'm trying to register these functions in a SimpleXMLRPCServer object. But When I pass the function names to the parameters, it says undefined variable.
Here is the code:
import SimpleXMLRPCServer
from google.a... | [
"You're trying to pass global objects login and register to register_function(), but those aren't global objects, they're methods.\nI'm assuming you either need to instantiate that class and pass the attributes of that object in or you need to pass the attributes of the class as the commenter suggested.\n",
"I ju... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007223703_google_app_engine_python.txt |
Q:
Graphs, plots in Python 3
I've been teaching myself the basics of programming using Python 3 and now want to delve into more mathematical/graphical stuff (e.g. plotting fractals).
Everything I find for graphs (e.g. pyLab, matplotlib) seems to be incompatible with Python 3, though I did find a version of numpy I c... | Graphs, plots in Python 3 | I've been teaching myself the basics of programming using Python 3 and now want to delve into more mathematical/graphical stuff (e.g. plotting fractals).
Everything I find for graphs (e.g. pyLab, matplotlib) seems to be incompatible with Python 3, though I did find a version of numpy I could install. Does anyone know ... | [
"Since April I'm using matplotlib with Python 3 (without problems).\nIt's about time to libraries update themselves to Python3.\nCheck this link\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python",
"python_3.x"
] | stackoverflow_0007223808_matplotlib_python_python_3.x.txt |
Q:
os.system or subprocess to pass command to shell
I am trying to execute a command in a shell and pipe the output at the same time for filtering.
the relevent code looks like:
import os
n=raw_input("enter cmd")
os.system(n + ' | grep x')
the result is
Syntax error: Redirection unexpected.
It is on ubuntu, seemed ... | os.system or subprocess to pass command to shell | I am trying to execute a command in a shell and pipe the output at the same time for filtering.
the relevent code looks like:
import os
n=raw_input("enter cmd")
os.system(n + ' | grep x')
the result is
Syntax error: Redirection unexpected.
It is on ubuntu, seemed like some references online mentioned this, but none I... | [
"Use subprocess module instead of os.system, which is deprecated.\nsubprocess allows piping and capturing stdout, as you want.\nprocess = subprocess.call(command_string.split(), ..., stdout=subprocess.PIPE, ...) \n\n... handle your output from process.communicate()\n\n",
"In Ubuntu, the default shell is dash, and... | [
2,
1,
0
] | [] | [] | [
"os.system",
"python",
"redirect",
"subprocess"
] | stackoverflow_0007224099_os.system_python_redirect_subprocess.txt |
Q:
weird python print behaviour
why this does not print anything:
for item in pipe.json["value"]["items"]:
print item["pubDate"]
but this does:
for item in pipe.json["value"]["items"]:
print item["pubDate"] + "\n"
p.s. the loop is running inside another loop.
p.p.s. this is running inside google app engine ap... | weird python print behaviour | why this does not print anything:
for item in pipe.json["value"]["items"]:
print item["pubDate"]
but this does:
for item in pipe.json["value"]["items"]:
print item["pubDate"] + "\n"
p.s. the loop is running inside another loop.
p.p.s. this is running inside google app engine application.i have looked at http re... | [
"It might be a problem with buffering, in which case flushing stdout would help.\nimport sys\nsys.stdout.flush()\n\n",
"Are you using some sort of wsgi framework, or just trying to write pure CGI code (which is a mistake?)\nYou probably don't want to be using print at all here, but rather using your framework's m... | [
4,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"printing",
"python"
] | stackoverflow_0004462068_google_app_engine_printing_python.txt |
Q:
Flushing the output in GAE?
I have tried two different ways of flushing the output to the browser in GAE:
from time import sleep
import sys;
print ""
print "Output"
sys.stdout.flush()
sleep(10)
And:
from time import sleep
self.response.out.write("Output")
self.response.out.flush()
sleep(10)
A:
You can't flush t... | Flushing the output in GAE? | I have tried two different ways of flushing the output to the browser in GAE:
from time import sleep
import sys;
print ""
print "Output"
sys.stdout.flush()
sleep(10)
And:
from time import sleep
self.response.out.write("Output")
self.response.out.flush()
sleep(10)
| [
"You can't flush the output to the browser. App Engine sends the entire response all at once when your handler returns. \nReference: http://code.google.com/appengine/docs/python/runtime.html#Responses\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007224434_google_app_engine_python.txt |
Q:
error when running python manage.py syncdb
I have a new server just installed. Everything seems to be fine but when i run:
python manage.py syncdb
it generates follow error:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/usr/lib/python2.6/sit... | error when running python manage.py syncdb | I have a new server just installed. Everything seems to be fine but when i run:
python manage.py syncdb
it generates follow error:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", ... | [
"So I am answering it here so that other people can have answer of same problem:\nAs said by Bill Kary: \nHe have solved this himself. Change all the collation of ALL tables AND fields to utf (utf8_general_ci) stops the error beautifully.\n"
] | [
1
] | [] | [] | [
"django",
"manage.py",
"mysql",
"python"
] | stackoverflow_0005718853_django_manage.py_mysql_python.txt |
Q:
Pass kwargs with invalid key=value pairs to function
The following code:
def f(a=1):
pass
kwargs = {}
kwargs['a'] = 1
kwargs['b'] = 2
f(**kwargs)
(correctly) raises an Exception:
Traceback (most recent call last):
File "tt.py", line 8, in <module>
f(**kwargs)
TypeError: f() got an unexpected keyword a... | Pass kwargs with invalid key=value pairs to function | The following code:
def f(a=1):
pass
kwargs = {}
kwargs['a'] = 1
kwargs['b'] = 2
f(**kwargs)
(correctly) raises an Exception:
Traceback (most recent call last):
File "tt.py", line 8, in <module>
f(**kwargs)
TypeError: f() got an unexpected keyword argument 'b'
Is there a way, with functools or other, to g... | [
"I am a bit astonished that you ask this question and fear that you are doing something you may regret.\nAre you trying to call different methods with the same dictionary providing all arguments combined?\nIf so, then the complexity required to handle this case shouldn't be dealt with in the called methods but the ... | [
5,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0007217328_python.txt |
Q:
Help with speeding up dictionary sort loop in Python?
I have a really ugly loop in my code which is really slowing down my program. The loop basically performs a dictionary comparison where, if a specific key in dict_A is the same as in dict_B, then for all matches a sort is performed which is written to a file.
f... | Help with speeding up dictionary sort loop in Python? | I have a really ugly loop in my code which is really slowing down my program. The loop basically performs a dictionary comparison where, if a specific key in dict_A is the same as in dict_B, then for all matches a sort is performed which is written to a file.
for k, v in A_dict.items():
for i, value in B_dict.items... | [
"Your example code may be inaccurate, but as written,\nsorted_B = [list(value) for key, value in \n groupby(sorted(B_dict.values()), key=itemgetter(2,3))]\n\nwill be the same every time... why is it in a loop at all?\nAlso \nfor k, v in A_dict.items():\n for i, value in B_dict.items():\n if... | [
1
] | [] | [] | [
"dictionary",
"performance",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0007225073_dictionary_performance_python_python_3.x_sorting.txt |
Q:
NumPy: array assignment issue when using custom dtype
I've found the following puzzling behavior with NumPy and a custom dtype for an ndarray:
import numpy as np
# Make a custom dtype with a single triplet of floats (my actual dtype has other
# components, but this suffices to demonstrate the problem.
dt = np.dty... | NumPy: array assignment issue when using custom dtype | I've found the following puzzling behavior with NumPy and a custom dtype for an ndarray:
import numpy as np
# Make a custom dtype with a single triplet of floats (my actual dtype has other
# components, but this suffices to demonstrate the problem.
dt = np.dtype([('a', np.float64, 3)])
# Make a zero array with this d... | [
"If you change the ordering of the indices, like this: points['a'][0][0] = np.array([1, 1, 1]), it works ok for me (python 2.6.5, numpy 1.3.0 on Ubuntu 10.04). I wish I knew why.\n",
"There are many method to assign points, if you want your method works:\npoints[0][0]['a'][:] = np.array([1, 1, 1])\n\nor:\npoints[... | [
3,
2
] | [] | [] | [
"arrays",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0007219306_arrays_multidimensional_array_numpy_python.txt |
Q:
If django is installed using pypm, would pydev detect it?
i have recently asked a question
I rechecked and it seems that pydev does not detect django either, but i can import django in activepython interpreter. so if i installed django using pypm would pydev detect it?
A:
PyDev currently doesn't pick additions ... | If django is installed using pypm, would pydev detect it? | i have recently asked a question
I rechecked and it seems that pydev does not detect django either, but i can import django in activepython interpreter. so if i installed django using pypm would pydev detect it?
| [
"PyDev currently doesn't pick additions to the PYTHONPATH automatically, so, you have to re-configure your interpreter within PyDev (even if only the PYTHONPATH changed).\nSee: http://pydev.org/manual_101_interpreter.html\n"
] | [
1
] | [] | [] | [
"activepython",
"django",
"pypm",
"python"
] | stackoverflow_0007221154_activepython_django_pypm_python.txt |
Q:
Python: maximum recursion depth
A function for returning sum of the sizes of its arguments which could be single file/directory or a list of files/directories, is given below. The code gives an error message RuntimeError: maximum recursion depth exceeded while calling a Python object however I try to test this.
Ho... | Python: maximum recursion depth | A function for returning sum of the sizes of its arguments which could be single file/directory or a list of files/directories, is given below. The code gives an error message RuntimeError: maximum recursion depth exceeded while calling a Python object however I try to test this.
How to fix this?
Thanks
suresh
#!/usr/b... | [
"Instead of writing your own adhoc directory-transversal method, use the built-in os.walk (Documentation) method.\nIn fact, the example in the documentation (link above) computes the total size of non-directory files.\n",
"Last time I checked, the default maximum recursion depth was 1000. You have a few options:\... | [
9,
3,
1,
1
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0007225106_python_recursion.txt |
Q:
Polar plot error bars don't rotate with angle in matplotlib
I want to create a polar bar plot with error bars in matplotlib. When I use the following code all my error bars have a horizontal alignment, and it looks wrong, unless the bar corresponds to the 90 or 270 degree case.
from numpy import *
from matplotlib ... | Polar plot error bars don't rotate with angle in matplotlib | I want to create a polar bar plot with error bars in matplotlib. When I use the following code all my error bars have a horizontal alignment, and it looks wrong, unless the bar corresponds to the 90 or 270 degree case.
from numpy import *
from matplotlib import pyplot as py
r=zeros([16])
err=zeros([16])
for i in ran... | [
"So, it appears that the error bars are created with a Line2D object; that is, a dashed line is plotted with data points corresponding to the error bar positions (x[i],y[i]+yerr[i]). The dashes in the line are always the same, because they are just symbols. This obviously does not work for the polar plot. So this e... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007224155_matplotlib_python.txt |
Q:
Policy Server with gevent-websocket
working on trying to get gevent-websocket working and it's not connecting to my policy server for the flash specification. My policy.py is as follows:
from gevent.server import StreamServer
policy = """<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<site-control... | Policy Server with gevent-websocket | working on trying to get gevent-websocket working and it's not connecting to my policy server for the flash specification. My policy.py is as follows:
from gevent.server import StreamServer
policy = """<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-... | [
"the readline() method won't work here, because Flash sends a '<policy-file-request/>\\0' which is not terminated by newline.\nTry this instead of readline():\nexpected = '<policy-file-request>'\ns.read(len(expected))\n\n"
] | [
2
] | [] | [] | [
"gevent",
"python",
"websocket"
] | stackoverflow_0007223096_gevent_python_websocket.txt |
Q:
Convert Java to python DSA signing
Does anyone know how I would go about converting this java code to python?
/**
* signs the data for the account account
*/
private byte[] sign(String pkStr,byte[] data, String keyType) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
KeyFactory keyFac = nul... | Convert Java to python DSA signing | Does anyone know how I would go about converting this java code to python?
/**
* signs the data for the account account
*/
private byte[] sign(String pkStr,byte[] data, String keyType) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
KeyFactory keyFac = null;
//instantiate the key factory bas... | [
"A DSA signature is defined as a pair of integers (called r and s, respectively). The DSA standard does not mandate a specific encoding of such a signature into a sequence of bytes. So every protocol which uses DSA signatures has to define its own encoding.\nThere are two commonly used DSA signature encodings; one ... | [
3,
1
] | [] | [] | [
"dsa",
"java",
"public_key_encryption",
"python"
] | stackoverflow_0007068733_dsa_java_public_key_encryption_python.txt |
Q:
Python: Program keeps getting into a infinite loop when using float
Here is my original working program:
def num_rushes(required_height, rush_height_gain, back_sliding):
current_height = 0
rushes = 0
while current_height < required_height:
rushes += 1
current_height += rush_height_gain
... | Python: Program keeps getting into a infinite loop when using float | Here is my original working program:
def num_rushes(required_height, rush_height_gain, back_sliding):
current_height = 0
rushes = 0
while current_height < required_height:
rushes += 1
current_height += rush_height_gain
if current_height >= required_height:
break
e... | [
"rush_high_gain gets smaller with each pass through the while-loop. But back_sliding stays constant. If enough passes are made through the loop (about 15), rush_height_gain may be less than backsliding. At that point current_height will get smaller and smaller, and you will never exit the loop.\n",
"If you tempor... | [
7,
2
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0007225451_loops_python.txt |
Q:
Why does Python (WLST) tell me a documented function doesn't exist?
I'm using the Weblogic Scripting Tool aka WLST, a Python-based shell environment, to programmatically edit variables in Plan.xml files for projects to be deployed to the Weblogic server. I can get as far as getting an instance of the WLSTPlan Obje... | Why does Python (WLST) tell me a documented function doesn't exist? | I'm using the Weblogic Scripting Tool aka WLST, a Python-based shell environment, to programmatically edit variables in Plan.xml files for projects to be deployed to the Weblogic server. I can get as far as getting an instance of the WLSTPlan Object, and can run getVariables and other methods to check that it is popula... | [
"Using javap and looking for setters on the WLSTPlan bean shows only the following setter\nvoid setVariableValue(java.lang.String, java.lang.String);\n\nCould be a typo in the docs. Can you try 'setVariableValue' instead.\n",
"The documentation is rather unclear, but from reading between the lines, it looks like ... | [
2,
0
] | [] | [] | [
"python",
"weblogic",
"wlst"
] | stackoverflow_0007184806_python_weblogic_wlst.txt |
Q:
Dict Index's in BeautifulSoup and "if x in Dict"
I don't think I understand how to check if an array index exists...
for tag in soup.findAll("input"):
print tag['type']
if 'type' in tag:
print "b"
Outputs:
2255
text
hidden
text
text
text
Traceback (most recent call last):
... | Dict Index's in BeautifulSoup and "if x in Dict" | I don't think I understand how to check if an array index exists...
for tag in soup.findAll("input"):
print tag['type']
if 'type' in tag:
print "b"
Outputs:
2255
text
hidden
text
text
text
Traceback (most recent call last):
File "/home//workspace//src/x.py", line 268, in <modu... | [
"A BeautifulSoup Tag is not a dict. Sometimes it acts like one in certain ways ([] notation as you discovered gets the value of an attribute), but in other ways it doesn't. in on a Tag will check if a tag is a direct child of that tag; it does not check attributes.\nInstead, you could do something like this:\nif no... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"dictionary",
"python"
] | stackoverflow_0007225518_beautifulsoup_dictionary_python.txt |
Q:
Least brute force way to see how many groups of numbers in a group of numbers add to a given number in C++ or Python
The title is probably a little ambiguous.
There is a given number.
There is a set of numbers all less than the given number and greater than zero.
I want to know how many different combinations of a... | Least brute force way to see how many groups of numbers in a group of numbers add to a given number in C++ or Python | The title is probably a little ambiguous.
There is a given number.
There is a set of numbers all less than the given number and greater than zero.
I want to know how many different combinations of adding numbers there are that equal the given number.
For example if the given number is 14 and the numbers in the set are... | [
"Don't be discouraged by the claims that this is NP-complete. The Wikipedia article on Subset Sum linked by @isbadawi mentions a 1999 paper by Professor David Pisinger with an algorithm that sounds like it would work with your existing constraints in linear time: http://www.sciencedirect.com/science/article/pii/S0... | [
0
] | [] | [] | [
"c++",
"numbers",
"python"
] | stackoverflow_0007225645_c++_numbers_python.txt |
Q:
Multiprocessing between different languages such as PHP and Python
I asked a question before about how to do multiprocessing in Python (although I did not use the word multiprocessing in the former question, because I was not sure I was asking about that yet).
Now I am wondering how to do multiprocessing when you ... | Multiprocessing between different languages such as PHP and Python | I asked a question before about how to do multiprocessing in Python (although I did not use the word multiprocessing in the former question, because I was not sure I was asking about that yet).
Now I am wondering how to do multiprocessing when you have more then one language involved, particularly if you have a PHP scr... | [
"One way to this would be though web services. You could have a PHP process sitting on a web server and running and calling a Python web service (using CherryPy) multiple times. You would pass variables using a standard object notation such as JSON which can be efficiently encoded/decoded by both PHP and Python.\... | [
1
] | [] | [] | [
"multiprocess",
"php",
"python"
] | stackoverflow_0007225684_multiprocess_php_python.txt |
Q:
The most efficient way to store large symmetric sparse matrices in python
I was working on drafting/testing a technique I devised for solving differential equations for speed and efficiency.
It would require a storing, manipulating, resizing, and (at some point) probably diagonalizing very large sparse matrices. ... | The most efficient way to store large symmetric sparse matrices in python | I was working on drafting/testing a technique I devised for solving differential equations for speed and efficiency.
It would require a storing, manipulating, resizing, and (at some point) probably diagonalizing very large sparse matrices. I would like to be able to have rows consisting of zeros and a few (say <5) one... | [
"The most efficient storage method for symmetric sparse matrices is probably sparse skyline format (this is what Intel MKL uses, for example). AFAIK scipy.sparse doesn't contain a sparse, symmetric matrix format. Pysparse, however, does. Using Pysparse, you can build the matrix incrementally using the link list for... | [
7,
4,
3
] | [] | [] | [
"matrix",
"numpy",
"python",
"sparse_matrix"
] | stackoverflow_0007225443_matrix_numpy_python_sparse_matrix.txt |
Q:
Finding form input fields using Mechanize where the field's label contains a string in a list of strings?
Now I understand what the error means, but I'm curious why this doesn't work and if there is an alternative available which will complete the same task. I pass regex's when using Beautiful Soup and am disappoi... | Finding form input fields using Mechanize where the field's label contains a string in a list of strings? | Now I understand what the error means, but I'm curious why this doesn't work and if there is an alternative available which will complete the same task. I pass regex's when using Beautiful Soup and am disappointed to find that Mechanize does not support (?) the same functionality.
input_names is a dict.
TypeError: cont... | [
"Assuming br.form.find_control() doesn't take regexes, we'll need to solve it somehow, e.g. by manually finding and matching all controls. Alternatively, use BS with regex to make the match to literal text, then feed that back to mechanize.\n"
] | [
1
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0007224140_mechanize_python.txt |
Q:
South: run a migration for a column that is both unique and not null
Using South/Django, I am running into a problem where I'm trying to add a UNIQUE and NOT NULL column for a model with existing rows in the database. South prompts me to specify a default for the column, since it is NOT NULL. But since it also has... | South: run a migration for a column that is both unique and not null | Using South/Django, I am running into a problem where I'm trying to add a UNIQUE and NOT NULL column for a model with existing rows in the database. South prompts me to specify a default for the column, since it is NOT NULL. But since it also has a UNIQUE constraint, I can't add a default to the field in models.py, nor... | [
"Yes, this is the approach you should take. You should be doing schemamigration -> datamigration -> schemamigration for this. unfortunately if there is no way to do it in SQL, south cannot do it either. \n"
] | [
13
] | [] | [] | [
"django",
"django_models",
"django_south",
"python"
] | stackoverflow_0007226036_django_django_models_django_south_python.txt |
Q:
Identify folders with a specific string in Python
Simple question here -- all I want to do is identify the folders in a directory which share a specific stub. For example, I would want to isolate all folders which begin with "B07", and they would include "B07.1", "B07.2", etc.
A:
You could use os.listdir or os.... | Identify folders with a specific string in Python | Simple question here -- all I want to do is identify the folders in a directory which share a specific stub. For example, I would want to isolate all folders which begin with "B07", and they would include "B07.1", "B07.2", etc.
| [
"You could use os.listdir or os.walk and filter directories, or glob.glob...\nimport os\nfolders = [x for x in os.listdir(path) if x.startswith('B07')]\n\n",
"import os\npath = './'\nlist = [i for i in os.listdir(path) if i.startswith('B07') and os.path.isdir(i)]\n\n",
"import glob\nglob.glob('*foo*')\n\nhttp:/... | [
3,
1,
1
] | [] | [] | [
"directory",
"python",
"string"
] | stackoverflow_0007226375_directory_python_string.txt |
Q:
noob question on executing cron job
I have a cron job like the following:
07 14 * * 1-5 python /home/foo/cronscript.py
The script:
if __name__ == '__main__':
f = open('/home/foo/cronpass.txt','w')
f.write('abc')
f.close()
Checking the syslog I suppose the command did run, but with an error:
Aug 29 ... | noob question on executing cron job | I have a cron job like the following:
07 14 * * 1-5 python /home/foo/cronscript.py
The script:
if __name__ == '__main__':
f = open('/home/foo/cronpass.txt','w')
f.write('abc')
f.close()
Checking the syslog I suppose the command did run, but with an error:
Aug 29 14:07:01 ubuntuserver CRON[16490]: (www-d... | [
"The usual error with crontab tasks, is that the environment in which they run don't have all the env. vars. you're accustomed to. Maybe here, PATH is not set to all the usual directories, and cron does not find the executable python. You should write the full path to it. as follows.\n07 14 * * 1-5 /usr/bin/python ... | [
3
] | [] | [] | [
"cron",
"linux",
"python"
] | stackoverflow_0007226780_cron_linux_python.txt |
Q:
datetime.datetime.strptime not present in Python 2.4.1
Our team is required to use Python 2.4.1 in certain circumstances. strptime is not present in the datetime.datetime module in Python 2.4.1:
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" f... | datetime.datetime.strptime not present in Python 2.4.1 | Our team is required to use Python 2.4.1 in certain circumstances. strptime is not present in the datetime.datetime module in Python 2.4.1:
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.dateti... | [
"Note that strptime is still in the time module, even as of 2.7.1, as well as in datetime.\nIf, however, you look at the documentation for datetime in a recent version, you will see this under strptime:\n\nThis is equivalent to datetime(*(time.strptime(date_string, format)[0:6]))\n\nso you can use that expression i... | [
20,
11,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0005585706_datetime_python.txt |
Q:
How would I implement a random.choice() like function which returns reproducible results?
I'd like to pass a fixed seed (string) to a function, and then have it randomly select one item from a list. However, it should be the same item from the same list if the same seed it used! Obviously this isn't random at all,... | How would I implement a random.choice() like function which returns reproducible results? | I'd like to pass a fixed seed (string) to a function, and then have it randomly select one item from a list. However, it should be the same item from the same list if the same seed it used! Obviously this isn't random at all, but it should more or less appear to be random and be about equally distributed. It must be qu... | [
"From the Python doc for random, I think this is what you are looking for:\n\nThe functions supplied by this module are actually bound methods of a hidden\n instance of the random.Random class. You can instantiate your own instances\n of Random to get generators that don’t share state.\n\nLike,\n> r = random.Rand... | [
3,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0007226901_python_python_2.7.txt |
Q:
Removing items from a list in a loop
For quite a bit of time now I have been trying to figure out a way to loop through a list and remove the current item that I'm at. I can't seem to get this working as I would like it to. It loops just 1 time through, but I wanted it to loop 2 times. When I remove the removal li... | Removing items from a list in a loop | For quite a bit of time now I have been trying to figure out a way to loop through a list and remove the current item that I'm at. I can't seem to get this working as I would like it to. It loops just 1 time through, but I wanted it to loop 2 times. When I remove the removal line - it loops 2 times.
a = [0, 1]
for i in... | [
"You're changing the list while iterating over it -- z = a doesn't make a copy, it just points z at the same place a points.\nTry \nfor i in a[:]: # slicing a list makes a copy\n print i # remove doesn't return the item so print it here\n a.remove(i) # remove the item from the ori... | [
8,
3,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007226997_list_python.txt |
Q:
Constant in Python Sage? Variable getting wiped out after use
Yesterday I began messing around with Sage, an open source computer algebra system. Sage uses Python to bind several open-source packages into one coding interface.
Unfortunately, not only was Sage new, Python was as well. I spent the better part of to... | Constant in Python Sage? Variable getting wiped out after use | Yesterday I began messing around with Sage, an open source computer algebra system. Sage uses Python to bind several open-source packages into one coding interface.
Unfortunately, not only was Sage new, Python was as well. I spent the better part of today learning both. What can I say? Once a nerd, always a nerd...
Th... | [
"w=var('w'): w is a symbol object with name 'w'.\nw=(x,y,z): w is a tuple of three symbol objects. To use this tuple to define expression function, you can use \"*\" to unpack the tuple: f(*w) is the same as f(x,y,z), when w==(x,y,z).\nSo, the following code will do solve() correctly:\nx=var('x')\ny=var('y')\nz=var... | [
1
] | [] | [] | [
"python",
"sage"
] | stackoverflow_0007226453_python_sage.txt |
Q:
How to pass a string + web url and receive the response using python
I'm using Python and Google Translate. When I click on Listen while translating, a sound file is generated and a URL is passed like so: http://translate.google.com/translate_tts?tl=en&q=text.
I want to generate URLs locally using Python then send... | How to pass a string + web url and receive the response using python | I'm using Python and Google Translate. When I click on Listen while translating, a sound file is generated and a URL is passed like so: http://translate.google.com/translate_tts?tl=en&q=text.
I want to generate URLs locally using Python then send them to the web and receive these sound files from Google Translate. I tr... | [
"You need to change the user-agent so that the website thinks you are connecting with a browser. Try the following bit of code: \nimport urllib2\n\nurl = \"http://translate.google.com/translate_tts?tl=en&q=text\"\nrequest = urllib2.Request(url)\nrequest.add_header('User-agent', 'Mozilla/5.0') \nopener = urllib2.bui... | [
6
] | [] | [] | [
"google_translate",
"python",
"text_to_speech"
] | stackoverflow_0007226167_google_translate_python_text_to_speech.txt |
Q:
Interact with SQL database using only Python 2.4
I have a website on an Australian webhost. I have designed my website to allow people to login & their login details are stored in an SQLite3 database. I interact with the SQLite3 database using pythons SQLite3 module(found only in python2.5 & up)
My Problem: the we... | Interact with SQL database using only Python 2.4 | I have a website on an Australian webhost. I have designed my website to allow people to login & their login details are stored in an SQLite3 database. I interact with the SQLite3 database using pythons SQLite3 module(found only in python2.5 & up)
My Problem: the webhost runs Python 2.4 so I cannot communicate with(que... | [
"There is a Python MySQL Module, called MySQLDB, which supports Python 2.3-2.7: http://sourceforge.net/projects/mysql-python/\nThe User Guide can be found here: http://mysql-python.sourceforge.net/MySQLdb.html\n",
"Check out pysqlite. It is the same module as in the newer python versions and I have used it no pro... | [
0,
0
] | [] | [] | [
"mysql",
"python",
"sql",
"sqlite",
"web_hosting"
] | stackoverflow_0007226131_mysql_python_sql_sqlite_web_hosting.txt |
Q:
Set ModelForm integer field as unrequired
I currently have a ModelForm set up in Django, but would like to make one of the fields of the form unrequired. Here's my forms.py:
from django.forms import ModelForm
from add_flair.models import User
class UserForm(ModelForm):
class Meta:
model = User
d... | Set ModelForm integer field as unrequired | I currently have a ModelForm set up in Django, but would like to make one of the fields of the form unrequired. Here's my forms.py:
from django.forms import ModelForm
from add_flair.models import User
class UserForm(ModelForm):
class Meta:
model = User
def __init__(self, *args, **kwargs):
su... | [
"Add blank=True, null=True to your field declaration im models.py (and don't forget to reflect this change in DB, by migration or manually).\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007227518_django_python.txt |
Q:
cv.filter2D return TypeError
My platform is Mac OS X 10.6 and install python 2.7.2/opencv by homebrew.
I want to use cv.filter2D to do Lanczos resampling, here is my code:
import cv
src = cv.imread('img.jpg')
dst = cv.CloneMat(src)
kernel = cv.CreateMat(7, 7, cv.CV_32FC1)
for i in range(-3, 4):
for j in rang... | cv.filter2D return TypeError | My platform is Mac OS X 10.6 and install python 2.7.2/opencv by homebrew.
I want to use cv.filter2D to do Lanczos resampling, here is my code:
import cv
src = cv.imread('img.jpg')
dst = cv.CloneMat(src)
kernel = cv.CreateMat(7, 7, cv.CV_32FC1)
for i in range(-3, 4):
for j in range(-3, 4):
kernel[i+3, j+3]... | [
"what is the version of your opencv, my version is:\n>>> import cv2 as cv\n>>> cv.__version__\n'$Rev: 4557 $'\n\nI can use a ndarray as the kernel, and don't need to create an empty array for the result, filter2D() will return a new ndarray.\nimport cv2 as cv\nimport numpy as np\nsrc = cv.imread('img.jpg')\nkernel ... | [
3
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0007227541_opencv_python.txt |
Q:
strange error of the semaphore in python
Can somebody please explain to me why I am receiving an error in the following code?
win32event.WaitForSingleObject(self.my_lock, win32event.INFINITE)
win32event.ReleaseSemaphore(self.big_semaphore, 1)
win32event.ReleaseSemaphore(self.small_semaphore, 1)
win32event.Releas... | strange error of the semaphore in python | Can somebody please explain to me why I am receiving an error in the following code?
win32event.WaitForSingleObject(self.my_lock, win32event.INFINITE)
win32event.ReleaseSemaphore(self.big_semaphore, 1)
win32event.ReleaseSemaphore(self.small_semaphore, 1)
win32event.ReleaseMutex(self.my_lock)
The strange thing here t... | [
"WAIT_ABANDONED is not really an error. It means that another thread or process was owning the mutex and terminated without releasing the mutex. The operating system grants ownership of the mutex to the next waiting thread (the one which receives the WAIT_ABANDONED result from WaitFromSingleObject()). \nWhen receiv... | [
1
] | [] | [] | [
"python",
"winapi",
"windows"
] | stackoverflow_0007226792_python_winapi_windows.txt |
Q:
MongoKit Schemaless
I have an object like follows:
@connection.register
class User(Document):
__collection__ = 'users'
__database__ = 'crucible_projects'
use_schemaless = True
structure = {
'name': unicode,
'password': unicode,
'last_name': unicode,
'first_name': uni... | MongoKit Schemaless | I have an object like follows:
@connection.register
class User(Document):
__collection__ = 'users'
__database__ = 'crucible_projects'
use_schemaless = True
structure = {
'name': unicode,
'password': unicode,
'last_name': unicode,
'first_name': unicode,
'email': un... | [
"It was a bug. Fixed in v0.7.1\nChangelog :\n\n* change MongokitMasterSlaveConnection to MasterSlaveConnection for consistency\n* fix #57 -- support pymongo > 1.9 in grid.py\n* fix #45 -- remove automatique index creation\n* fix #43 -- slicing a cursor should return a mongokit document, not dict\n* Dont try to conv... | [
1
] | [] | [] | [
"mongodb",
"mongokit",
"python"
] | stackoverflow_0007158589_mongodb_mongokit_python.txt |
Q:
python: how to write daemon in Linux
I have a .py file that is ran by:
python a.py &
I am using a ssh to run the command, after it I have to log off. I find after some time the process is exited. I suspect it's Linux send some signal to it? I think if I can make the daemon then I can avoid this?
A:
Although nohu... | python: how to write daemon in Linux | I have a .py file that is ran by:
python a.py &
I am using a ssh to run the command, after it I have to log off. I find after some time the process is exited. I suspect it's Linux send some signal to it? I think if I can make the daemon then I can avoid this?
| [
"Although nohup will work, it's a quick and dirty solution. To make a proper daemon process you need to use SysV init or (If you are running Ubuntu 6.10+ or Fedora 9+) upstart.\nHere's a simple script that starts a.py and restarts it whenever it gets killed (up to 5 times inside a 5 minute span):\nrespawn\n\nrespa... | [
7,
5,
4,
3,
2
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0004755760_linux_python.txt |
Q:
creating a output file when the output file exists in the path
How do I code in python the option that when the output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?
A:
You can use os.path.exists to check if a file already exists. The rest is... | creating a output file when the output file exists in the path | How do I code in python the option that when the output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?
| [
"You can use os.path.exists to check if a file already exists. The rest is a simple loop that tries new filenames.\n",
"Something like\nimport os.path\n\ndef getnewfilename(filename):\n testfile = filename\n i = 0\n while os.path.exists(testfile):\n i += 1\n testfile = \"%s_%s\" % (testfil... | [
2,
2,
0
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0007228081_python_python_2.5.txt |
Q:
Query between three tables, many to many relationship
I have three databases in GAE. Hobby, Attendee and Event.
class Hobby(db.Model):
name = db.StringProperty()
htest = Hobby.get_or_insert('tennis')
htest.name = 'tennis'
htest.put()
htest = Hobby.get_or_insert('basketball')
htest.name = 'basketball'
htest... | Query between three tables, many to many relationship | I have three databases in GAE. Hobby, Attendee and Event.
class Hobby(db.Model):
name = db.StringProperty()
htest = Hobby.get_or_insert('tennis')
htest.name = 'tennis'
htest.put()
htest = Hobby.get_or_insert('basketball')
htest.name = 'basketball'
htest.put()
htest = Hobby.get_or_insert('food')
class Event(db... | [
"I think you should record the invitations send in a table, say \"invitationsSend\" with two fields : event and attendee, which two fields are making a unique primary key.\nTo build this, you will have to select the data between both your tables event and attendees :\ninsert into invitationsSend(select E.Event, A.A... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007227562_google_app_engine_python.txt |
Q:
python metaclass doesn't remember the new value
I wrote a class Person with a metaclass Spell. In the metaclass I change an attribute and it is ok, but if i want to use this new value for another operation, it doesn't work and it use the previous value.
How can i fix this?
class Spell(type):
def __new__(cls,cl... | python metaclass doesn't remember the new value | I wrote a class Person with a metaclass Spell. In the metaclass I change an attribute and it is ok, but if i want to use this new value for another operation, it doesn't work and it use the previous value.
How can i fix this?
class Spell(type):
def __new__(cls,classname,super,classdict):
def pph( hours ): r... | [
"The lambda you created refers to the dictionary filled during class construction. Later (after class creation) changes to class variables are not reflected in it, but even if that was the case, the line persona4.pay_per_hour = 15 assigns a new instance attribute instead of changing the class attribute. Use self.pa... | [
2,
1
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0007228676_metaclass_python.txt |
Q:
Python scope / namespace issue
I have two python modules:
//// funcs.py
from classes import *
def func():
d = D()
print "func"
if __name__ == "__main__":
c = C()
//// classes.py
from funcs import *
class C:
def __init__(self):
print "C class"
func()
class D:
def __init__(se... | Python scope / namespace issue | I have two python modules:
//// funcs.py
from classes import *
def func():
d = D()
print "func"
if __name__ == "__main__":
c = C()
//// classes.py
from funcs import *
class C:
def __init__(self):
print "C class"
func()
class D:
def __init__(self):
print "D class"
Runni... | [
"This one works fine without complicating your code:\n///funcs.py\nimport classes\n\ndef func():\n d = classes.D()\n print \"func\"\n\nif __name__ == \"__main__\":\n c = classes.C()\n\n///classes.py\nimport funcs\n\nclass C:\n def __init__(self):\n print \"C class\"\n funcs.func()\n\nclass... | [
5,
2
] | [] | [] | [
"namespaces",
"python",
"scope"
] | stackoverflow_0007228594_namespaces_python_scope.txt |
Q:
MuxerError in pymedia
so i have this code and when i run it i get the error:
Traceback (most recent call last):
File "C:/Users/tryer.py", line 7, in <module>
da=dm.getInfo()
MuxerError: The header has not been read yet. Cannot get stream information.
-
import glob
import pymedia
for x in glob... | MuxerError in pymedia | so i have this code and when i run it i get the error:
Traceback (most recent call last):
File "C:/Users/tryer.py", line 7, in <module>
da=dm.getInfo()
MuxerError: The header has not been read yet. Cannot get stream information.
-
import glob
import pymedia
for x in glob.glob('C:\Downloaded/*mp3')... | [
"Can it be that the file must explicitly be opened ?\n f= wave.open( 'YOUR FILE NAME', 'rb' )\n\nI'm not sure, but please try.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007228248_python.txt |
Q:
Django (dojango) FieldRegex not being passed
I know there is not much on stackoverflow on dojango, but I thought I'd ask anyway.
Dojango describes RegexField as follows:
class RegexField(DojoFieldMixin, fields.RegexField):
widget = widgets.ValidationTextInput
js_regex = None # we additionally have to defin... | Django (dojango) FieldRegex not being passed | I know there is not much on stackoverflow on dojango, but I thought I'd ask anyway.
Dojango describes RegexField as follows:
class RegexField(DojoFieldMixin, fields.RegexField):
widget = widgets.ValidationTextInput
js_regex = None # we additionally have to define a custom javascript regexp, because the python o... | [
"After three days of beavering away I fould that you need to send regex and js_regex, though regex is not used:\npost_code = RegexField(\n regex='',\n required = True,\n widget=ValidationTextInput(\n attrs={\n 'invalid': 'Post Code in incorrect format',\n 'regExp': '[A-Z]{1,2}\... | [
1,
0
] | [] | [] | [
"dijit.form",
"django",
"dojo",
"python"
] | stackoverflow_0007196148_dijit.form_django_dojo_python.txt |
Q:
Is Slow compiling of scala a factor against using it in website project when compared to Python?
In my website project, there is conflict right now on using python or scala. One argument that went against scala was its slow compile time whereas Python does not even compile.
According to answers given in this ques... | Is Slow compiling of scala a factor against using it in website project when compared to Python? | In my website project, there is conflict right now on using python or scala. One argument that went against scala was its slow compile time whereas Python does not even compile.
According to answers given in this question
Why does IntelliJ IDEA compile Scala so slowly?
So my question is for a website, what's more imp... | [
"With a compiled language you only compile it once. Even in python the bytecode is only generated if the source has changed. I would imagine this is the same with Scala. Looking for which language runs faster is a foolish endeavor as it is \"just another language war.\" Instead of looking for speed you should be lo... | [
3,
1
] | [] | [] | [
"compile_time",
"performance",
"python",
"scala"
] | stackoverflow_0007229231_compile_time_performance_python_scala.txt |
Q:
Python LXML catalog lookup
I'm making an SCons file for building Docbook documentation. In order to trace dependencies I would like some way to resolve catalog file lookups to an absolute path to a file.
So say I have a bit of Docbook XML :
<book xmlns="http://docbook.org/ns/docbook"
xmlns:xi="http://www.w3... | Python LXML catalog lookup | I'm making an SCons file for building Docbook documentation. In order to trace dependencies I would like some way to resolve catalog file lookups to an absolute path to a file.
So say I have a bit of Docbook XML :
<book xmlns="http://docbook.org/ns/docbook"
xmlns:xi="http://www.w3.org/2001/XInclude">
<info>
... | [
"Lxml uses the catalog support from libxml2. Use the environment variable XML_CATALOG_FILES to provide a list of catalogs (you could set this from python as well, using os.environ), or, if this variable is not present, it checks for the existence of /etc/xml/catalog (can't use this one on windows of course).\nAn al... | [
0
] | [] | [] | [
"lxml",
"python",
"xmlcatalog"
] | stackoverflow_0007228583_lxml_python_xmlcatalog.txt |
Q:
Hacking Django Admin, hooks for login/logout
How do I add hooks to the Django Admin, such that I can execute a function when the user logs in or out?
A:
Django does sadly not send any signals on that events.... But you could make your own custom AuthorizationBackend that enables you to do so:
from django.dispatc... | Hacking Django Admin, hooks for login/logout | How do I add hooks to the Django Admin, such that I can execute a function when the user logs in or out?
| [
"Django does sadly not send any signals on that events.... But you could make your own custom AuthorizationBackend that enables you to do so:\nfrom django.dispatch import Signal\n\npost_login = Signal(providing_args=['user'])\n\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.contrib.auth.models ... | [
7,
4,
4,
2
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003037558_django_django_admin_python.txt |
Q:
Determining the height of a TreeView Row
I want to set the height of a treeview widget to accommodate N rows, in order to do that I need to identify a single row height.
I am using the code below:
path = Gtk.TreePath().new_first()
height = tree_view.get_cell_area(path, column).height
After creating the tree widg... | Determining the height of a TreeView Row | I want to set the height of a treeview widget to accommodate N rows, in order to do that I need to identify a single row height.
I am using the code below:
path = Gtk.TreePath().new_first()
height = tree_view.get_cell_area(path, column).height
After creating the tree widget, filling the data model, and selecting the ... | [
"Probably this : (read from the gtk site) :\n\"If path points to a path not currently displayed, the y and height attributes of the rectangle will be 0. The sum of all cell rects does not cover the entire tree; there are extra pixels in between rows, for example. The returned rectangle is equivalent to the cell_are... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0007221447_gtk_pygtk_python.txt |
Q:
In Python find and extract only required info
I am getting info from an HP device and storing it in a variable named data.
Now, I want to extract only the values for Chassis: and Serial Number: from the output, an example of which is below (I obtain it by typing the command show module):
==========================... | In Python find and extract only required info | I am getting info from an HP device and storing it in a variable named data.
Now, I want to extract only the values for Chassis: and Serial Number: from the output, an example of which is below (I obtain it by typing the command show module):
============================
coaza077-cor-01> show module
Status and Counte... | [
">>> data = \"\"\"\n============================\ncoaza077-cor-01> show module\n\n Status and Counters - Module Information\n Chassis: 2900-24G J9049A Serial Number: SG748KI09F\n Slot Module Description Serial Number\n ----- ---------------------------------------- --------------... | [
7,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007229705_python.txt |
Q:
convert huffman code string to binary
I am having problem with how to convert huffman encoding string to binary python.
This question involves nothing of the huffman algorithm.
It is like this:
I can get an encoded huffman string, say 01010101010. Note, it is a string.
But now I want to save the string representat... | convert huffman code string to binary | I am having problem with how to convert huffman encoding string to binary python.
This question involves nothing of the huffman algorithm.
It is like this:
I can get an encoded huffman string, say 01010101010. Note, it is a string.
But now I want to save the string representation into real binary.
In the huffman encode... | [
"There are two different \"binary\" representations in Python that you might want to use.\nBignum\nOne is a \"bignum\" or arbitrary-precision integer. This type is called long in Python 2.x and int in Python 3.x. As the name suggests, this representation is semantically an integer of arbitrary length, so it's usefu... | [
2,
2,
1
] | [] | [] | [
"binary",
"huffman_code",
"python"
] | stackoverflow_0007225601_binary_huffman_code_python.txt |
Q:
Measure cpu usage of child but not grandchildren
This might be an obvious thing, but I can't seem to figure out how to do it.
Assuming that I spawn a process like this:
popen = subprocess.Popen(args, executable=executable,
bufsize=-1,
stdin=s... | Measure cpu usage of child but not grandchildren | This might be an obvious thing, but I can't seem to figure out how to do it.
Assuming that I spawn a process like this:
popen = subprocess.Popen(args, executable=executable,
bufsize=-1,
stdin=subprocess.PIPE,
stdo... | [
"You can use psutil\nimport psutil\npopen = ...\np = psutil.Process(popen.pid)\nprint p.get_cpu_times()\n\n"
] | [
2
] | [] | [] | [
"python",
"rusage",
"subprocess"
] | stackoverflow_0007229299_python_rusage_subprocess.txt |
Q:
Locking on file locations in a large Python project
When a Python project gets big, certain code segments, such as utility functions, tend to be run from various locations:
from a __main__
from a django server process
from a test in a test suite
In each case the working directory for the python interpreter may b... | Locking on file locations in a large Python project | When a Python project gets big, certain code segments, such as utility functions, tend to be run from various locations:
from a __main__
from a django server process
from a test in a test suite
In each case the working directory for the python interpreter may be different and assuming the project spans over a sub-dir... | [
"using the following variable to get the directory of the project may help \n\n __file__ \n\nHow to make a python program path independent?\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007230237_python.txt |
Q:
Nested Cluster in pydot
I want to arrange the nodes in such a manner that there are 2 clusters A and B.
B has further 2 clusters C and D.
For the same i wrote the below program in which i am adding 2 clusters inside one and then adding cluster B as a subgraph in main graph.
However the nested boxes do not appear. ... | Nested Cluster in pydot | I want to arrange the nodes in such a manner that there are 2 clusters A and B.
B has further 2 clusters C and D.
For the same i wrote the below program in which i am adding 2 clusters inside one and then adding cluster B as a subgraph in main graph.
However the nested boxes do not appear. Can someone tell me what am i... | [
"Neato does not support clusters, as it uses a spring model where node placement is very dynamic. If you replace neato engine with dot engine, your clusters will appear correcly.\n"
] | [
3
] | [] | [] | [
"pydot",
"python"
] | stackoverflow_0006368920_pydot_python.txt |
Q:
Formating a text file in python 2
I have a file text that has the following rows:
1231231.txt
231231.txt
24141241.txt
3123123.txt
341241241.txt
4123412.txt
iplist.txt
What i want to know is how can i make the lines look like this:
1231231
231231
24141241
3123123
341241241
4123412
in python 2.
I have tried somet... | Formating a text file in python 2 | I have a file text that has the following rows:
1231231.txt
231231.txt
24141241.txt
3123123.txt
341241241.txt
4123412.txt
iplist.txt
What i want to know is how can i make the lines look like this:
1231231
231231
24141241
3123123
341241241
4123412
in python 2.
I have tried something like this with no succes :
with op... | [
"with open('iplist.txt') as fd:\n my_list = [line.strip().rstrip('.txt') for line in fd]\n\nprint ' '.join(my_list)\n\noutputs:\n1231231 231231 24141241 3123123 341241241 4123412\n\nassuming this:\n$ cat iplist.txt \n1231231.txt\n231231.txt\n24141241.txt\n3123123.txt\n341241241.txt\n4123412.txt\n\nPlease note th... | [
0
] | [] | [] | [
"python",
"text"
] | stackoverflow_0007230462_python_text.txt |
Q:
Button Label change on EVT_BUTTON in wxpython?
Some system info before proceeding further:
Platform: Mac OS X 10.7.1
Python Version: ActiveState Python 2.7.1
wxPython Version: wxPython2.9-osx-cocoa-py2.7
I want the button label to be changed while performing a task
So, here is what I did/want:
self.run_button=wx.B... | Button Label change on EVT_BUTTON in wxpython? | Some system info before proceeding further:
Platform: Mac OS X 10.7.1
Python Version: ActiveState Python 2.7.1
wxPython Version: wxPython2.9-osx-cocoa-py2.7
I want the button label to be changed while performing a task
So, here is what I did/want:
self.run_button=wx.Button(self.panel,ID_RUN_BUTTON,label='Install')
self... | [
"The button never gets a chance to redraw itself with the new label because you're running your logic (installation_task()) on the GUI thread.\nYou need to run installation_task() on a background thread so you don't lock up the GUI.\n",
"The \"installation_task\" function that you're running is blocking the GUI's... | [
3,
2
] | [] | [] | [
"button",
"label",
"python",
"wxpython"
] | stackoverflow_0007225179_button_label_python_wxpython.txt |
Q:
Using PyObject_IsInstance
My application embeds python by dynamically loading it. I need to obtain the values from the dictionary of the script being executed.
pFnPyDict_GetItemString *pFGetItemString = NULL;
pFGetItemString = (pFnPyDict_GetItemString *)::GetProcAddress(hModulePython, PyDict_GetItemString);
if ... | Using PyObject_IsInstance | My application embeds python by dynamically loading it. I need to obtain the values from the dictionary of the script being executed.
pFnPyDict_GetItemString *pFGetItemString = NULL;
pFGetItemString = (pFnPyDict_GetItemString *)::GetProcAddress(hModulePython, PyDict_GetItemString);
if (pFGetItemString)
{
PyObjec... | [
"Do you only want to check for ints? If so you're better off using PyInt_Check instead.\nAdditional: Some advice, that you didn't ask for but which might help you. :) Are you using C or C++. If it's the later, consider using Boost.Python instead of the Python C API — it will make things a lot easier. Exposing funct... | [
0,
0
] | [] | [] | [
"python",
"types"
] | stackoverflow_0007227019_python_types.txt |
Q:
How to converting Wikipedia Article to RSS Feed item
Problem statement:
A python script should be created to generate the rss feed of Wikipedia's Featured Articles for several languages.
English rss feed exists I need to create similar for other languages. Generation of English rss is pretty easy using the url s... | How to converting Wikipedia Article to RSS Feed item | Problem statement:
A python script should be created to generate the rss feed of Wikipedia's Featured Articles for several languages.
English rss feed exists I need to create similar for other languages. Generation of English rss is pretty easy using the url structure of this type of urls http://en.wikipedia.org/wiki... | [
"I wouldn't convert the wiki page. I would convert the english rss, take feedparser to get the feed. Convert it with your favorite langauge api then send it back out using twisted to serve the rss feed.\n"
] | [
0
] | [] | [] | [
"mediawiki",
"python",
"web_scraping",
"wikipedia",
"wikipedia_api"
] | stackoverflow_0007230350_mediawiki_python_web_scraping_wikipedia_wikipedia_api.txt |
Q:
What method calls `__init__()` in Python classes
I was wondering how __init__() methods get called. Does __new__() calls it, or __call__() calls it after it created an instance with __new__(), or some other way?
A:
Python determines whether __new__() should call __init__():
If __new__() returns an instance of c... | What method calls `__init__()` in Python classes | I was wondering how __init__() methods get called. Does __new__() calls it, or __call__() calls it after it created an instance with __new__(), or some other way?
| [
"Python determines whether __new__() should call __init__():\n\nIf __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().\n\n__init__() will not b... | [
8,
3
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0007230636_class_methods_python.txt |
Q:
2D grid data visualization in Python
I need to visualize some data. It's basic 2D grid, where each cell have float value. I know how to e.g. assign color to value and paint grid in OpenCV. But the point here is that there are so many values so it's nearly impossible to do that. I am looking for some method, where ... | 2D grid data visualization in Python | I need to visualize some data. It's basic 2D grid, where each cell have float value. I know how to e.g. assign color to value and paint grid in OpenCV. But the point here is that there are so many values so it's nearly impossible to do that. I am looking for some method, where I could use gradient. For example value -5... | [
"Matplotlib has the imshow method for plotting arrays:\nimport matplotlib as mpl\nfrom matplotlib import pyplot\nimport numpy as np\n\n# make values from -5 to 5, for this example\nzvals = np.random.rand(100,100)*10-5\n\n# make a color map of fixed colors\ncmap = mpl.colors.ListedColormap(['blue','black','red'])\nb... | [
53,
9
] | [] | [] | [
"colors",
"gradient",
"grid",
"python",
"visualization"
] | stackoverflow_0007229971_colors_gradient_grid_python_visualization.txt |
Q:
Django page hit counter concurrency
Im a django newbie. Im making a crude hit counter as an assignment for a course in web programming at Uni. I made a class HitCount:
from django.db import models
# Create your models here.
class HitCount(models.Model):
count = models.IntegerField()
And then I use this code... | Django page hit counter concurrency | Im a django newbie. Im making a crude hit counter as an assignment for a course in web programming at Uni. I made a class HitCount:
from django.db import models
# Create your models here.
class HitCount(models.Model):
count = models.IntegerField()
And then I use this code in the views file:
def index(request):
... | [
"Off topic, but you should be catching HitCount.DoesNotExist in your try/except, since you really only want to execute the code in the except if the HitCount object doesn't exist yet.\nIf it's possible, you might want to look at something like Redis (or another key/val store) to do your hit counter.\nRedis provides... | [
3,
2,
0
] | [] | [] | [
"auto_increment",
"concurrency",
"django",
"python"
] | stackoverflow_0007227123_auto_increment_concurrency_django_python.txt |
Q:
How to stop python Regular Expression being too greedy
I'm trying to match (in Python) the show name and season/episode numbers from tv episode filenames in the format:
Show.One.S01E05.720p.HDTV.x264-CTU.mkv
and
Show.Two.S08E02.HDTV.XviD-LOL.avi
My regular expression:
(?P<show>[\w\s.,_-]+)\.[Ss]?(?P<season>[\d]{1,... | How to stop python Regular Expression being too greedy | I'm trying to match (in Python) the show name and season/episode numbers from tv episode filenames in the format:
Show.One.S01E05.720p.HDTV.x264-CTU.mkv
and
Show.Two.S08E02.HDTV.XviD-LOL.avi
My regular expression:
(?P<show>[\w\s.,_-]+)\.[Ss]?(?P<season>[\d]{1,2})[XxEe]?(?P<episode>[\d]{2})
matches correctly on Show Two... | [
"Change the greedity on first match:\n p=re.compile('(?P<show>[\\w\\s.,_-]+?)\\.[Ss]?(?P<season>[\\d]{1,2})[XxEe]?(?P<episode>[\\d]{2})')\n print p.findall(\"Game.of.Thrones.S01E05.720p.HDTV.x264-CTU.mkv\")\n [('Game.of.Thrones', '01', '05')]\n print p.findall(\"Entourage.S08E02.HDTV.XviD-LOL.avi\")\n [('Entourage'... | [
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007231258_python_regex.txt |
Q:
How can I use "Expect: 100-continue" header in Twisted Web?
I've been working with AkaDAV, a Twisted based WebDAV server, and I'm trying to support the full litmus test suite. I'm currently stuck on the http sub-suite.
Specifically, I can run:
$ TESTS=http litmus http://localhost:8080/steder/
-> running `http':
... | How can I use "Expect: 100-continue" header in Twisted Web? | I've been working with AkaDAV, a Twisted based WebDAV server, and I'm trying to support the full litmus test suite. I'm currently stuck on the http sub-suite.
Specifically, I can run:
$ TESTS=http litmus http://localhost:8080/steder/
-> running `http':
0. init.................. pass
1. begin................. pass
... | [
"After some more investigation it's pretty clear how to modify the HTTP protocol implementation to support this use case. It looks like the official fix will be in Twisted soon but in the meantime I'm using this as a workaround.\nJust include this code before you instantiate your Site (or t.w.http.HTTPFactory):\nf... | [
1
] | [] | [] | [
"http",
"python",
"twisted",
"webdav"
] | stackoverflow_0007212851_http_python_twisted_webdav.txt |
Q:
Search by tag contents with BeautifulSoup
I would like to search for a particular tag by it's text contents. For example:
<a href="http://goinghere.com">Lets go somewhere</a>
I want to find the above by searching for the text 'Lets go somewhere'.
I am currently doing it using re. Can it be done in BeautifulSoup o... | Search by tag contents with BeautifulSoup | I would like to search for a particular tag by it's text contents. For example:
<a href="http://goinghere.com">Lets go somewhere</a>
I want to find the above by searching for the text 'Lets go somewhere'.
I am currently doing it using re. Can it be done in BeautifulSoup or is it better to use re in this case?
| [
"s = BeautifulSoup(...)\ns.find(text='Lets go somewhere')\n\nYou can also use regex.\nUsing BeautifulSoup to find a HTML tag that contains certain text\nEdit: While the find method prints a string if you use it on the command line, that's actually just a representation of the object it returns; you can access the p... | [
2
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0007231769_beautifulsoup_html_python.txt |
Q:
Why I got messy characters while opening url using urllib2?
Here's my code, you guys can also test it out. I always get messed-up characters instead of page source.
Header = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 GTB7.1 (.NET CLR 3.5.30729)"}
Req =... | Why I got messy characters while opening url using urllib2? | Here's my code, you guys can also test it out. I always get messed-up characters instead of page source.
Header = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 GTB7.1 (.NET CLR 3.5.30729)"}
Req = urllib2.Request("http://rlslog.net", None, Header)
Response = u... | [
"As Bruce already suggested, it seems to be a problem with compression. The server returns gzip compressed content, but urllib2 does not support automatic gzip compression. In fact, the server is misbehaving in this case as far as I know: it should only compress the content if an Accept-encoding: gzip header is pre... | [
1,
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0007231280_python_urllib_urllib2.txt |
Q:
Python List: Is this the best way to remove duplicates while preserving order?
Possible Duplicates:
How do you remove duplicates from a list in Python whilst preserving order?
Algorithm - How to delete duplicate elements in a list efficiently?
I've read a lot of methods for removing duplicates from a python list... | Python List: Is this the best way to remove duplicates while preserving order? |
Possible Duplicates:
How do you remove duplicates from a list in Python whilst preserving order?
Algorithm - How to delete duplicate elements in a list efficiently?
I've read a lot of methods for removing duplicates from a python list while preserving the order. All the methods appear to require the creation of a fu... | [
"a.index(x) itself will be O(n) as the list has to be searched for the value x. The overall runtime is O(n^2).\n\"Saving\" function calls does not make a bad algorithm faster than a good one.\nMore efficient (O(n)) would probably be:\nresult = []\nseen = set()\nfor i in a:\n if i not in seen:\n result.app... | [
6,
1
] | [] | [] | [
"duplicates",
"list",
"python"
] | stackoverflow_0007232220_duplicates_list_python.txt |
Q:
Is this an appropriate way to define and use a Python exception?
I just want to make sure I'm doing this in the proper "pythonic" way - I want to make sure I've defind - and am using - this exception class correctly. Especially the eval(repr()) logic - it's mostly for cleanliness, I understand why you end up with... | Is this an appropriate way to define and use a Python exception? | I just want to make sure I'm doing this in the proper "pythonic" way - I want to make sure I've defind - and am using - this exception class correctly. Especially the eval(repr()) logic - it's mostly for cleanliness, I understand why you end up with quotes around the string repr() returns, but I don't like to log them... | [
"eval(repr(self.val))\n\nEek, what are you trying to accomplish here? isn't self.val already supposed to be a string?\nThe way to avoid the quotes that repr attaches is not to use it in the first place.\nIf you're worried that the value passed to the constructor won't be a string, well - that will fail in the const... | [
4,
2
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0007232234_exception_python.txt |
Q:
Getting started with Python on Mac OS X but having trouble with GUI
I am sure this is very simple but I can't find an answer anywhere. Let's say I have this simple temperature conversion program called ConversionSelector.py that looks like
# Helper function to print all menu items:
def displayMenu():
print 'Te... | Getting started with Python on Mac OS X but having trouble with GUI | I am sure this is very simple but I can't find an answer anywhere. Let's say I have this simple temperature conversion program called ConversionSelector.py that looks like
# Helper function to print all menu items:
def displayMenu():
print 'Temperature Conversions Menu:';
print '(1) Convert Fahrenheit to Celsiu... | [
"Add this to the bottom of your file:\nif __name__ == '__main__':\n select()\n\nThis will make python ConversionSelector.py run your select function. What's happening here is that __name__ is __main__ when invoking your script directly, so you need to tell the interpreter to run your main function.\nAlternatively... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007232567_python.txt |
Q:
Is this a safe way to increment and get the value of a counter in Django?
I'm using MySQL with the InnoDB engine and REPEATABLE-READ isolation level.
I have written a function which I think should atomically increment an IntegerField, and give me the value after the increment. I would like opinions on whether my ... | Is this a safe way to increment and get the value of a counter in Django? | I'm using MySQL with the InnoDB engine and REPEATABLE-READ isolation level.
I have written a function which I think should atomically increment an IntegerField, and give me the value after the increment. I would like opinions on whether my code is robust against concurrency issues.
My code looks like this:
class MyMod... | [
"A general rule-of-thumb is that any sort of custom queries or customized query behavior should go into manager methods.\nThis makes sense in your case, because you can increment, save and return the version number at a very low level: during the actual query. \nThus, use a manager (object = MyManager()) and write ... | [
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0007148859_django_mysql_python.txt |
Q:
Get Total number of records in gae datastore table
How to get the total number of records in gae datastore table ?
Query
result = db.GqlQuery("Select * from stocklist ORDER BY part_number")
print result.count()
The output will shows 1000 only. But it will contails more than 5000 records. Why?
A:
The cou... | Get Total number of records in gae datastore table | How to get the total number of records in gae datastore table ?
Query
result = db.GqlQuery("Select * from stocklist ORDER BY part_number")
print result.count()
The output will shows 1000 only. But it will contails more than 5000 records. Why?
| [
"The count method has a default limit of 1000 which can be overridden.\nex. result.count(99999) will count up to 99,999 records.\nThe generally accepted best practice here is to use a sharded counter, so that you are doing the bulk of your work during the write operation rather than the read.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0007226941_google_app_engine_gql_python.txt |
Q:
Pyparsing: Attempt to be non-greedy causes infinite loop
I'm trying to create a parser for the RCS file format, however, it experiences an infinite loop when trying to parse RCSid in the context of RCSadmin. Removing the offending line
Group(ZeroOrMore(RCSid)).setResultsName('access') + \
causes the hang ... | Pyparsing: Attempt to be non-greedy causes infinite loop | I'm trying to create a parser for the RCS file format, however, it experiences an infinite loop when trying to parse RCSid in the context of RCSadmin. Removing the offending line
Group(ZeroOrMore(RCSid)).setResultsName('access') + \
causes the hang not to occur. RCSid on its succeeds in parsing string. Any sug... | [
"Is an empty string really a valid RCSid? I suspect not. Now it may be possible for the RCSid to be omitted in the access clause of your admin statement, but you are already handling that with the ZeroOrMore. Define your primitives as they are specified, and then factor in Optional, ZeroOrMore etc, in the higher... | [
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0007232768_pyparsing_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.