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:
Getting two-tuples out of a list
I just extracted some data from a list using python but think it's overcomplicated and unpythonic and there's probably a much better way to do this. I'm actually pretty sure I saw this somewhere in the standard library docs but my brain refuses to tell me where.
So here it goes:
In... | Getting two-tuples out of a list | I just extracted some data from a list using python but think it's overcomplicated and unpythonic and there's probably a much better way to do this. I'm actually pretty sure I saw this somewhere in the standard library docs but my brain refuses to tell me where.
So here it goes:
Input:
x = range(8) # any even sequence
... | [
"Tuples?\nIn Python 2.n\n>>> zip(*2*[iter(x)])\n[(0, 1), (2, 3), (4, 5), (6, 7)]\n\nIn Python 3.n\nzip() behaves slightly differently...\n>> zip(*2*[iter(x)])\n<zip object at 0x285c582c>\n>>> list(zip(*2*[iter(x)])])\n[(0, 1), (2, 3), (4, 5), (6, 7)]\n\nLists?\nThe implementation is the same in Python 2 and 3...\n>... | [
7,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006007736_python.txt |
Q:
Need help with Image processing using Python
I am a new programmer in Python and I am trying to do some image processing. I want to incorporate a selection feature on an image with the help of the mouse. The image will display and then the user will select a part of the image with the mouse which will get saved as... | Need help with Image processing using Python | I am a new programmer in Python and I am trying to do some image processing. I want to incorporate a selection feature on an image with the help of the mouse. The image will display and then the user will select a part of the image with the mouse which will get saved as a new image. I have idea about opening, displayin... | [
"Checkout PIL (Python Imaging Library):\nhttp://www.pythonware.com/products/pil/\n",
"I am not sure what image library you are using. But to create a subset of an image using PIL look here under the chapter \"Cutting, Pasting and Merging Images\".\n",
"If you are trying to do some complex shape selecting instea... | [
3,
0,
0
] | [] | [] | [
"image",
"image_processing",
"python"
] | stackoverflow_0006008012_image_image_processing_python.txt |
Q:
How __hash__ is implemented in Python 3.2?
I want to make custom object hash-able (via pickling). I could find __hash__ algorithm for Python 2.x (see code below), but it obviously differs from hash for Python 3.2 (I wonder why?). Does anybody know how __hash__ implemented in Python 3.2?
#Version: Python 3.2
def ... | How __hash__ is implemented in Python 3.2? | I want to make custom object hash-able (via pickling). I could find __hash__ algorithm for Python 2.x (see code below), but it obviously differs from hash for Python 3.2 (I wonder why?). Does anybody know how __hash__ implemented in Python 3.2?
#Version: Python 3.2
def c_mul(a, b):
#C type multiplication
retu... | [
"The answer why they are different is written there:\n\nHash values are now values of a new\n type, Py_hash_t, which is defined to\n be the same size as a pointer.\n Previously they were of type long,\n which on some 64-bit operating systems\n is still only 32 bits long.\n\nThe hashing also consider new values... | [
5,
3
] | [] | [] | [
"algorithm",
"hash",
"python"
] | stackoverflow_0006008026_algorithm_hash_python.txt |
Q:
Replacing special methods of a Python list object
I want to write a class that subclasses the Python list and notifies a certain other object when the list changes. Since there are many methods that need to be overridden, I opted for a solution like this, instead of overriding all methods that change the list:
des... | Replacing special methods of a Python list object | I want to write a class that subclasses the Python list and notifies a certain other object when the list changes. Since there are many methods that need to be overridden, I opted for a solution like this, instead of overriding all methods that change the list:
destructiveMethods = ["__setitem__",
... | [
"Special methods can only defined on the object's type and not on instancessource.\nCompare\n>>> class A(object):\n... __getitem__ = lambda self,i: 42\n>>> A()[0]\n42\n\nand\n>>> class B(object):\n... def __init__(self):\n... self.__getitem__ = lambda self,i: 42\n>>> B()[0]\nTypeError: 'B' objec... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006008260_python.txt |
Q:
Python Web Service Recommendations
I am looking to create a web service in Python, but none of the libraries/tools I have looked at appear to be actively maintained. I am looking to build a server using SOAP. Don't need to build a client at the moment as I can test using soapUI but will need to write a client at s... | Python Web Service Recommendations | I am looking to create a web service in Python, but none of the libraries/tools I have looked at appear to be actively maintained. I am looking to build a server using SOAP. Don't need to build a client at the moment as I can test using soapUI but will need to write a client at some point.
The ones I have already looke... | [
"Try twisted: http://twistedmatrix.com/trac/\nIts heavily used project to various web services. You can build almost anything from it. \nTalking about SOAP here is twisted support for SOAP from docs: http://twistedmatrix.com/documents/current/web/howto/xmlrpc.html#auto4\nLast change was few hour ago - so it is acti... | [
1
] | [] | [] | [
"python",
"soap",
"web_services",
"wsdl"
] | stackoverflow_0006008380_python_soap_web_services_wsdl.txt |
Q:
How to delete () using re module in Python
I am in trouble for processing XML text.
I want to delete () from my text as follows:
from <b>(apa-bhari(n))</b> to <b>apa-bhari(n)</b>
The following code was made
name= re.sub('<b>\((.+)\)</b>','<b>\1</b>',name)
But this can only returns
<b></b>
I do not understand es... | How to delete () using re module in Python | I am in trouble for processing XML text.
I want to delete () from my text as follows:
from <b>(apa-bhari(n))</b> to <b>apa-bhari(n)</b>
The following code was made
name= re.sub('<b>\((.+)\)</b>','<b>\1</b>',name)
But this can only returns
<b></b>
I do not understand escape sequences and backreference. Please tell me... | [
"You need to use raw strings, or escape the slashes:\nname = re.sub(r'<b>\\((.+)\\)</b>', r'<b>\\1</b>', name)\n\n",
"You need to escape backslashes in Python strings if followed by a number; the following expressions are all true:\nassert '\\1' == '\\x01'\nassert len('\\\\1') == 2\nassert '\\)' == '\\\\)'\n\nSo,... | [
2,
1,
1
] | [] | [] | [
"backreference",
"escaping",
"python",
"regex"
] | stackoverflow_0006008791_backreference_escaping_python_regex.txt |
Q:
Emulating a Windows shortcut in Python
This is probably a fairly simple question, but I have gone thoroughly overwhelmed trying to figure it out.
I want to start another program in Windows from Python 2.6. I have the "command-line argument" figured out so that if I create shortcut and double-click on it the other ... | Emulating a Windows shortcut in Python | This is probably a fairly simple question, but I have gone thoroughly overwhelmed trying to figure it out.
I want to start another program in Windows from Python 2.6. I have the "command-line argument" figured out so that if I create shortcut and double-click on it the other program opens, does what it needs to, and th... | [
"Something like below maybe?\nimport os\nos.system(\"notepad\")\n\nOr:\nfrom subprocess import call\ncall([\"notepad\"])\n\nThe below question has some excellent answers:\nCalling an external command in Python\n"
] | [
1
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0006008817_python_windows.txt |
Q:
Python/Javascript/AJAX live search help
I'm trying to create an AJAX live search (such as Google Suggest) with python. I'm new to AJAX, so I started reading some tutorials and other useful documentation. I found an example, http://www.w3schools.com/ajax/ajax_aspphp.asp, which is basically what I'm trying to accomp... | Python/Javascript/AJAX live search help | I'm trying to create an AJAX live search (such as Google Suggest) with python. I'm new to AJAX, so I started reading some tutorials and other useful documentation. I found an example, http://www.w3schools.com/ajax/ajax_aspphp.asp, which is basically what I'm trying to accomplish but this example is for asp/php only. I ... | [
"The <input> element has no attribute text. That's why this.text and later str are undefined. Maybe <input type=\"text\" id=\"sname\" onkeyup=\"showHint(this.value)\"> would do what you want.\n"
] | [
2
] | [] | [] | [
"ajax",
"javascript",
"python"
] | stackoverflow_0006009149_ajax_javascript_python.txt |
Q:
Decorating method (class methods overloading)
Inspired by Muhammad Alkarouri answer in What are good uses for Python3's "Function Annotations" , I want to do this multimethod for methods, not regular functions. However, when I do this
registry = {}
class MultiMethod(object):
def __init__(self, name):
... | Decorating method (class methods overloading) | Inspired by Muhammad Alkarouri answer in What are good uses for Python3's "Function Annotations" , I want to do this multimethod for methods, not regular functions. However, when I do this
registry = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def ... | [
"The basic problem you have is that you use a class in place of a function. There is no mechanism to bind that class to the instance it's called from, unlike a function where this happens automatically. \nIn short, when you do a.foo( .. ) it returns a MultiMethod, but this object has no idea that it is supposed to ... | [
5
] | [] | [] | [
"decorator",
"methods",
"python",
"python_3.x"
] | stackoverflow_0006009344_decorator_methods_python_python_3.x.txt |
Q:
How to modify trac to create own custom Link format (TracLinks)
In the open-source trac issue tracking software, when you write text in the wiki or ticket comments, you can link to a ticket using #1234 or you can link to a code changeset using r1234. This is the documentation: http://trac.edgewall.org/wiki/TracLin... | How to modify trac to create own custom Link format (TracLinks) | In the open-source trac issue tracking software, when you write text in the wiki or ticket comments, you can link to a ticket using #1234 or you can link to a code changeset using r1234. This is the documentation: http://trac.edgewall.org/wiki/TracLinks
I would like to define my own link format. 3 examples of what I'd ... | [
"If you want this exact syntax, you have no other choice than to create a plugin and have a Component that implements the IWikiSyntaxProvider interface.\nIf you can live with a slightly different syntax, for example [a:1234] for the acunote ticket, [g:e2a1b3caadd0986e3e3d316c01965a2495329b87] for the github changes... | [
4,
1
] | [] | [] | [
"customization",
"issue_tracking",
"python",
"trac"
] | stackoverflow_0006002390_customization_issue_tracking_python_trac.txt |
Q:
Python Orange Distributed Computing
I am currently working with the Python package Orange to run some classification tests on large sets of data. I am primarily using the Naive Bayes method, and I know from other applications that is is able to be distributed out to multiple nodes to compute. Orange unfortunately ... | Python Orange Distributed Computing | I am currently working with the Python package Orange to run some classification tests on large sets of data. I am primarily using the Naive Bayes method, and I know from other applications that is is able to be distributed out to multiple nodes to compute. Orange unfortunately does not appear to have the ability to us... | [
"I would recommend using BOINC and their library dedicated to such a task. \ncheers\n"
] | [
1
] | [] | [] | [
"bayesian",
"classification",
"distributed",
"orange",
"python"
] | stackoverflow_0005023088_bayesian_classification_distributed_orange_python.txt |
Q:
Python "input data"
I have file *.data, which include data in this order:
2.5,10,U1
3,4.5,U1
3,9,U1
3.5,5.5,U1
3.5,8,U1
4,7.5,U1
4.5,3.5,U1
4.5,4.5,U1
4.5,6,U1
5,5,U1
5,7,U1
7,6.5,U1
3.5,9.5,U2
3.5,10.5,U2
4.5,8,U2
4.5,10.5,U2
5,9,U2
5.5,5.5,U2
5.5,7.5,U2
In this data(I have different types of data, this is just ... | Python "input data" | I have file *.data, which include data in this order:
2.5,10,U1
3,4.5,U1
3,9,U1
3.5,5.5,U1
3.5,8,U1
4,7.5,U1
4.5,3.5,U1
4.5,4.5,U1
4.5,6,U1
5,5,U1
5,7,U1
7,6.5,U1
3.5,9.5,U2
3.5,10.5,U2
4.5,8,U2
4.5,10.5,U2
5,9,U2
5.5,5.5,U2
5.5,7.5,U2
In this data(I have different types of data, this is just example where are just 2 ... | [
"You can filter your list after reading into two distinct subsets:\ndata_list_1 = [(x,y,c) for (x,y,c) in data_list if c=='U1']\ndata_list_2 = [(x,y,c) for (x,y,c) in data_list if c=='U2']\n\nAfterwards you can then construct two different learing sets and test sets as before but on the filtered lists, e.g.\nlearni... | [
2,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006009542_python.txt |
Q:
Replacing filenames in python with new filenames
Possible Duplicate:
Rename Files in Python
Hey all, I am creating a script in Python to wrap a number of OS commands related to bulk image editing, and most of the tasks are completed, however I am stumped on one task (a seemingly simple one at that).
When I scan ... | Replacing filenames in python with new filenames |
Possible Duplicate:
Rename Files in Python
Hey all, I am creating a script in Python to wrap a number of OS commands related to bulk image editing, and most of the tasks are completed, however I am stumped on one task (a seemingly simple one at that).
When I scan pictures on my scanner, I get a filename similar to t... | [
"something like:\nsep = '_'\ntry:\n prefix,keeper = filename.split(sep)\nexcept: # filename does not match desired structure\n print \"not processed: no '\" + sep + \"' in '\"+ filename + \"'\"\nelse: # split succeeded: \n if prefix == old_prefix:\n filename = new_prefix + sep + keeper\n # ... | [
2
] | [] | [] | [
"linux",
"python",
"rename"
] | stackoverflow_0006009881_linux_python_rename.txt |
Q:
How to read an uploaded file in Google App Engine
Hi I have another question in app engine. You have one form where there's one field for file upload, I need to read the uploaded file, validate it and store it into the datastore.
My question is how can I read the uploaded file?
In django I would have used request.... | How to read an uploaded file in Google App Engine | Hi I have another question in app engine. You have one form where there's one field for file upload, I need to read the uploaded file, validate it and store it into the datastore.
My question is how can I read the uploaded file?
In django I would have used request.FILES, in GAE is there anything of that sort?
I'd appre... | [
"this question has been answered in \nUpload files in Google App Engine\nthe google app engine documents also explain it.\nhttp://code.google.com/appengine/docs/images/usingimages.html#Uploading\nIn brief, you just need to use self.request.get('name_of_file_in_the_input_form')\n",
"One good example for uploading ... | [
2,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0006009928_django_google_app_engine_python.txt |
Q:
Displaying generated jpg map on Google App Engine
I have an image created from the Google Maps API static map library and I'd like to make this visible on the screen.
How's the best way to do this? My map is being generated as follows:
map = urlfetch.fetch(url).content
Which should correspond to an image. My que... | Displaying generated jpg map on Google App Engine | I have an image created from the Google Maps API static map library and I'd like to make this visible on the screen.
How's the best way to do this? My map is being generated as follows:
map = urlfetch.fetch(url).content
Which should correspond to an image. My question is how best to place this image on the Django fra... | [
"If you've generated a url that denotes a static map, which I think is the only way to do it, then you'll just want to use it as the src attribute of an img tag.\n<img alt=\"My Map\" src=\"{{url}}\" />\n\nhttp://code.google.com/apis/maps/documentation/staticmaps\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"google_maps",
"image",
"python"
] | stackoverflow_0006010011_google_app_engine_google_maps_image_python.txt |
Q:
Python "data naming"
My input:
test_set, like:
[['4.5', '6', 'U1'], ['5', '5', 'U1'], ['5', '7', 'U1'], ['7', '6.5', 'U1'], ['5.5', '5.5', 'U2'], ['5.5', '7.5', 'U2']]
After this I made a lot of calculation with this data, and my "final" result is array of test_set_final
test_set_final=array([[ 1.6488378 ],
... | Python "data naming" | My input:
test_set, like:
[['4.5', '6', 'U1'], ['5', '5', 'U1'], ['5', '7', 'U1'], ['7', '6.5', 'U1'], ['5.5', '5.5', 'U2'], ['5.5', '7.5', 'U2']]
After this I made a lot of calculation with this data, and my "final" result is array of test_set_final
test_set_final=array([[ 1.6488378 ],
[ 2.61782463],
[... | [
"This should do it (had it prepared from the last version of your question):\ntest_set_final = [[r, c[-1]] for [r], c in zip (test_set_final, test_set)]\n\nEdit: Added unpacking for r - the example looked different before.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006010331_python.txt |
Q:
help with datastore query
Hi I am trying to list playlists wich contain songs by a given artist for which i have the keyname, my models are:
**playlist**
songs = db.ListProperty(db.Key)
**Song**
artist = db.ReferenceProperty(Artist,collection_name='songs')
**Artist**
Key Name = john-lennon
so playlist contains ... | help with datastore query | Hi I am trying to list playlists wich contain songs by a given artist for which i have the keyname, my models are:
**playlist**
songs = db.ListProperty(db.Key)
**Song**
artist = db.ReferenceProperty(Artist,collection_name='songs')
**Artist**
Key Name = john-lennon
so playlist contains a list of song keys, and a song... | [
"You can't really do queries like this with GAE. The datastore is not a relational database, and does not do things like JOINs.\nThe best you can do is to get all the songs whose artist is John Lennon, and then find the playlist for those songs:\nsongs = GqlQuery('SELECT __key__ FROM song WHERE artist = :1', 'john-... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"gql",
"python"
] | stackoverflow_0006010240_google_app_engine_google_cloud_datastore_gql_python.txt |
Q:
Python Keyboard shortcuts
So, I have a python script running I the background, and I want it to trigger X function whenever a key combination is pressed. How would I implement that? The problem is that the app will be running in the background, so it won't have focus from the OS.
A:
Well, it basicly has nothing... | Python Keyboard shortcuts | So, I have a python script running I the background, and I want it to trigger X function whenever a key combination is pressed. How would I implement that? The problem is that the app will be running in the background, so it won't have focus from the OS.
| [
"Well, it basicly has nothing to do with python. That heavily depends on the operating system you're working on.\nYou can use XLib under Linux (http://python-xlib.sourceforge.net/) or wxPython under Windows (http://wxpython.org/docs/api/wx.Window-class.html#RegisterHotKey)\nAnother idea would be to hook the system ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006010608_python.txt |
Q:
python subprocess call
The following is a python code using the subprocess module. Can someone explain what the code is doing?
process = subprocess.Popen(['aspell', 'list'],
stdin = subprocess.PIPE, # reading from the op of a pipe.
stdout = subprocess.PIPE) # writing to the i/p of a pipe
(result, stderrd... | python subprocess call | The following is a python code using the subprocess module. Can someone explain what the code is doing?
process = subprocess.Popen(['aspell', 'list'],
stdin = subprocess.PIPE, # reading from the op of a pipe.
stdout = subprocess.PIPE) # writing to the i/p of a pipe
(result, stderrdata) = process.communicate("... | [
"Its a really badly laid out script for opening the process aspell giving it the argument list. then piping the stdout and stderr into a tuple while feeding ' '.join(text) as stdin to the process.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006010632_python.txt |
Q:
Python calling shell script - no directory?
In a python script I call a bash script as follows:
subprocess.Popen(["./scan.sh", dir])
Inside that script, there is,
find $1 -name "*013*.txt" > found_files.txt
For some reason, the dir argument from python is translated into a version with quotes inside the bash scr... | Python calling shell script - no directory? | In a python script I call a bash script as follows:
subprocess.Popen(["./scan.sh", dir])
Inside that script, there is,
find $1 -name "*013*.txt" > found_files.txt
For some reason, the dir argument from python is translated into a version with quotes inside the bash script. Printing 'dir' in python yields the exact pa... | [
"There aren't. What's happening is that the ~ is not being interpreted, as it's the shell's job to do so. Use os.path.expanduser() to expand the path before passing it to subprocess.\n",
"use $HOME. the '~' is not expanding in quotes nor in double quotes.\npython -c \"import subprocess;subprocess.Popen(['./scan.s... | [
8,
0
] | [] | [] | [
"bash",
"find",
"python",
"subprocess"
] | stackoverflow_0006010663_bash_find_python_subprocess.txt |
Q:
How does the automatic full qualification of class names work, in Python? [relevant to object pickling]
(It is possible to directly jump to the question, further down, and to skip the introduction.)
There is a common difficulty with pickling Python objects from user-defined classes:
# This is program dumper.py
imp... | How does the automatic full qualification of class names work, in Python? [relevant to object pickling] | (It is possible to directly jump to the question, further down, and to skip the introduction.)
There is a common difficulty with pickling Python objects from user-defined classes:
# This is program dumper.py
import pickle
class C(object):
pass
with open('obj.pickle', 'wb') as f:
pickle.dump(C(), f)
In fact, ... | [
"When your classes are defined in your main module, that's where pickle expects to find them when they are unpickled. In your first case, the classes were defined in the main module, so when loader runs, loader is the main module and pickle can't find the classes. If you look at the content of obj.pickle, you'll ... | [
3,
2
] | [] | [] | [
"class",
"fully_qualified_naming",
"import",
"pickle",
"python"
] | stackoverflow_0006009169_class_fully_qualified_naming_import_pickle_python.txt |
Q:
Monkey patch __del__ to new function
For specific debugging purposes I'd like to wrap the del function of an arbitrary object to perform extra tasks like write the last value of the object to a file.
Ideally I want to write
monkey(x)
and it should mean that the final value of x is printed when x is deleted
Now... | Monkey patch __del__ to new function | For specific debugging purposes I'd like to wrap the del function of an arbitrary object to perform extra tasks like write the last value of the object to a file.
Ideally I want to write
monkey(x)
and it should mean that the final value of x is printed when x is deleted
Now I figured that del is a class method. So ... | [
"While special 'double underscore' methods like __del__, __str__, __repr__, etc. can be monkey-patched on the instance level, they'll just be ignored, unless they are called directly (e.g., if you take Omnifarious's answer: del a won't print a thing, but a.__del__() would).\nIf you still want to monkey patch a sing... | [
8,
1,
0,
0
] | [] | [] | [
"monkeypatching",
"python"
] | stackoverflow_0006010282_monkeypatching_python.txt |
Q:
How do I detect a socket disconnection? / How do I call socket.recv with a timeout?
I'm using gevent patched socket to connect to a streaming server and I'm using an adsl connection.
I don't control the server but in my tests, if I stop the server I can detect the disconnection by just checking if the result from... | How do I detect a socket disconnection? / How do I call socket.recv with a timeout? | I'm using gevent patched socket to connect to a streaming server and I'm using an adsl connection.
I don't control the server but in my tests, if I stop the server I can detect the disconnection by just checking if the result from recv is an empty string, but if I turn off my adsl modem recv never exits. If I just dis... | [
"Use the timeouts provided by gevent, for example in a with-statement:\nwith Timeout(5, False):\n data = sock.recv()\n\nor as a function:\ndata = gevent.with_timeout(5, sock.recv, timeout_value=\"\")\n\n",
"it's not detecting the disconnection because there wasn't any disconnection, the TCP \"connection\" is s... | [
4,
2
] | [] | [] | [
"gevent",
"networking",
"python",
"sockets"
] | stackoverflow_0006009365_gevent_networking_python_sockets.txt |
Q:
Cooley Tukey twiddle factor in a simple python script
I'm reading how the cooley tukey method works, but I have a few problems with the following python script:
def fft_CT_twiddles(x, inverse = False, verbose = False, twiddles = None) :
"""
Computes the DFT of x using Cooley-Tukey's FFT algorithm. Twiddle ... | Cooley Tukey twiddle factor in a simple python script | I'm reading how the cooley tukey method works, but I have a few problems with the following python script:
def fft_CT_twiddles(x, inverse = False, verbose = False, twiddles = None) :
"""
Computes the DFT of x using Cooley-Tukey's FFT algorithm. Twiddle factors
are precalculated in the first function call, t... | [
"The code you asked about is doing the following:\n+[N] # appends N to the end of the array\n\n\ntwiddles[-1] # is the last element of the array ( the N in this case ).\n\nThe code appears to add the 'N' to the end of the twiddles array just for convenience, so that it can be used later, and so that it can easily b... | [
2,
2
] | [] | [] | [
"dft",
"discrete_mathematics",
"fft",
"math",
"python"
] | stackoverflow_0006010684_dft_discrete_mathematics_fft_math_python.txt |
Q:
Novice Django question about object relationship
I am having some troubles understanding the object relationships in Django. I wrote this:
from django.db import models
class Community(models.Model):
name = models.CharField(max_length=200) #arbitrary max length
class Category(models.Model):
community = ... | Novice Django question about object relationship | I am having some troubles understanding the object relationships in Django. I wrote this:
from django.db import models
class Community(models.Model):
name = models.CharField(max_length=200) #arbitrary max length
class Category(models.Model):
community = models.ForeignKey(Community)
category = models.Cha... | [
"You probably haven't run python manage.py syncdb recently, or you did but you changed some table/models.Model definitions.\nTry dropping your database, creating it, and running syncdb again. That is, if you don't have any important data in there.\nYou can also do python manage.py reset <appname>\n",
"This sounds... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006010870_django_python.txt |
Q:
How do I 'install' a module on Google App Engine?
Excuse me as I'm new to this. I've done all the searching I can, and while I know the module I want to install, I can't figure out how to install the specific module.
I'm wanting to install Python-OAuth2 to GAE, but as I can't find the specific oauth2.py file, I do... | How do I 'install' a module on Google App Engine? | Excuse me as I'm new to this. I've done all the searching I can, and while I know the module I want to install, I can't figure out how to install the specific module.
I'm wanting to install Python-OAuth2 to GAE, but as I can't find the specific oauth2.py file, I don't know what to copy into my app's directory on my mac... | [
"For this particular case, copy the entire oauth2 directory to your app's folder. It should work.\n",
"Modules in python are nothing but python files. Packages are directories that contain an __init__.py file. You can import a python file called foobar.py that resides in the same directory as the file you're impo... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006010885_google_app_engine_python.txt |
Q:
Getting one Python program to "feed" another one
I am trying to do some work on 2-SAT and 3-SAT for an assignment and I was allowed to search the web for the implementation of the program. I came across 2 programs in Python that basically I can run and they enable me to continue with my assignment. However I can't... | Getting one Python program to "feed" another one | I am trying to do some work on 2-SAT and 3-SAT for an assignment and I was allowed to search the web for the implementation of the program. I came across 2 programs in Python that basically I can run and they enable me to continue with my assignment. However I can't get the output from one program to feed the other one... | [
"What you want to do is pipe the output from the first script into the second.\nSince the scripts seem to be named 3sat.py and gsat.py respectively, just cd into the directory where they're located and run:\n./3sat.py | ./gsat.py\n\nor, equivalently:\npython 3sat.py | python gsat.py\n\n"
] | [
2
] | [] | [] | [
"io",
"python"
] | stackoverflow_0006011039_io_python.txt |
Q:
Working with multiple code files and folders in Python
I am new to Python and I haven't figured out a simple way of separating code in multiple code files and folders.
What I do today is: for each folder I create an __init__.py file. Sometimes it's empty. I don't know why I do it, but it seems necessary. That's th... | Working with multiple code files and folders in Python | I am new to Python and I haven't figured out a simple way of separating code in multiple code files and folders.
What I do today is: for each folder I create an __init__.py file. Sometimes it's empty. I don't know why I do it, but it seems necessary. That's the first difference from working with C#.
The second differen... | [
"You should read up on modules: http://docs.python.org/tutorial/modules.html\nBasically, I think you aren't organizing your code right. With Python, directories and files have a meaning; it's not just what you write into the files. With every new directory (with __init__.py) and every new file you create a new \"na... | [
18,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0006011322_import_python.txt |
Q:
pyMPI build & install
Hi everyone I'm trying to install pyMPI on ubuntu server 10.04.2 .
When i run ./configure this is what it prints out
enter
root@ACRS-CN1:/usr/local/src/pyMPI-2.5b0# ./configure
checking build system type... i686-pc-linux-gnu
checking host system type... i686-pc-linux-gnu
checking for a BSD-... | pyMPI build & install | Hi everyone I'm trying to install pyMPI on ubuntu server 10.04.2 .
When i run ./configure this is what it prints out
enter
root@ACRS-CN1:/usr/local/src/pyMPI-2.5b0# ./configure
checking build system type... i686-pc-linux-gnu
checking host system type... i686-pc-linux-gnu
checking for a BSD-compatible install... /usr/... | [
"sudo apt-get install python-dev libopenmpi-dev\n\nare needed to build successfully. Just tested right now.\n"
] | [
2
] | [] | [] | [
"cluster_computing",
"mpi",
"python"
] | stackoverflow_0006011498_cluster_computing_mpi_python.txt |
Q:
Python select() behavior is strange
I'm having some trouble understanding the behavior of select.select. Please consider the following Python program:
def str_to_hex(s):
def dig(n):
if n > 9:
return chr(65-10+n)
else:
return chr(48+n)
r = ''
while len(s) > 0:
... | Python select() behavior is strange | I'm having some trouble understanding the behavior of select.select. Please consider the following Python program:
def str_to_hex(s):
def dig(n):
if n > 9:
return chr(65-10+n)
else:
return chr(48+n)
r = ''
while len(s) > 0:
c = s[0]
s = s[1:]
... | [
"The read method of sys.stdin works at a higher level of abstraction than select. When you do ans[0].read(1), python actually reads a larger number of bytes from the operating system and buffers them internally. select is not aware of this extra buffering; It only sees that everything has been read, and so will blo... | [
9,
1
] | [] | [] | [
"io",
"linux",
"python",
"unix"
] | stackoverflow_0006011481_io_linux_python_unix.txt |
Q:
How to validate JSON with simplejson
Occasionally I'm querying a server for JSON and receiving a 404 HTML page when the requested data is not available.
Thus, I must have a check to ensure that the JSON I'm expecting, is actually json rather than HTML. I'm accomplishing this now by checking for a string that I ... | How to validate JSON with simplejson | Occasionally I'm querying a server for JSON and receiving a 404 HTML page when the requested data is not available.
Thus, I must have a check to ensure that the JSON I'm expecting, is actually json rather than HTML. I'm accomplishing this now by checking for a string that I can expect to be in the HTML is contained ... | [
"Find the first non-whitespace character. If it's \"<\" then you have HTML.\nAlso, check the content type header and HTTP status code.\n",
"You should be able to tell that you recieved a 404, because the response code was not 200. That is:\nimport urllib\nresp = urllib.urlopen('http://example.com/')\n\nif resp.g... | [
2,
0
] | [] | [] | [
"django",
"json",
"python",
"simplejson"
] | stackoverflow_0006011596_django_json_python_simplejson.txt |
Q:
RSA python publickey using pyCrypto
How to load a RSA public key file into a pyCrypto publickey object in python?
A:
The RSA Class has an importKey method for this:
importKey(externKey) Import an RSA
key (public or private half).
externKey: the RSA key to import,
encoded as a string. The key can be in
D... | RSA python publickey using pyCrypto | How to load a RSA public key file into a pyCrypto publickey object in python?
| [
"The RSA Class has an importKey method for this:\n\nimportKey(externKey) Import an RSA\n key (public or private half).\nexternKey: the RSA key to import,\n encoded as a string. The key can be in\n DER (PKCS#1) or in unencrypted PEM\n format (RFC1421).\n\n"
] | [
3
] | [] | [] | [
"gnupg",
"pycrypto",
"python"
] | stackoverflow_0006011666_gnupg_pycrypto_python.txt |
Q:
Google App Engine Geo Query
query = db.GqlQuery("SELECT * FROM Place
WHERE location >= :1 AND
location <= :2",
db.GeoPt(lat=minLat, lon=minLon),
db.GeoPt(lat=maxLat, lon=maxLon) )
From what I understand, GAE ignore the lo... | Google App Engine Geo Query | query = db.GqlQuery("SELECT * FROM Place
WHERE location >= :1 AND
location <= :2",
db.GeoPt(lat=minLat, lon=minLon),
db.GeoPt(lat=maxLat, lon=maxLon) )
From what I understand, GAE ignore the long in this case.
Is this true?
| [
"Short answer: Yes.\nLong answer: GeoPt properties are sorted first by latitude, then by longitude. This query will find entities that fall between the two latitudes, only considering the longitudes if the latitudes are identical.\n"
] | [
1
] | [] | [] | [
"geolocation",
"geospatial",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005986925_geolocation_geospatial_google_app_engine_google_cloud_datastore_python.txt |
Q:
python Django - filter + contain readable syntax
i have created little search method. The problem that its hard to read it and ordering seems to be "out of shape". What is the best way to filter query in such manner?
@login_check
def search(request):
subdomain = request.get_host() ... | python Django - filter + contain readable syntax | i have created little search method. The problem that its hard to read it and ordering seems to be "out of shape". What is the best way to filter query in such manner?
@login_check
def search(request):
subdomain = request.get_host()
q = request.... | [
"\"Complex lookups with Q objects\"\n",
"you could use a list comprehension to factor out the common tail: \nqueryset_list = (\n item.filter(alias=Site.objects.get(domain=subdomain)).order_by('created')\n for item in (\n SomeObject.objects.filter(title__icontains=q),\n SomeObject.objects.filt... | [
3,
1
] | [] | [] | [
"contains",
"django",
"filtering",
"python"
] | stackoverflow_0006011662_contains_django_filtering_python.txt |
Q:
Easiest & fastest way to export a Python program to run on another computer?
My friend does not have Python or the libraries needed installed on his machine to run a program I have written. Is there a simple way to export my project (currently sitting in pydev on my x64 Windows 7 machine) so that he could run it ... | Easiest & fastest way to export a Python program to run on another computer? | My friend does not have Python or the libraries needed installed on his machine to run a program I have written. Is there a simple way to export my project (currently sitting in pydev on my x64 Windows 7 machine) so that he could run it on his machine? (He has OSX, but he could find Unix or Windows if needed.) My pro... | [
"You could use py2exe (Windows), cx_Freeze (should work on any platform that Python itself works on) or py2app (Mac OS X).\n",
"OS X actually already has python installed, albeit a somewhat old version. On OS X, a great solution to getting newer python Mac Ports package manager. \nOn Windows, python has an inst... | [
5,
2
] | [] | [] | [
"export",
"pydev",
"python",
"wxpython"
] | stackoverflow_0006011815_export_pydev_python_wxpython.txt |
Q:
Python Type Error while working with sockets in 2.7
Working with sockets in python 2.7, and I've encountered a Type error as follows:
TypeError: coercing to Unicode: need string or buffer, instance found.
I'm sure this has something to do with the differences between python2 and python3 in terms of unicode. But I... | Python Type Error while working with sockets in 2.7 | Working with sockets in python 2.7, and I've encountered a Type error as follows:
TypeError: coercing to Unicode: need string or buffer, instance found.
I'm sure this has something to do with the differences between python2 and python3 in terms of unicode. But I'm not familiar enough with the differences to narrow dow... | [
"I think the problem is that you are giving socket.connect() an IPy.IP object, but it expects a string. Try coercing it to a string first, IE: \nsvr = (str(x), 25)\n\n",
"It looks like it doesn't like something with the value of x in your server tuple I recommend checking the value of x through each iteration. I... | [
1,
0
] | [] | [] | [
"python",
"sockets",
"typeerror"
] | stackoverflow_0006011655_python_sockets_typeerror.txt |
Q:
Text Game Commands Parsing?
I'm interested in writing a parsing engine such as the ones in Inform, which is very robust.
I've tried a couple of different approach:
regex. For regex, I can only match {verb} {noun1 optional-noun2} {optional-preposition} {indirect-noun1 optional-indirect-noun2} This doesn't work th... | Text Game Commands Parsing? | I'm interested in writing a parsing engine such as the ones in Inform, which is very robust.
I've tried a couple of different approach:
regex. For regex, I can only match {verb} {noun1 optional-noun2} {optional-preposition} {indirect-noun1 optional-indirect-noun2} This doesn't work that well.
list of predefined verbs... | [
"Besides the mentioned pyparsing, which looks very appropriate (I've only used it a tiny bit), you should look into using nltk. It's a great collection of tools for natural language processing, and there's even a book.\n"
] | [
2
] | [] | [] | [
"nlp",
"python"
] | stackoverflow_0006011845_nlp_python.txt |
Q:
Searching for a Python lightweight IDE (or text-editor)
Possible Duplicate:
What IDE to use for Python?
Hi all,
I'm looking for either a lightweight IDE or a text-editor (with plugins, of course) for writing Python code. Some of the features I'd like the software to provide are as follows:
1) Auto-complete/sugg... | Searching for a Python lightweight IDE (or text-editor) |
Possible Duplicate:
What IDE to use for Python?
Hi all,
I'm looking for either a lightweight IDE or a text-editor (with plugins, of course) for writing Python code. Some of the features I'd like the software to provide are as follows:
1) Auto-complete/suggest
2) Multi-tab
3) Auto-format (on save if it is possible)
... | [
"You mention Eclipse - what about PyDev, a Python IDE for Eclipse? \nedit - also, this question has an incredibly comprehensive list of Python IDEs, sorted by feature. Might be worth a look.\n",
"Wingware's Python IDE fulfills all of your requirements, and I do consider it to be the best Python IDE around. That b... | [
3,
1,
1,
0
] | [] | [] | [
"editor",
"ide",
"python"
] | stackoverflow_0006011678_editor_ide_python.txt |
Q:
Python -- Overhead of `.so` Imports?
I have 1000s of custom (compiled to '.so') modules that I'd like to use in python at the same time. Each such module is of size (100 [KB]) on average.
Does anyone know what is the overhead (on the OS -- assuming python is not handling this) of every .so import? meaning, is the ... | Python -- Overhead of `.so` Imports? | I have 1000s of custom (compiled to '.so') modules that I'd like to use in python at the same time. Each such module is of size (100 [KB]) on average.
Does anyone know what is the overhead (on the OS -- assuming python is not handling this) of every .so import? meaning, is the overhead equal to the size of the .so file... | [
"There would be a large time overhead of importing that many shared libraries - the dynamic linker would spend a significant amount of time during the loading phase. The dynamic linker is really optimized for tens to hundreds of shared objects, not thousands to tens of thousands.\nIf at all possible, combine your s... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006012105_python.txt |
Q:
Grouping items in two lists
Give these two lists:
I[2]: list1 = ['r1', 'r1', 'r1', 'r2', 'r2', 'r3']
I[3]: list2 = [1,2,3,1,2,1]
What is the Pythonic way to construct the following dictionary?
I[5]: mydict
O[5]: {'r1': {'n1': 1, 'n2': 2, 'n3': 3}, 'r2': {'n1': 1, 'n2': 2}, 'r3': 'n1'}
Thanks.
A:
l1 = ['r1', '... | Grouping items in two lists | Give these two lists:
I[2]: list1 = ['r1', 'r1', 'r1', 'r2', 'r2', 'r3']
I[3]: list2 = [1,2,3,1,2,1]
What is the Pythonic way to construct the following dictionary?
I[5]: mydict
O[5]: {'r1': {'n1': 1, 'n2': 2, 'n3': 3}, 'r2': {'n1': 1, 'n2': 2}, 'r3': 'n1'}
Thanks.
| [
"l1 = ['r1', 'r1', 'r1', 'r2', 'r2', 'r3']\nl2 = [1, 2, 3, 1, 2, 1]\n\nd = {}\nfor i, j in zip(l1, l2):\n d[i] = d.get(i, {})\n d[i]['n%s' % j] = j\n\nAlternatively:\nl1 = ['r1', 'r1', 'r1', 'r2', 'r2', 'r3']\nl2 = [1, 2, 3, 1, 2, 1]\n\nd = dict((i, {}) for i in set(l1))\nfor i, j in zip(l1, l2):\n d[i]['n%s' % ... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006009985_python.txt |
Q:
Bypass Twitter OAuth
Essentially the same problem as this question but looking for a solution in Python. How to work around Twitter OAuth?
Ideally, I dont want to have to go through the hoops of setting up a user/login interface and backend since the work I'm doing is for internal purposes.
I would also like to b... | Bypass Twitter OAuth | Essentially the same problem as this question but looking for a solution in Python. How to work around Twitter OAuth?
Ideally, I dont want to have to go through the hoops of setting up a user/login interface and backend since the work I'm doing is for internal purposes.
I would also like to bypass the part where I nee... | [
"You'll want to use Twitter's OOB flow. This is explained nicely in this answer\nTwitter API - OOB Flow\n",
"So, reading between the lines a little, you have a twitter account and a password because this is internal, so you don't want to go with an auth process that requires a user to interact with it?\nThe idea ... | [
3,
3,
1,
1,
0
] | [] | [] | [
"python",
"twitter",
"twitter_oauth"
] | stackoverflow_0005906263_python_twitter_twitter_oauth.txt |
Q:
Using git to manage virtualenv state: will this cause problems?
I currently have git and virtualenv set up in a way which exactly
suits my needs and, so far, hasn't caused any problems. However I'm aware that
my setup is non-standard and I'm wondering if anyone more familiar with virtualenv's
internals can point o... | Using git to manage virtualenv state: will this cause problems? | I currently have git and virtualenv set up in a way which exactly
suits my needs and, so far, hasn't caused any problems. However I'm aware that
my setup is non-standard and I'm wondering if anyone more familiar with virtualenv's
internals can point out if, and where, it's likely to go wrong.
My setup
My virtualenv is ... | [
"This is an interesting question. I think the other two answers (thus far) raise good specific points. Clearly you've thought this through and have arrived at a solution you like, but I'll note that there does seem to be a philosophical split here among virtualenv users. \nOne camp, to which I'd guess you belong, f... | [
10,
6,
2
] | [] | [] | [
"git",
"python",
"virtualenv"
] | stackoverflow_0005955690_git_python_virtualenv.txt |
Q:
Python Socket Timeout Issue. How do control the flow of this code better?
While working with the sockets library in python 2.7, I am encountering an issue with getting the code to flow the way I want it to. I'd like the code to iterate over a range of IP addresses and open a socket connection for each ip in the ra... | Python Socket Timeout Issue. How do control the flow of this code better? | While working with the sockets library in python 2.7, I am encountering an issue with getting the code to flow the way I want it to. I'd like the code to iterate over a range of IP addresses and open a socket connection for each ip in the range. If the connection times out, print an error and move on to the next addres... | [
"You cannot call s.recv(2048) on a timedout socket I believe. I think this modified code should work fine.\nfrom IPy import IP\nip = IP(sys.argv[1])\nfor x in ip:\n print(\"Connecting to: {0}\".format(str(x)))\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(10)\n svr = (str(x), 25... | [
1,
0
] | [] | [] | [
"python",
"sockets",
"timeout"
] | stackoverflow_0006012620_python_sockets_timeout.txt |
Q:
reason for using three open-close quotes when using re.verbose in python
I'm just curious as to why most examples I've seen that make use of re.verbose when using regular expressions, use '''?
An example I found is shown below
address = re.compile(
''' #THIS
[\w\d.+-]+ # username
@
... | reason for using three open-close quotes when using re.verbose in python | I'm just curious as to why most examples I've seen that make use of re.verbose when using regular expressions, use '''?
An example I found is shown below
address = re.compile(
''' #THIS
[\w\d.+-]+ # username
@
([\w\d.]+\.)+ # domain name prefix
(com|org|edu) # we should supp... | [
"Using ''' allows the string to span multiple lines, so they can break down each part of the re instead of having one long line.\nIt is done for code readability, not functionality.\nSee the Python Tutorial strings section for more information about strings that span multiple lines.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006012806_python.txt |
Q:
nio error when parsing xml file
I've got a function in Jython, this function uses Popen to run another program which writes an xml file to it's stdout, which is directed to a file. When the process is done I close the file and call another function to parse it. I've been getting a bunch of error messages referri... | nio error when parsing xml file | I've got a function in Jython, this function uses Popen to run another program which writes an xml file to it's stdout, which is directed to a file. When the process is done I close the file and call another function to parse it. I've been getting a bunch of error messages referring to access to closed files and/or i... | [
"I think this problem started when I switched from calling wait on the subprocess to using the poll method so I can stop the process while it's running. Since I already had the results for many of the datasets I worked with it was a while before I had to start the subprocess again so it was hard to tell. Anyway, ... | [
1
] | [] | [] | [
"file",
"java",
"jython",
"python",
"xml"
] | stackoverflow_0005998947_file_java_jython_python_xml.txt |
Q:
Get actual value from Python list
Say I have
a = [1,2,3]
b = [foo(x) for x in a]
Now b is something like [ < function at 0x00F91540>, ...], how do I get python to evaluate b into it's actual values?
--EDIT--
Sorry for the confusion, my frustration is that Python doesn't give me the actual values in b, hence when... | Get actual value from Python list | Say I have
a = [1,2,3]
b = [foo(x) for x in a]
Now b is something like [ < function at 0x00F91540>, ...], how do I get python to evaluate b into it's actual values?
--EDIT--
Sorry for the confusion, my frustration is that Python doesn't give me the actual values in b, hence when I try to do something like:
b[0] + 1
... | [
"If you just want the values, you don't need lambdas at all.\nYou can simply write:\nb = [x + 1 for x in a]\n\nIf, for some reason, you still want to evaluate the lambdas that are in your version of b, you can write something like this:\nc = [f(n) for f, n in zip(b, a)]\n\n",
"Define your function outside the com... | [
3,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006013190_python.txt |
Q:
Python: How do I pass a big string as a single argument?
I'm trying to pass an entire string as an argument to a python script. The problem I am having is that the Python assumes that I only want the first word of the string.
In the example below, the -l arg stands for log and I want it to capture the entire st... | Python: How do I pass a big string as a single argument? | I'm trying to pass an entire string as an argument to a python script. The problem I am having is that the Python assumes that I only want the first word of the string.
In the example below, the -l arg stands for log and I want it to capture the entire string.
example:
python myscript.py -l "Big String I want to a... | [
"First: getopt is pretty outdated and deprecated. \nPlease use the optparse module of Python or the even newer argparse module (there is a backport of argparse for Python 2.X on PyPI).\nThe first example clearly covers your usecase solved using optparse:\nhttp://docs.python.org/library/optparse.html\nparser = Optio... | [
2,
1,
0
] | [] | [] | [
"command_line_arguments",
"python"
] | stackoverflow_0006013465_command_line_arguments_python.txt |
Q:
python pypdf to read pdf and get highlighted words
how to use python pypdf to read pdf and get highlighted words? I highlighted the unknown words in a pdf and I want to extract them for referencing later.
A:
Short answer: not possible with pypdf and not with any PDF tool for Python I know.
| python pypdf to read pdf and get highlighted words | how to use python pypdf to read pdf and get highlighted words? I highlighted the unknown words in a pdf and I want to extract them for referencing later.
| [
"Short answer: not possible with pypdf and not with any PDF tool for Python I know.\n"
] | [
1
] | [] | [] | [
"pdf",
"pypdf",
"python"
] | stackoverflow_0006013930_pdf_pypdf_python.txt |
Q:
Is there a function for Python which like getimagesize in PHP?
I have search for a while, and there is a function call get_image_dimensions(), however, as to my understanding, it works for the images which are downloaded or say local. So, any functions or solution like getimagesize in PHP, that we can just get the... | Is there a function for Python which like getimagesize in PHP? | I have search for a while, and there is a function call get_image_dimensions(), however, as to my understanding, it works for the images which are downloaded or say local. So, any functions or solution like getimagesize in PHP, that we can just get the dimension of an image via URL, instead of path to local?
| [
"Using the python image library (PIL)\nfrom PIL import Image\nim = Image.open(\"fileName.jpg\")\nim.size\n\nIf you have an url, open it via urlopen and pass the file object to Image.open\nimport urllib2 as urllib\nfd = urllib.urlopen(\"http://a/b/c\")\nim = Image.open(fd)\nim.size\n\n",
"PHP can open a URL as it ... | [
10,
1
] | [] | [] | [
"dimension",
"image",
"python",
"url"
] | stackoverflow_0006013996_dimension_image_python_url.txt |
Q:
How to solve this memory error - python
I have the following code
def gen_primes():
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
... | How to solve this memory error - python | I have the following code
def gen_primes():
D = {}
q = 2
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
... | [
"This prime generator doesn't use very much memory. It's also not very fast.\ndef gcd(a, b):\n rem = a % b\n while rem != 0:\n a = b\n b = rem\n rem = a % b\n return b\n\ndef primegen():\n yield 2\n yield 3\n yield 5\n yield 7\n yield 11\n accum = 2*3*5*7\n out = f... | [
1,
0,
0,
0
] | [] | [] | [
"memory",
"primes",
"python"
] | stackoverflow_0006012604_memory_primes_python.txt |
Q:
Python __init__ syntax
I'm confused about some examples I've seen of initializing classes using inheritance. Some of them look like:
class Foo(Bar):
def __init__(self, arg, parent = None):
Bar.__init__(self, parent)
self.Baz = arg
etc.
While others are simpler:
class Foo(Bar):
def... | Python __init__ syntax | I'm confused about some examples I've seen of initializing classes using inheritance. Some of them look like:
class Foo(Bar):
def __init__(self, arg, parent = None):
Bar.__init__(self, parent)
self.Baz = arg
etc.
While others are simpler:
class Foo(Bar):
def __init__(self, arg):
... | [
"Generally passing parent is not something that's required, only when the parent class's constructor explicitly needs such an argument. This is used in some hierarchies, such as PyQt. \nAnd a good idiom of parent class initialization is to use super:\nclass Child(Father):\n def __init__(self):\n super(Child, se... | [
9,
3
] | [] | [] | [
"class",
"constructor",
"python"
] | stackoverflow_0006013844_class_constructor_python.txt |
Q:
[float(i) for i in lst]
prorgamming newbie--I was looking for answers to an exercise I was doing and got my answers from here. My question is this--from that thread, the one chosen as best answer, was this code
[float(i) for i in lst]
The code did what it was supposed to do, but when I tried to get to that new li... | [float(i) for i in lst] | prorgamming newbie--I was looking for answers to an exercise I was doing and got my answers from here. My question is this--from that thread, the one chosen as best answer, was this code
[float(i) for i in lst]
The code did what it was supposed to do, but when I tried to get to that new list, I am getting errors
>>> x... | [
"You have to assign [float(i) for i in xs] to something:\n>>> new_list = [float(i) for i in xs]\n>>> new_list\n[12.0, 10.0, 32.0, 3.0, 66.0, 17.0, 42.0, 99.0, 20.0]\n>>> new_list[0]\n12.0\n>>> new_list[5]\n17.0\n\n",
"Using map:\nxs = '12 10 32 3 66 17 42 99 20'.split()\nnew_xs = map(float, xs)\n\n",
"Unlike fo... | [
7,
3,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006011759_python_python_3.x.txt |
Q:
Copying a stream in Python
How do I transfer the contents of a stream to another in Python?
The trivial solution would be
output.write(input.read())
but that fails if the input file is larger than the available memory (or even infinitely large); and it doesn't work well when a partial copy is useful as well. Basi... | Copying a stream in Python | How do I transfer the contents of a stream to another in Python?
The trivial solution would be
output.write(input.read())
but that fails if the input file is larger than the available memory (or even infinitely large); and it doesn't work well when a partial copy is useful as well. Basically I'm looking for the equiva... | [
"shutil.copyfile and shutil.copyfileobj for the rescue. See http://docs.python.org/library/shutil.html#module-shutil\n"
] | [
40
] | [] | [] | [
"io",
"python"
] | stackoverflow_0006014520_io_python.txt |
Q:
Convert AWK regex to Python script
Good morning all,
Wondering if you could please help me with the following query:-
I have just started learning Python last weekend after a colleague of mine showed me how to dramatically cut the time a Bash script takes to execute by re-writing it in Python. I was amazed at how... | Convert AWK regex to Python script | Good morning all,
Wondering if you could please help me with the following query:-
I have just started learning Python last weekend after a colleague of mine showed me how to dramatically cut the time a Bash script takes to execute by re-writing it in Python. I was amazed at how fast it ran. I would now like to do th... | [
"Since these lines are very structured, for simplicity (and speed), I would not go for a regex at all. Here's an example extracting your first piece of data:\n>>> line = \"2011-05-16 09:46:22,361 [Thread-4847133] PDU D <G_CC_SMS_SERVICE_51408_656.O_ CC_SMS_SERVICE_51408_656-ServerThread-VASPSessionThread-7ee35fb0-7... | [
6
] | [] | [] | [
"filtering",
"logging",
"python",
"regex"
] | stackoverflow_0006014777_filtering_logging_python_regex.txt |
Q:
Django login/logout
I'm trying to create a login and logout page with django. The problem I have is that when I submit the form, it doesn't go the url which I specified. When I click the login button, I want it to go to http://127.0.0.1:8000/home/ but instead, it goes to http://127.0.0.1:8000/?next=/home/.
Below i... | Django login/logout | I'm trying to create a login and logout page with django. The problem I have is that when I submit the form, it doesn't go the url which I specified. When I click the login button, I want it to go to http://127.0.0.1:8000/home/ but instead, it goes to http://127.0.0.1:8000/?next=/home/.
Below is my login/logout code in... | [
"The problem is that you don't actually login the user, the form sends unauthenticated user to /home/, which can't process, because it requires login. :-) So it redirects user to login view, storing the destination in next parameter.\nSolution:\n<form action=\"\" method=\"post\">\n",
"maybe you should try to remo... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006014834_django_python.txt |
Q:
Timed Quiz: How to consider internet interruptions?
I am preparing a Test or Quiz in Django. The quiz needs to be completed in certain time frame. Say 30 minutes for 40 questions.I can always initiate a clock at start of the test, and then calculate time by the time the Quiz is completed. However it's likely that ... | Timed Quiz: How to consider internet interruptions? | I am preparing a Test or Quiz in Django. The quiz needs to be completed in certain time frame. Say 30 minutes for 40 questions.I can always initiate a clock at start of the test, and then calculate time by the time the Quiz is completed. However it's likely that during the attempt, there may be issues such as internet ... | [
"The simplest way would be to add a timestamp when the person starts the quiz and then compare that to when they submit. Of course, this doesn't take into account connection drops, crashes, etc... like you mentioned.\nTo account for these issues I'd probably use something like node.js. Each client has \"check-in\" ... | [
2,
2,
2,
0
] | [] | [] | [
"django",
"python",
"session",
"timer"
] | stackoverflow_0005995674_django_python_session_timer.txt |
Q:
No module named x.urls
Seem to be having a problem here. Been working off my netbook for a while and brought all my code across to my desktop. Now, I'm getting 'No module named x.urls' on every single page. I don't know why. Works fine on the netbook. All I did was copy and paste all the code across. Also, I'm run... | No module named x.urls | Seem to be having a problem here. Been working off my netbook for a while and brought all my code across to my desktop. Now, I'm getting 'No module named x.urls' on every single page. I don't know why. Works fine on the netbook. All I did was copy and paste all the code across. Also, I'm running 1.2.1 on the netbook an... | [
"Name the directory where you put you project 'x' and it will work.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006015400_django_python.txt |
Q:
Python multi threading Yay or nay?
I have been trying to write a simple python application to implement a worker queue
every webpage I found about threading has some random guy commenting on it, you shouldn't use python threading because this or that, can someone help me out? what is up with Python threading, can... | Python multi threading Yay or nay? | I have been trying to write a simple python application to implement a worker queue
every webpage I found about threading has some random guy commenting on it, you shouldn't use python threading because this or that, can someone help me out? what is up with Python threading, can I use it or not? if yes which lib? the ... | [
"Python's threads are perfectly viable and useful for many tasks. Since they're implemented with native OS threads, they allow executing blocking system calls and keep \"running\" simultaneously - by calling the blocking syscall in a separate thread. This is very useful for programs that have to do multiple things ... | [
5,
0,
0
] | [] | [] | [
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0006015632_multithreading_python_python_multithreading.txt |
Q:
Tuple Unpacking Similar to Python, but in Common Lisp
Is there a way to assign the values of a list to a list of symbols in Common Lisp similar to the way that you can assign the values of tuple to variables in Python?
x, y, z = (1, 2, 3)
Something like
(setq '(n p) '(1 2))
Where n and p are now equal to 1 and 2... | Tuple Unpacking Similar to Python, but in Common Lisp | Is there a way to assign the values of a list to a list of symbols in Common Lisp similar to the way that you can assign the values of tuple to variables in Python?
x, y, z = (1, 2, 3)
Something like
(setq '(n p) '(1 2))
Where n and p are now equal to 1 and 2, respectively. The above was just how I was thinking about... | [
"Use DESTRUCTURING-BIND, which can do a whole heck of a lot more than tuple unpacking. Like assignment by keywords, and optional parameters, etc. Really, anything you can do with a function's parameter list.\nBut if you don't actually have a list to destructure, and want to set a bunch of variables at once, use PSE... | [
13,
10,
7
] | [] | [] | [
"common_lisp",
"iterable_unpacking",
"lisp",
"list",
"python"
] | stackoverflow_0006012688_common_lisp_iterable_unpacking_lisp_list_python.txt |
Q:
Is there any way to pass all variables in the current scope to Mako as a context?
I have a method like so:
def index(self):
title = "test"
return render("index.html", title=title)
Where render is a function that automatically renders the given template file with the rest of the variables passed in as it's... | Is there any way to pass all variables in the current scope to Mako as a context? | I have a method like so:
def index(self):
title = "test"
return render("index.html", title=title)
Where render is a function that automatically renders the given template file with the rest of the variables passed in as it's context. In this case, I'm passing title in as a variable in the context. This is a li... | [
"Use the technique given below:\ndef render(template, **vars):\n # In practice this would render a template\n print(vars)\n\ndef index():\n title = 'A title'\n subject = 'A subject'\n render(\"index.html\", **locals())\n\nif __name__ == '__main__':\n index()\n\nWhen you run the above script, it pr... | [
2,
0
] | [] | [] | [
"mako",
"python",
"templates"
] | stackoverflow_0006013539_mako_python_templates.txt |
Q:
Django dynamic css implementation
I have my little blog app, and I want to be able to change styles (not necessarily all) from admin page. What would be the 'right' way to implement dynamic style loading in django project?
My own thoughts:
Edit css file through Python file I/O
Construct css file from database
Thou... | Django dynamic css implementation | I have my little blog app, and I want to be able to change styles (not necessarily all) from admin page. What would be the 'right' way to implement dynamic style loading in django project?
My own thoughts:
Edit css file through Python file I/O
Construct css file from database
Though both implementations have serious dr... | [
"The \"right\" way to do this would be to define a single class at the top-level div (or even body), which determines the master style for that page. All the style-able elements in that page then inherit this style via the magic of cascading:\n.master-default {\n color: black;\n}\n.master-default .bordered {\n ... | [
1
] | [] | [] | [
"django",
"dynamic_css",
"python"
] | stackoverflow_0006015782_django_dynamic_css_python.txt |
Q:
how to solve this particular query in django queryset
+----+---------+-----------+---------------------+-----------+-----------+
| id | user_id | foo_id | created_at | active |type |
+----+---------+-----------+---------------------+-----------+-----------+
| 1 | 1 | 1 | 2011-05... | how to solve this particular query in django queryset | +----+---------+-----------+---------------------+-----------+-----------+
| id | user_id | foo_id | created_at | active |type |
+----+---------+-----------+---------------------+-----------+-----------+
| 1 | 1 | 1 | 2011-05-10 13:12:35 | 1 | 2 |
| 7 | 5 | ... | [
"If you mean user_id=6 and type=6 and food_id=2, then just use: \nUserMapper.objects.filter(user_id=6, type=6, food_id=2)\n\nif you mean (user_id=6) or (type=6 and food_id=2), you can use the Q object : \nfrom django.db.models import Q\nUserMapper.objects.filter(Q(user_id=6) | Q(type=6, food_id=2))\n\nSee more ab... | [
5,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006016095_django_python.txt |
Q:
input-validation & string conversion
I have a script, which take input from the user and I want to validate the input first then convert the user-input to a predefined format. The input should be like this:
my_script -c 'formatDate(%d/%m) == 23/5 && userName == John Dee && status == c
At the moment I'm dealing wi... | input-validation & string conversion | I have a script, which take input from the user and I want to validate the input first then convert the user-input to a predefined format. The input should be like this:
my_script -c 'formatDate(%d/%m) == 23/5 && userName == John Dee && status == c
At the moment I'm dealing with formatDate() bit only. The main rules a... | [
"You're not making a complication, but have you thought of the consequences of expanding the grammar of the user requests? \nThe simplest parser is Shunting yard algorithm. You can adopt it to the user requests and expand the grammar easily. You can find Python implementation here.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006016259_python.txt |
Q:
In Python, how do you get the content_type or mime_type of a file?
Possible Duplicate:
How to find the mime type of a file in python?
I'm using an email processing API (sendgrid.com) that posts all incoming emails to a web request handler in my app. The attachments are posted as attachment0=xyz&attachment1=abc a... | In Python, how do you get the content_type or mime_type of a file? |
Possible Duplicate:
How to find the mime type of a file in python?
I'm using an email processing API (sendgrid.com) that posts all incoming emails to a web request handler in my app. The attachments are posted as attachment0=xyz&attachment1=abc along with other email fields like 'to' 'cc' 'subject', etc...
I then st... | [
"If you saved the filename when it was uploaded, you'd use mimetypes.guess_type function to give it a shot here. The linked SO question by Alexander is good to read.\nUnfortunately, that is not your case. If all you have is a binary blob, I'm afraid you have to put on some custom heuristics here. Follow these simpl... | [
3
] | [] | [] | [
"email",
"file",
"mime",
"python"
] | stackoverflow_0006016291_email_file_mime_python.txt |
Q:
How do I fill a list in python with user-defined class instances?
So I'm trying to fill a list with instances of a class that I defined myself, but I keep getting an error when I try to access any element in the list. The code is below.
Any help would be appreciated!
class Population:
"""total population of worke... | How do I fill a list in python with user-defined class instances? | So I'm trying to fill a list with instances of a class that I defined myself, but I keep getting an error when I try to access any element in the list. The code is below.
Any help would be appreciated!
class Population:
"""total population of workers"""
workerl = []
def __init__(self, p, workers):
# p... | [
"Your program is flawed on oh so many levels.\nclass Population:\n\"\"\"total population of workers\"\"\" # <-- indentation error\n workerl = [] # <-- class attribute, never used\n\n def __init__(self, p, workers):\n # probability of a worker becoming unemployed\n # low in booms, high in recessi... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006014428_python.txt |
Q:
Exclusive access to a PostgreSQL table through python or Postgres
I have a table with a list of URL in stored in PG and I have an application which is supposed to take a subset of available URLs and process them. This application will update the processed field=true when it retrieves the set of URLs. I am going to... | Exclusive access to a PostgreSQL table through python or Postgres | I have a table with a list of URL in stored in PG and I have an application which is supposed to take a subset of available URLs and process them. This application will update the processed field=true when it retrieves the set of URLs. I am going to have multiple instances running on different machines. How do I ensure... | [
"This problem can be solved purely in your postgresql queries using the LOCK statement. Here is a link to the documentation with examples:\nhttp://www.postgresql.org/docs/8.1/static/sql-lock.html\n",
"You can lock rows in multiple ways, in postgresql: table-level locks, row-level locks, and advisory locks.\nhttp... | [
2,
2
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0006014112_postgresql_python.txt |
Q:
Writing a string to the last line in a file, Python
I'm attempting to make a function that writes a string to the last line in a file. However, what I currently have (below) only writes to the first line. So if I call the function more than once, it simply overwrites the first line. I'd like it to instead write th... | Writing a string to the last line in a file, Python | I'm attempting to make a function that writes a string to the last line in a file. However, what I currently have (below) only writes to the first line. So if I call the function more than once, it simply overwrites the first line. I'd like it to instead write the string to a new line; how would I go about this?
Snip... | [
"Open the file in append mode ('a' instead of 'w'). Opening in 'w' mode truncates your file (you're now writing into an empty file)\n"
] | [
16
] | [] | [] | [
"file",
"io",
"python",
"string"
] | stackoverflow_0006016937_file_io_python_string.txt |
Q:
python: where is a true built-in file object required?
From the python docs on urllib.urlopen(), talking about the file-like object the function returns on success:
(It is not a built-in file object, however, so it can’t be used at those few places where a true built-in file object is required.)
What are those f... | python: where is a true built-in file object required? | From the python docs on urllib.urlopen(), talking about the file-like object the function returns on success:
(It is not a built-in file object, however, so it can’t be used at those few places where a true built-in file object is required.)
What are those few places where a true built-in file object is required?
NB:... | [
"As the other answers have noted, there isn't really anywhere that specifically needs a file object, but there are interfaces that need real OS level file descriptors, which file-like objects like StringIO can't provide.\nThe os module has several methods that operate directly on file descriptors, as do the select ... | [
3,
2,
0
] | [] | [] | [
"api",
"file",
"interface",
"python",
"standard_library"
] | stackoverflow_0006012043_api_file_interface_python_standard_library.txt |
Q:
Do python thread wait for standard output?
if you run couple of threads but they all have to print to the same stdout, does this mean they have to wait on each other? so say if all 4 threads have something to write, they have to pause and wait for the stdout to be free so they can get on with their work?
A:
Deep... | Do python thread wait for standard output? | if you run couple of threads but they all have to print to the same stdout, does this mean they have to wait on each other? so say if all 4 threads have something to write, they have to pause and wait for the stdout to be free so they can get on with their work?
| [
"Deep deep (deep deep deep...) down in the OS's system calls, yes. Modern OSes have thread-safe terminal printing routines which usually just lock around the critical sections that do the actual device access (or buffer, depending on what you're writing into and what its settings are). These waits are very short, h... | [
3,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0006016663_multithreading_python.txt |
Q:
how to apply list methods on a slices in python
a = [1,2,3,4,5]
x = a[1:]
x.insert(0,5)
this works
but i want to combine all these statements into a single one to use it in a list comprehension
what is want is
x = a[1:].insert(0,5)
i can see what is wrong with this but but i cant find a correct method,
the exact... | how to apply list methods on a slices in python | a = [1,2,3,4,5]
x = a[1:]
x.insert(0,5)
this works
but i want to combine all these statements into a single one to use it in a list comprehension
what is want is
x = a[1:].insert(0,5)
i can see what is wrong with this but but i cant find a correct method,
the exact code is somewhat similar to this
spacelist = [ alist... | [
"What about trying something like this : \nx = [5,] + a[1:]\n",
"List comprehensions for their own sake are a mistake. Stop trying to make your code clever and cool and make sure people can read and comprehend what's going on in your code. If you want, put a \"TODO\" comment near it and update it later when you f... | [
6,
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"substring"
] | stackoverflow_0006017060_list_python_substring.txt |
Q:
How to convert a numpy array view to opencv matrix?
I'm using opencv v2.2 to do some template matching on ndarrays, and I had great trouble with memory leaks when using their wrapped method cv.fromarray(). Rather than plug the memory leaks I avoided the fromarray() function and used cv.SetData directly, like this... | How to convert a numpy array view to opencv matrix? | I'm using opencv v2.2 to do some template matching on ndarrays, and I had great trouble with memory leaks when using their wrapped method cv.fromarray(). Rather than plug the memory leaks I avoided the fromarray() function and used cv.SetData directly, like this:
assert foo_numpy.dtype == 'uint8'
assert foo_numpy.nd... | [
"I think the problem with what you were trying to do is that the array data you're interested in (ie. foo_np_view) is actually only stored in one place i.e. foo_np.data, and the OpenCV SetData method doesn't provide any way to specify stride settings that would allow you to skip the bytes that are not part of foo_n... | [
2
] | [] | [] | [
"arrays",
"numpy",
"opencv",
"python",
"stride"
] | stackoverflow_0005575108_arrays_numpy_opencv_python_stride.txt |
Q:
How is this called and how can be done ( `function_name.decorator` )?
Really sorry for the extremely stupid title, but if I know what it is, I wouldn't write here (:
def some_decorator( func ):
# ..
class A:
@some_decorator
def func():
pass
@func.some_decorator # this one here - func.so... | How is this called and how can be done ( `function_name.decorator` )? | Really sorry for the extremely stupid title, but if I know what it is, I wouldn't write here (:
def some_decorator( func ):
# ..
class A:
@some_decorator
def func():
pass
@func.some_decorator # this one here - func.some_decorator ?
def func():
pass
some_decorator decorates func ... | [
"Remember that the function definition with decorator is equivalent to this:\ndef func():\n pass\nfunc = some_decorator(func)\n\nSo in the following lines, func doesn't refer to the function you defined but to what the decorator turned it into. Also note that decorators can return any object, not just functions.... | [
7,
2
] | [] | [] | [
"decorator",
"python",
"python_3.x"
] | stackoverflow_0006010102_decorator_python_python_3.x.txt |
Q:
What language has been used to create Python?
Which programming language has been used to develop Python (programming language) ?
Thank you
A:
The most-often used implementation is written in C and called "CPython". It can be downloaded at the main Python website.
There are also implementations written in Java (... | What language has been used to create Python? | Which programming language has been used to develop Python (programming language) ?
Thank you
| [
"The most-often used implementation is written in C and called \"CPython\". It can be downloaded at the main Python website.\nThere are also implementations written in Java (Jython) and C# (IronPython) and Python (PyPy).\n",
"C Programming Language and others\nhttp://en.wikipedia.org/wiki/C_(programming_language)... | [
12,
4
] | [] | [] | [
"programming_languages",
"python"
] | stackoverflow_0006017599_programming_languages_python.txt |
Q:
How to get formatted date time in python
I want my Linux Filename like this
May-01-0340AM-2011.tar
How can i get the date variable formatted like above in Python
IN bash i write
date1=$(date +"%b-%d-%I%M%p-%G")
A:
You can use the same formatting string in strftime on a datetime object:
>>> import datetime
>>> ... | How to get formatted date time in python | I want my Linux Filename like this
May-01-0340AM-2011.tar
How can i get the date variable formatted like above in Python
IN bash i write
date1=$(date +"%b-%d-%I%M%p-%G")
| [
"You can use the same formatting string in strftime on a datetime object:\n>>> import datetime\n>>> datetime.datetime.now().strftime('%b-%d-%I%M%p-%G')\n'May-16-0245PM-2011'\n\nIncidentally, I'd just like to put a word in for the joy of ISO-8601 date formatting\n",
"Same formatting, using strftime():\n>>> import ... | [
28,
7
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0006017570_linux_python.txt |
Q:
NaN in python and validity checking
I'm doing a program where I optimize some values. Due to the equations, from time to time my values are NaN
My problem, some of the entries are NaN.
I would like to know if there is a test to check their logical validity so I can skip those values and retry.
So far I have tried ... | NaN in python and validity checking | I'm doing a program where I optimize some values. Due to the equations, from time to time my values are NaN
My problem, some of the entries are NaN.
I would like to know if there is a test to check their logical validity so I can skip those values and retry.
So far I have tried checking for
a==np.nan, a==nan, b=a a==b... | [
"Using numpy,\nimport numpy as np\nnp.isnan(np.nan) # returns True\n\n",
"Since Python 2.6, you want to import math and use math.isnan(a).\nSee http://docs.python.org/library/math.html#math.isnan\n"
] | [
30,
7
] | [] | [] | [
"nan",
"numpy",
"python"
] | stackoverflow_0006016744_nan_numpy_python.txt |
Q:
tagging module in python
In python 2.4 how to install the module tagging can any one give me links to it..I am trying to implement a blog system and in the models of which i require this module
A:
I fed django and tagging into a well-known search engine and got the following as the top hit:
http://code.google.c... | tagging module in python | In python 2.4 how to install the module tagging can any one give me links to it..I am trying to implement a blog system and in the models of which i require this module
| [
"I fed django and tagging into a well-known search engine and got the following as the top hit:\nhttp://code.google.com/p/django-tagging/\nSince most of your \"blog\" questions are related to Django, I presume that you meant that, rather than Python. It's written in Python, if that helps.\n",
"I believe Django-ta... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006017319_python.txt |
Q:
Proper output for the program
import itertools
file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
file.write(variation_string)
file.close()
The output fr... | Proper output for the program | import itertools
file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
file.write(variation_string)
file.close()
The output from the above program is like a clus... | [
"After your file.write, add another file.write('\\n').\n",
"Here is a revised code that fixes a few other issues in addition to the mentioned problem:\nimport itertools\nwith open('out.txt', 'w') as f:\n for variation in itertools.product('abc', repeat=3):\n f.write(str.join(\"\", variation) + \"\\n\")\... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006017831_python.txt |
Q:
using the value stored in the ._field attribute in python ast
This question is a result of my python ast work.
I have a node in the ast and I want to obtain its children.
The ._field attribute gives the names of all the children of a node. However it is different for different node depending upon the syntax node. ... | using the value stored in the ._field attribute in python ast | This question is a result of my python ast work.
I have a node in the ast and I want to obtain its children.
The ._field attribute gives the names of all the children of a node. However it is different for different node depending upon the syntax node.
for example if node is of type BinOp..then node._field will yield ... | [
"To iterate over the children of an arbitrary node, use ast.iter_child_nodes(). To iterate over the fields instead, use ast.iter_fields().\n"
] | [
2
] | [] | [] | [
"abstract_syntax_tree",
"python"
] | stackoverflow_0006018025_abstract_syntax_tree_python.txt |
Q:
Pyglet, edge pixels of images are being wrapped
I am currently working on developing game with Python and have been putting off trying to fix this issue.
For some reason the very edge of my image tiles are being wrapped around to the other side of the image. Not by a large amount just by a tiny sub pixel amount it... | Pyglet, edge pixels of images are being wrapped | I am currently working on developing game with Python and have been putting off trying to fix this issue.
For some reason the very edge of my image tiles are being wrapped around to the other side of the image. Not by a large amount just by a tiny sub pixel amount it seems.
Here is a close up of a screen shot so you ca... | [
"This problem is due to minor floating point accuracy problems, at the edges of the image. OpenGL has to interpolate against some value at the edges where no further values are given. The normal operation is GL_REPEAT, which means a wrap around effect for the texture. What you want is GL_CLAMP, but this has to be s... | [
1
] | [] | [] | [
"image",
"pyglet",
"python"
] | stackoverflow_0006017593_image_pyglet_python.txt |
Q:
Python: Pick other value
Please excuse (or improve the title) but I have a silly little problem that's making me very unsure.
I have a list that can contain one to two values, never more, never less and only these two options:
options = ['option one', 'option two']
As I say, sometimes there may only be one of tho... | Python: Pick other value | Please excuse (or improve the title) but I have a silly little problem that's making me very unsure.
I have a list that can contain one to two values, never more, never less and only these two options:
options = ['option one', 'option two']
As I say, sometimes there may only be one of those values in the list so it mi... | [
"options.remove(current_option)\noptions.append(False)\nreturn options[0]\n\nEdit: If you don't want to modify options, you can also use the somewhat less readable\nreturn (options + [False])[current_option == options[0]]\n\n",
"current_option = request.GET.get('option', options[0])\nif not current_option in opti... | [
10,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006018173_list_python.txt |
Q:
Partly wrong pyopencl output
I am trying to implement elementwise multiply with pyopencl, but when I read the result buffer from pyopencl, only the first 3 of 8 rows are correct. I am not sure if it is a problem with OpenCL or pyopencl. Here is my minimal example with output. I am happy for every suggestion.
Thank... | Partly wrong pyopencl output | I am trying to implement elementwise multiply with pyopencl, but when I read the result buffer from pyopencl, only the first 3 of 8 rows are correct. I am not sure if it is a problem with OpenCL or pyopencl. Here is my minimal example with output. I am happy for every suggestion.
Thanks
import pyopencl as cl
import num... | [
"There looks to be a bit of confusion about how you are specifying the shape of the arrays to the kernel - basically you have width and height reversed compared to how the source numpy arrays have been sized. As a result you are trying to write in column major order using a pitch of 4 words into the output array, r... | [
2
] | [] | [] | [
"opencl",
"python"
] | stackoverflow_0006016345_opencl_python.txt |
Q:
pyexpect alternative for windows
a friend of mine is searching for some alternative of pyexpect for windows, capable to run a binary and to feed its inputs and read outputs. Although we have made certain effort using google, still no success. Using pyexpect + cygwin is not the option here. Hence, here comes the qu... | pyexpect alternative for windows | a friend of mine is searching for some alternative of pyexpect for windows, capable to run a binary and to feed its inputs and read outputs. Although we have made certain effort using google, still no success. Using pyexpect + cygwin is not the option here. Hence, here comes the question: does anyone know about anythin... | [
"How about using actual Expect?\n"
] | [
0
] | [] | [] | [
"expect",
"python"
] | stackoverflow_0006016919_expect_python.txt |
Q:
import cx_oracle fails when python script is started as win32 service
I have written a python script that should run as a windows service by subclassing the win32serviceutil.ServiceFramework. Within the script the cx_oracle module is used.
When I run the service in debug mode ( python DLOGprod.py debug ) everythin... | import cx_oracle fails when python script is started as win32 service | I have written a python script that should run as a windows service by subclassing the win32serviceutil.ServiceFramework. Within the script the cx_oracle module is used.
When I run the service in debug mode ( python DLOGprod.py debug ) everything works fine.
But when I try to start the service ( python DLOGprod.py star... | [
"I did resolve my problem. The root cause was I had only added the path to the oracle client software to the user's PATH variable. Since adding it to the system wide PATH variable everything is working fine.\nTo troubleshoot the issue I have followed the following procedure:\n\ndownloaded the process explorer utili... | [
1
] | [] | [] | [
"cx_oracle",
"python",
"winapi"
] | stackoverflow_0005994021_cx_oracle_python_winapi.txt |
Q:
How to read multiline .properties file in python
I'm trying to read a java multiline i18n properties file. Having lines like:
messages.welcome=Hello\
World!
messages.bye=bye
Using this code:
import configobj
properties = configobj.ConfigObj(propertyFileName)
But with multilines values it fails.
Any suggestions?... | How to read multiline .properties file in python | I'm trying to read a java multiline i18n properties file. Having lines like:
messages.welcome=Hello\
World!
messages.bye=bye
Using this code:
import configobj
properties = configobj.ConfigObj(propertyFileName)
But with multilines values it fails.
Any suggestions?
| [
"According to the ConfigObj documentation, configobj requires you to surround multiline values in triple quotes:\n\nValues that contain line breaks\n (multi-line values) can be surrounded\n by triple quotes. These can also be\n used if a value contains both types of\n quotes. List members cannot be\n surrounde... | [
6,
1,
0,
0,
0
] | [] | [] | [
"multiline",
"properties",
"python"
] | stackoverflow_0005984603_multiline_properties_python.txt |
Q:
How to add a button to matplotlib.pylab.imshow() dialog?
I want to do additional operations on the image displayed by matplotlib.pyplot.imshow() method.
For Example:
I want an extra button "Display ROI" where it displays the ROI of the co-ordinates I have selected in the image in my preferred format.
Is this possi... | How to add a button to matplotlib.pylab.imshow() dialog? | I want to do additional operations on the image displayed by matplotlib.pyplot.imshow() method.
For Example:
I want an extra button "Display ROI" where it displays the ROI of the co-ordinates I have selected in the image in my preferred format.
Is this possible?
| [
"There is a widgets module in matplotlib that can give you that functionality. Check out the widgets examples page.\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006012961_matplotlib_python.txt |
Q:
Memory profiler for numpy
I have a numpy script that -- according to top -- is using about 5GB of RAM:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
16994 aix 25 0 5813m 5.2g 5.1g S 0.0 22.1 52:19.66 ipython
Is there a memory profiler that would enable me to get some idea about the obje... | Memory profiler for numpy | I have a numpy script that -- according to top -- is using about 5GB of RAM:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
16994 aix 25 0 5813m 5.2g 5.1g S 0.0 22.1 52:19.66 ipython
Is there a memory profiler that would enable me to get some idea about the objects that are taking most of tha... | [
"Numpy (and its library bindings, more on that in a minute) use C malloc to allocate space, which is why memory used by big numpy allocations doesn't show up in the profiling of things like heapy and never gets cleaned up by the garbage collector.\nThe usual suspects for big leaks are actually scipy or numpy librar... | [
11
] | [] | [] | [
"memory",
"memory_profiling",
"numpy",
"python"
] | stackoverflow_0006018986_memory_memory_profiling_numpy_python.txt |
Q:
Is there a way to add a namespace prefix setuptools package distributions?
I'm looking to add a namespace prefix to my Python setuptools distributed package. E.g. we have a package called common_utils and a would like it to be accessed as umbrella.common_utils without having to include the dummy directory/module '... | Is there a way to add a namespace prefix setuptools package distributions? | I'm looking to add a namespace prefix to my Python setuptools distributed package. E.g. we have a package called common_utils and a would like it to be accessed as umbrella.common_utils without having to include the dummy directory/module 'umbrella' in the package tree.
Is this possible?
Thanks,
| [
"You can use the package_dir option to tell setuptools the full package name and location of the subpackage:\nfrom setuptools import setup\n\nsetup(\n name = 'umbrella',\n packages = [\n 'umbrella.common_utils'\n ],\n package_dir = {\n 'umbrella.common_utils': './common_utils'\n ... | [
3
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0006019042_python_setuptools.txt |
Q:
Need help to convert the bash code to python equivalent
I have this in my bash script
for FOLDERNAME in `\ls -1 /home/`
do
if [ ! -d /backups/home/${date} ]; then
mkdir /backups/home/${date}
chmod 777 /backups/home/${date}
/bin/chgrp ${FOLDERNAME} /backups/home/${FOLDERNAME}
usermod -a -G ${FOLDERNAME} john
fi
ho... | Need help to convert the bash code to python equivalent | I have this in my bash script
for FOLDERNAME in `\ls -1 /home/`
do
if [ ! -d /backups/home/${date} ]; then
mkdir /backups/home/${date}
chmod 777 /backups/home/${date}
/bin/chgrp ${FOLDERNAME} /backups/home/${FOLDERNAME}
usermod -a -G ${FOLDERNAME} john
fi
how can i convert that to python code
| [
"Most of it can be done using the \"os\" module : I advise you to have a look at the doc of this module, try, and if you have issue, ask for relevant questions. \n",
"While not being very familiar with Linux commands, this code should help you in attaining your final goal.\nimport shutil, datetime\nshutil.copytre... | [
2,
0
] | [] | [] | [
"bash",
"linux",
"python"
] | stackoverflow_0006017637_bash_linux_python.txt |
Q:
Find max length of each column in a list of lists
I'm using Python 2.6 along with the xlwt and pyodbc modules to create excel reports from a view on an MS SQL Sever (2008). In order to programatically set the correct width of each field in excel, I would like to retrieve the maximum length of the values in each c... | Find max length of each column in a list of lists | I'm using Python 2.6 along with the xlwt and pyodbc modules to create excel reports from a view on an MS SQL Sever (2008). In order to programatically set the correct width of each field in excel, I would like to retrieve the maximum length of the values in each column.
For example
foo=[[1, 'This is a test',12039],[1... | [
"[max(len(str(x)) for x in line) for line in zip(*foo)]\n\n",
"If the input lists are very long, itertools.izip() might be a better choice than zip() since it will return an iterator instead of a long list, so you can save some memory space.\n"
] | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0006018916_python.txt |
Q:
Python - How to specify an optional argument for class based decorators?
How would I write a decorator like this. I want to be able to specify the value for max_hits when I call the decorator (or optionally leave it out).
E.g., the desired use would be
@memoize(max_hits=7)
def a(val):
print val
or
@memoize
d... | Python - How to specify an optional argument for class based decorators? | How would I write a decorator like this. I want to be able to specify the value for max_hits when I call the decorator (or optionally leave it out).
E.g., the desired use would be
@memoize(max_hits=7)
def a(val):
print val
or
@memoize
def a(val):
print val
(Using the first example gives an error about incorr... | [
"You have to make memoize a function that takes an optional argument max_hits and returns a decorator (i.e. another callable object that will take the function as the first argument); in this case, you can use the following two syntaxes:\n@memoize()\ndef func(x):\n [...]\n\n@memoize(max_hits=7)\ndef func(x):\n ... | [
8,
4
] | [] | [] | [
"decorator",
"memoization",
"python"
] | stackoverflow_0006018403_decorator_memoization_python.txt |
Q:
Attribute error using python scientific module on Windows
I get the following error when our program is run on Windows XP using ActivePerl 2.6 (although it runs fine on linux). Any ideas of what is going on? Is this a bug in the module or a problem with our code?
Error log:
File "C:\Python26\lib\site-package... | Attribute error using python scientific module on Windows | I get the following error when our program is run on Windows XP using ActivePerl 2.6 (although it runs fine on linux). Any ideas of what is going on? Is this a bug in the module or a problem with our code?
Error log:
File "C:\Python26\lib\site-packages\Scientific\IO\PDB.py", line 1163, in __ini
t__
se... | [
"I'm guessing, but it looks like a bug in Scientific.IO.PDB where they do something like:\nif type(file_or_filename) == str:\n file = open(file_or_filename)\nelse:\n file = file_or_filename\n\nrather than doing:\nif isinstance(file_or_filename, basestr):\n ...\n\nFor whatever reason, you appear to be passi... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005888668_python.txt |
Q:
Django error when removing ForeignKey relationship
I have a class as following:
class Mission(models.Model):
taxi = ForeignKey(Taxi, null=True, blank=True, unique=True, related_name="mission")
passenger = ForeignKey(Passenger, null=True, blank=True, unique=True, related_name="mission")
Now there's a metho... | Django error when removing ForeignKey relationship | I have a class as following:
class Mission(models.Model):
taxi = ForeignKey(Taxi, null=True, blank=True, unique=True, related_name="mission")
passenger = ForeignKey(Passenger, null=True, blank=True, unique=True, related_name="mission")
Now there's a method in the Class Taxi:
def turn_free(self):
....
s... | [
"Make sure your database has been updated properly.\nFor example, if you originally had (without specifying null=True)\npassenger = Foreignkey(Passsenger, unique=True)\n\nAnd added the null=True later on, a regular syncdb will not update that column to allow null.\nIf any of that sounds familiar, try doing an sqlcl... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006015322_django_python.txt |
Q:
How to prevent termination of a running program using "ctrl+c" in Linux using python?
I have written a piece of code in python, in which I am asking questions and users should give their input. Sometimes, these questions are difficult for the user to understand(they are non-english). So most of the time they want ... | How to prevent termination of a running program using "ctrl+c" in Linux using python? | I have written a piece of code in python, in which I am asking questions and users should give their input. Sometimes, these questions are difficult for the user to understand(they are non-english). So most of the time they want to copy paste the sentence into google translate. However, since this code is running in th... | [
"When you hit ctrl+c it sends SIGINT to the running process. You can catch it as described here.\nYou can find more about the different types of signals here.\n",
"import signal\ndef SigIntHand(SIG, FRM):\n print(\"Please Right click-copy. Ctrl-C does not work on the cmd prompt\")\n\nsignal.signal(signal.SIGI... | [
2,
2,
0
] | [] | [] | [
"command_line",
"keyboard_shortcuts",
"python"
] | stackoverflow_0006019192_command_line_keyboard_shortcuts_python.txt |
Q:
How do I plot with matplotlib, called from a function?
I currently have a main script, calling a function. Part of that functions functionality is plotting two graphs. The script works if I include show() at the end, but it is a bit annoying that either the script pauses until I close the graph or I have to wait t... | How do I plot with matplotlib, called from a function? | I currently have a main script, calling a function. Part of that functions functionality is plotting two graphs. The script works if I include show() at the end, but it is a bit annoying that either the script pauses until I close the graph or I have to wait to look at the graphs until the program is finished. Hence I ... | [
"You can use a different rendering backend, however, you will need to save the plot as a file with savefig instead of using show\nimport matplotlib\nmatplotlib.use('Agg')\n\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006019419_matplotlib_python.txt |
Q:
Deploying with git
Currently I have a bunch of git repos for a django site i'm looking to deploy, the repos' take the form:
sn-static
sn-django
sn-templates
[etc]
I then have a super repos that stores each of these as a submodules. In terms of deployment, I want to try to keep things fairly simple, would it be a ... | Deploying with git | Currently I have a bunch of git repos for a django site i'm looking to deploy, the repos' take the form:
sn-static
sn-django
sn-templates
[etc]
I then have a super repos that stores each of these as a submodules. In terms of deployment, I want to try to keep things fairly simple, would it be a valid method to:
Clone ... | [
"An option you should consider is using pip in conjunction with virtualenv to install your packages especially as pip has the option to directly install certain branches or tags from a git repository.\nThat way you can use one requirements file to handle all your dependencies, your own packages and apps by other pe... | [
2
] | [
"When you reach a release point in your code, tag it (Git Tag). On your server, clone the master branch once and then simply to pull the release tag you want, each time you do a release.\ngit pull [tag]\n\n"
] | [
-1
] | [
"deployment",
"django",
"git",
"production",
"python"
] | stackoverflow_0006018995_deployment_django_git_production_python.txt |
Q:
Stopping a request in Tornado
I have a method for signing up a user, basically if the user fails
validation I want the request to stop processing so the user isn't
signed up.
def post(self):
#[...]
if isvalid(username) == False:
print "Invalid Username"
self.redirect("/baduserna... | Stopping a request in Tornado | I have a method for signing up a user, basically if the user fails
validation I want the request to stop processing so the user isn't
signed up.
def post(self):
#[...]
if isvalid(username) == False:
print "Invalid Username"
self.redirect("/badusername")
print "User Is OK"
If... | [
"def post(self):\n #[...]\n if isvalid(username) == False:\n print \"Invalid Username\"\n self.redirect(\"/badusername\")\n else:\n print \"User Is OK\"\n\n",
"Just do a return, like this:\ndef post(self):\n #[...]\n if not isvalid(username):\n ... | [
1,
1,
1
] | [] | [] | [
"python",
"tornado",
"web.py"
] | stackoverflow_0006019768_python_tornado_web.py.txt |
Q:
Parameterized queries with psycopg2: SELECT from a Python list
Given a large (~10,000) list of integers in Python, How do I efficiently SELECT all items from a table whose id is in the list?
I've tried:
>>> lst2
[{'id': 97600167}, {'id': 97600168}, {'id': 97611194}]
>>> cur.executemany("SELECT id, parent_id FROM m... | Parameterized queries with psycopg2: SELECT from a Python list | Given a large (~10,000) list of integers in Python, How do I efficiently SELECT all items from a table whose id is in the list?
I've tried:
>>> lst2
[{'id': 97600167}, {'id': 97600168}, {'id': 97611194}]
>>> cur.executemany("SELECT id, parent_id FROM my_table WHERE id=%(id)s", lst2)
>>> cur.fetchall()
[(97611194, 10020... | [
"Using your example, use where id in and then pass a parameter which is a tuple of the id values you want to select:\n>>> lst2\n[{'id': 97600167}, {'id': 97600168}, {'id': 97611194}]\n>>> ids = tuple(x['id'] for x in lst2)\n>>> cur.execute(\"SELECT id, parent_id FROM my_table where id in %s\",[ids])\n\n"
] | [
8
] | [] | [] | [
"psycopg2",
"python",
"sql_parametrized_query"
] | stackoverflow_0006018966_psycopg2_python_sql_parametrized_query.txt |
Q:
Passing parameters to form action in Django?
Template:
<form method="post" action="/reply/{{feed.id}}/">
{{rform.as_p}}
<input type="submit" value="send" />
</form>
and url:
(r'^reply/(\d+)/$',reply),
But when we submit the form, {{feed.id}} is not translated and url directs to /reply//
Are parameter... | Passing parameters to form action in Django? | Template:
<form method="post" action="/reply/{{feed.id}}/">
{{rform.as_p}}
<input type="submit" value="send" />
</form>
and url:
(r'^reply/(\d+)/$',reply),
But when we submit the form, {{feed.id}} is not translated and url directs to /reply//
Are parameters not allowed in form actions?
If its allowed then... | [
"If {{ feed.id }} is empty it means that that either feed.id is empty, or feed is None. Make sure you are passing feed in your view context when you render the template using render_to_response\n",
"I assume your feed is dictionary object?\nIn your views.py module \nfrom django.shortcuts import render_to_respons... | [
1,
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0006016774_django_django_forms_django_templates_django_urls_python.txt |
Q:
Django: Question on Template Inheritance
Hello I seem to be having a problem of using a base template. My base html is called help_content.html.
<html>
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=UTF-8">
<a href="help_new_client.html">New Client</a>
<title>User Manual</title>
... | Django: Question on Template Inheritance | Hello I seem to be having a problem of using a base template. My base html is called help_content.html.
<html>
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=UTF-8">
<a href="help_new_client.html">New Client</a>
<title>User Manual</title>
<style></style></head>
<body style="padding... | [
"I guess that you are not rendering the template from a view.\nAre you sure you are doing something like this in a view, and that you are executing that view via a corresponding url pattern:\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\ndef index(request):\n return... | [
0,
0
] | [] | [] | [
"django",
"html",
"python",
"templates"
] | stackoverflow_0006016430_django_html_python_templates.txt |
Q:
Is using the google appengine parent attribute to apply default permissions to an object a good idea?
While hacking together an authorization framework for my web app, I thought a lot of my work would be cut out if by default I applied the following logic. All objects created by a 'User' have a parent being the 'U... | Is using the google appengine parent attribute to apply default permissions to an object a good idea? | While hacking together an authorization framework for my web app, I thought a lot of my work would be cut out if by default I applied the following logic. All objects created by a 'User' have a parent being the 'User'. When a query is run to retrieve objects for a view, limit the returned objects by applying the ancest... | [
"If you aim is to cordon-off all the objects that are related to a single account, then you might want to look at the multi-tenancy features, which are designed to do just this.\nIf your aim is just to have a convienent way to grab everything created by a single user, then we would need to know more about what your... | [
4,
3
] | [] | [] | [
"authorization",
"google_app_engine",
"python"
] | stackoverflow_0006020055_authorization_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.