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:
My implementation of Bresenham's algorithm fails for lines at certain angles
I've written an implementation of Bresenham's algorithm in Python (following the Wikipedia article), and it works correctly except for lines at certain angles. All lines that should extend between 45 and 90 degrees, or between 135 and 27... | My implementation of Bresenham's algorithm fails for lines at certain angles | I've written an implementation of Bresenham's algorithm in Python (following the Wikipedia article), and it works correctly except for lines at certain angles. All lines that should extend between 45 and 90 degrees, or between 135 and 270 degrees, will instead extend along the line y = x.
Here's my code:
def bresenh... | [
"I don't know why you're using an xstep variable. You don't really need one with the algorithm you're using.\n\n@Gabe: xstep is needed because without it, if x0 > x1, then the for loop will terminate immediately, as the default step for a Python for loop is 1.\n\nThe reason you don't need an xstep variable is becau... | [
4,
4
] | [] | [] | [
"bresenham",
"python"
] | stackoverflow_0003713821_bresenham_python.txt |
Q:
Handling file reading and multiple values to a key in dictionary
How can I code to read the first line from a file and put it as a key value of a dictionary and keep reading next values in a iterative manner and put them as the values to the particular key they fall into in the file.
Like example:
Item Quality ... | Handling file reading and multiple values to a key in dictionary | How can I code to read the first line from a file and put it as a key value of a dictionary and keep reading next values in a iterative manner and put them as the values to the particular key they fall into in the file.
Like example:
Item Quality Cost Place
Ball 1 $12 TX
Umbrella 5 $35 NY
... | [
"Looks like you are describing a csv file with a space delimiter. Something like this should work (from the Python help).\n>>> import csv\n>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')\n>>> for row in spamReader:\n... print ', '.join(row)\nSpam, Spam, Spam, Spam, Spam, Baked ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003714067_python.txt |
Q:
Two Tkinter Images
I have written a simple GUI in Python using the Tkinter library. This GUI has to display 2 images, one on top and one on the bottom. When I place the two images on the window, there seems to be a white line between the two. How to I place them so this doesn't show up?
I am programming on Windows... | Two Tkinter Images | I have written a simple GUI in Python using the Tkinter library. This GUI has to display 2 images, one on top and one on the bottom. When I place the two images on the window, there seems to be a white line between the two. How to I place them so this doesn't show up?
I am programming on Windows 7 with Python 2.6
| [
"I set border=0 and it seemed to eliminate the gap between the two stacked images.\n\npanel1 = Label(root, border=0, image=p)\npanel2 = Label(root, border=0, image=p)\n\n"
] | [
1
] | [] | [] | [
"image",
"python",
"tkinter",
"user_interface",
"windows_7"
] | stackoverflow_0003713499_image_python_tkinter_user_interface_windows_7.txt |
Q:
Python: spawn or thread for long running background process?
I am planning to make a long running background process with Python but I am still unsure whether to use os.spawnle or thread. I've only read about it therefore I have not much experience with either spawn or thread. Is there any rule of thumb when to us... | Python: spawn or thread for long running background process? | I am planning to make a long running background process with Python but I am still unsure whether to use os.spawnle or thread. I've only read about it therefore I have not much experience with either spawn or thread. Is there any rule of thumb when to use which?
Thanks heaps
| [
"Be sure that you take the Global Interpreter Lock into account. If the long running process is CPU intensive, you should probably make it an independent process. If on the other hand, it's going to spend a lot of time blocking, then the GIL isn't really that big of a deal and you should be fine to make it a thread... | [
4,
2
] | [] | [] | [
"background_process",
"python",
"spawn"
] | stackoverflow_0003713429_background_process_python_spawn.txt |
Q:
What to use for Python string.find?
The documentation for Python 2.7 lists string.find as a deprecated function but does not (unlike atoi and atol) provide an alternative.
I'm coding in 2.7 at the moment so I'm happy to use it but I would like to know:
what is it going to be replaced with?
is that usable in 2.7 (... | What to use for Python string.find? | The documentation for Python 2.7 lists string.find as a deprecated function but does not (unlike atoi and atol) provide an alternative.
I'm coding in 2.7 at the moment so I'm happy to use it but I would like to know:
what is it going to be replaced with?
is that usable in 2.7 (if so, I'll use it now so as to avoid rec... | [
"A lot of methods in string have been replaced by the str class. Here is str.find.\n",
"Almost the entire string module has been moved to the str type as method functions.\nWhy are you using the string module, when almost everything you need is already part of the string type?\nhttp://docs.python.org/library/std... | [
6,
6
] | [] | [] | [
"deprecated",
"find",
"python",
"string"
] | stackoverflow_0003714276_deprecated_find_python_string.txt |
Q:
How to inspect mystery deserialized object in Python
I'm trying to load JSON back into an object. The "loads" method seems to work without error, but the object doesn't seem to have the properties I expect.
How can I go about examining/inspecting the object that I have (this is web-based code).
results = {"Su... | How to inspect mystery deserialized object in Python | I'm trying to load JSON back into an object. The "loads" method seems to work without error, but the object doesn't seem to have the properties I expect.
How can I go about examining/inspecting the object that I have (this is web-based code).
results = {"Subscriber": {"firstname": "Neal", "lastname": "Walters"}}
... | [
"json only encodes strings, floats, integers, javascript objects (python dicts) and lists.\nYou have to create a function to turn the returned dictionary into a class and then pass it to a json.loads using the object_hook keyword argument along with the json string. Heres some code that fleshes it out:\nimport json... | [
4,
3,
0
] | [] | [] | [
"google_app_engine",
"inspection",
"json",
"python"
] | stackoverflow_0003706208_google_app_engine_inspection_json_python.txt |
Q:
Python, trying to instantiate class imported using __import__, getting ''module' object is not callable'
I've been researching how to do this and I can't figure out what I am doing wrong, I want to use import to import a class and then instantiate it and am doing it as so:
the class, from a file called "action_1",... | Python, trying to instantiate class imported using __import__, getting ''module' object is not callable' | I've been researching how to do this and I can't figure out what I am doing wrong, I want to use import to import a class and then instantiate it and am doing it as so:
the class, from a file called "action_1", I have already imported / appended the path to this)
class Action_1 ():
def __init__ (self):
pass... | [
"__import__ returns the module, not anything specified in the fromlist. Check out the __import__ docs and see the example below.\n>>> a1module = __import__('action_1', fromlist=['Action_1'])\n>>> action1 = a1module.Action_1()\n>>> print action1\n<action_1.Action_1 instance at 0xb77b8a0c>\n\nNote, the fromlist is no... | [
2
] | [] | [] | [
"class",
"dynamic",
"import",
"python"
] | stackoverflow_0003714573_class_dynamic_import_python.txt |
Q:
can a django application be run using paster?
can a django application be run using paster? Or is it pylons specific?
A:
It's pylons specific. There was a Django Paste project, but I'm not sure if it's active or how much progress was ever made.
| can a django application be run using paster? | can a django application be run using paster? Or is it pylons specific?
| [
"It's pylons specific. There was a Django Paste project, but I'm not sure if it's active or how much progress was ever made.\n"
] | [
1
] | [] | [] | [
"django",
"pylons",
"python"
] | stackoverflow_0003714373_django_pylons_python.txt |
Q:
which language (python/perl/tcl) on linux doesn't need to install the third-party libs?
When deploy java app on linux, we don't need to install anything, all third-party libs are jar files and we only update classpath in script file. But java needs jre which is quite large.
So is there any other language supported... | which language (python/perl/tcl) on linux doesn't need to install the third-party libs? | When deploy java app on linux, we don't need to install anything, all third-party libs are jar files and we only update classpath in script file. But java needs jre which is quite large.
So is there any other language supported by linux can do that? By default our server only support perl/python/tcl, no gcc available, ... | [
"Perl 5 has PAR and PAR::Packer. PAR is conceptually similar to a JAR file (it is a zip file of one or more modules). PAR::Packer takes it one step further: it bundles every you need to run a program into one executable file. PAR::Packer executables don't even need Perl 5 installed on the target system.\n",
"p... | [
10,
4,
3,
2,
0
] | [] | [] | [
"java",
"linux",
"perl",
"python",
"tcl"
] | stackoverflow_0003675659_java_linux_perl_python_tcl.txt |
Q:
Is there a way to compare two lists of dicts in python efficiently?
I have two lists of dictionaries. The first list contains sphere definitions in terms of x, y, z, radius. The second list contains various points in space as x, y, z. These lists are both very long, so iterating over each list and comparing agains... | Is there a way to compare two lists of dicts in python efficiently? | I have two lists of dictionaries. The first list contains sphere definitions in terms of x, y, z, radius. The second list contains various points in space as x, y, z. These lists are both very long, so iterating over each list and comparing against all values is inefficient.
I've been trying the map and reduce terms, ... | [
"try this:\ndef in_sphere(node):\n return any(float(findRadius(sphere, node)) <= float(sphere['radius']) \n for sphere in sphereList)\n\nnodeRemovalList = filter(in_sphere, nodeList)\n\nThis will run much faster than the code that you have displayed.\nthis is assuming that you actually want the nod... | [
4,
3,
2
] | [] | [] | [
"compare",
"filter",
"list",
"performance",
"python"
] | stackoverflow_0003715039_compare_filter_list_performance_python.txt |
Q:
Can stuck Python threads hinder other threads if there are no shared resources?
I am considering utilizing Python to call various dlls that will perform things like accessing the LAN (on Windows) or making HTTP requests. These dlls might be poorly written and get stuck. My first question is, whether isolating thes... | Can stuck Python threads hinder other threads if there are no shared resources? | I am considering utilizing Python to call various dlls that will perform things like accessing the LAN (on Windows) or making HTTP requests. These dlls might be poorly written and get stuck. My first question is, whether isolating these dll calls in Python threads will guarantee that the main Python thread will not get... | [
"Your main thread will still be responsive if another thread is issuing a blocking call. Still, terminating a thread is never really clean and might leave a mess around. See the MSDN documentation for TerminateThread for that matter.\nWith the introduction of the subprocess module, what are your concerns when it co... | [
1
] | [] | [] | [
"multithreading",
"python",
"python_3.x",
"python_multithreading"
] | stackoverflow_0003716027_multithreading_python_python_3.x_python_multithreading.txt |
Q:
wxPython: Assigning text labels to ticks on a slider
A wxPython program that I'm writing uses two sliders as part of the GUI. These sliders represent a three state switch with the states "On Full", "On Medium" and "Off". I'd like to be able to assign these labels to the ticks on the slider. Is there a way of doing... | wxPython: Assigning text labels to ticks on a slider | A wxPython program that I'm writing uses two sliders as part of the GUI. These sliders represent a three state switch with the states "On Full", "On Medium" and "Off". I'd like to be able to assign these labels to the ticks on the slider. Is there a way of doing this without having to subclass or position separate stat... | [
"Not built in. You'd have to create your own.\n"
] | [
1
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003715317_python_user_interface_wxpython.txt |
Q:
Is python's shutil.move() atomic on linux?
I am wondering whether python's shutil.move is atomic on linux ? Is the behavior different if the source and destination files are on two different partitions or is it same as when they are present on the same partition ?
I am more concerned to know whether the shutil.mov... | Is python's shutil.move() atomic on linux? | I am wondering whether python's shutil.move is atomic on linux ? Is the behavior different if the source and destination files are on two different partitions or is it same as when they are present on the same partition ?
I am more concerned to know whether the shutil.move is atomic if the source and destination files ... | [
"It is not atomic if the files are on different filsystems. In that case, python opens the source and destination file, loops on reading from the source and writing to the desination and finally unlinks the source file.\nIf the source and destination file are on the same file system, python uses the rename() C cal... | [
22
] | [] | [] | [
"atomic",
"file",
"python",
"unix"
] | stackoverflow_0003716325_atomic_file_python_unix.txt |
Q:
gtk: indicate a button should be pressed
What's the best way to indicate on a GTK interface that a button should be pressed / to "highlight" the button? The use case is that I have a set of checkboxes representing various settings, but for them to take effect, they must be submitted to a server. I want to indicate... | gtk: indicate a button should be pressed | What's the best way to indicate on a GTK interface that a button should be pressed / to "highlight" the button? The use case is that I have a set of checkboxes representing various settings, but for them to take effect, they must be submitted to a server. I want to indicate that the currently checked settings have not ... | [
"Perhaps you could disable the button (so that it \"greyed out\") until all the checkboxes have been set or whatever... This is quite a common approach.\n",
"You could set the button's label to be bold when there are changes to be submitted:\nbutton.get_child().set_markup('<b>Submit</b>')\n\n"
] | [
4,
1
] | [] | [] | [
"coding_style",
"gtk",
"python",
"user_interface"
] | stackoverflow_0003711300_coding_style_gtk_python_user_interface.txt |
Q:
Python: safe to read values from an object in a thread?
I have a Python/wxPython program where the GUI is the main thread and I use another thread to load data from a file. Sometimes the files are big and slow to load so I use a wxPulse dialog to indicate progress.
As I load the file, I count the number of lines ... | Python: safe to read values from an object in a thread? | I have a Python/wxPython program where the GUI is the main thread and I use another thread to load data from a file. Sometimes the files are big and slow to load so I use a wxPulse dialog to indicate progress.
As I load the file, I count the number of lines that have been read in the counting thread, and I display thi... | [
"Generally as long as...\n\nYou only have one thread writing to it, and...\nIt's not important that the count be kept precisely in sync with the displayed value...\n\nit's fine.\n",
"In normal python this will be safe as all access to variables are protected by the GIL(Global Interpreter Lock) this means that all... | [
8,
3,
2,
1,
0
] | [] | [] | [
"python",
"thread_safety"
] | stackoverflow_0003714613_python_thread_safety.txt |
Q:
python bitwise operation
hi i am new in python just started learning with python i got a task in which i need to store "1" byte of integer into different bits just like RGB the value are store in that can any one would write a small program for me and explain that ,please i need a help
Thankyou
A:
I'll assume t... | python bitwise operation | hi i am new in python just started learning with python i got a task in which i need to store "1" byte of integer into different bits just like RGB the value are store in that can any one would write a small program for me and explain that ,please i need a help
Thankyou
| [
"I'll assume this question is legitimate and appropriate for the forum..\n# To Encode:\nr = 1\ng = 2\nb = 3\n\nrgb = r << 16 | g << 8 | b\n\n#To extract:\nr = (rgb >> 16) & 0xFF\ng = (rgb >> 8) & 0xFF\nb = rgb & 0xFF\n\n",
"To convert a number to a list of it's binary digits: list(bin(number))[2:]\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003711762_python.txt |
Q:
GtkExpander style widget in wxWidgets?
I'm looking for a widget along the lines of GtkExpander, but for wxWidgets. Can't seem to find anything obvious in the documentation. Custom widgets (non-GPL) from somewhere else would be fine, but they need to work on Windows (i.e. without GTK).
Practically (if it makes any ... | GtkExpander style widget in wxWidgets? | I'm looking for a widget along the lines of GtkExpander, but for wxWidgets. Can't seem to find anything obvious in the documentation. Custom widgets (non-GPL) from somewhere else would be fine, but they need to work on Windows (i.e. without GTK).
Practically (if it makes any difference) this is primarily for wxPython, ... | [
"Damn, I'm stupid. If you've got here because you're stupid too, check out wxCollapsiblePane.\n"
] | [
3
] | [] | [] | [
"gtk",
"python",
"windows",
"wxpython",
"wxwidgets"
] | stackoverflow_0003716997_gtk_python_windows_wxpython_wxwidgets.txt |
Q:
Sentence Splitter testing file
I am looking for a testing file for my Sentence Splitter Application, and i hope the file can cover as many cases as possible.
Thanks!
A:
Read the documentation for Lingua::Sentence. It names the corpus it uses, and also related sentence splitting modules. Peruse the test files.
| Sentence Splitter testing file | I am looking for a testing file for my Sentence Splitter Application, and i hope the file can cover as many cases as possible.
Thanks!
| [
"Read the documentation for Lingua::Sentence. It names the corpus it uses, and also related sentence splitting modules. Peruse the test files.\n"
] | [
6
] | [] | [] | [
"java",
"perl",
"python"
] | stackoverflow_0003717171_java_perl_python.txt |
Q:
Color handling in Python
For my clustering gui, I am currently using random colors for the clusters, since I won't know before hand how many clusters I will end up with.
In Python, this looks like:
import random
def randomColor():
return (random.random(),random.random(),random.random())
However, when I update... | Color handling in Python | For my clustering gui, I am currently using random colors for the clusters, since I won't know before hand how many clusters I will end up with.
In Python, this looks like:
import random
def randomColor():
return (random.random(),random.random(),random.random())
However, when I update things, the colors change.
So... | [
"One way is to use caching. Use a defaultdict:\n>>> import random\n>>> def randomColor():\n... return (random.random(),random.random(),random.random())\n... \n>>> from collections import defaultdict\n>>> colors = defaultdict(randomColor)\n>>> colors[3]\n(0.10726172906719755, 0.97327604757295705, 0.58935794305308... | [
6,
2,
1,
1
] | [
"You can use i to seed the random number generator. So, as long as the seed remains the same, you get the same value.\n>>> import random\n>>> random.seed(12)\n>>> random.randint(0,255), random.randint(0,255), random.randint(0,255)\n(121, 168, 170)\n>>> random.seed(12)\n>>> random.randint(0,255), random.randint(0,25... | [
-1
] | [
"colors",
"python"
] | stackoverflow_0003717354_colors_python.txt |
Q:
Python Twisted framework HTTP client
I want to write a simple SSL HTTP client in Python and have heard about the Twisted framework.
I need to be able to authenticate with a REST service - so I was thinking I'd just POST a user name and password to the target server. Assuming authentication is successful, the clien... | Python Twisted framework HTTP client | I want to write a simple SSL HTTP client in Python and have heard about the Twisted framework.
I need to be able to authenticate with a REST service - so I was thinking I'd just POST a user name and password to the target server. Assuming authentication is successful, the client will receive a cookie.
Will an HTTP clie... | [
"\nWill an HTTP client built on Twisted automatically resend the cookie header for each subsequent request, or do I need to do something special?\n\n\"an HTTP client built on Twisted\" will do anything it is built to do - just like, presumably any X built on any Y will do whatever it was built to do. :) So I might... | [
4
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0003716647_python_twisted_twisted.web.txt |
Q:
Which exception App Engine raises when a task nears the 30 second limit?
From Task Queue Python API Overview:
If your task's execution nears the 30
second limit, App Engine will raise an
exception which you may catch and then
quickly save your work or log process.
Which exception is that?
A:
The exceptio... | Which exception App Engine raises when a task nears the 30 second limit? | From Task Queue Python API Overview:
If your task's execution nears the 30
second limit, App Engine will raise an
exception which you may catch and then
quickly save your work or log process.
Which exception is that?
| [
"The exception is google.appengine.runtime.DeadlineExceededError, the same was with normal web requests. A task running from the queue behaves identically to an ordinary web request, except that the Taskqueue API will reschedule a task that exits with a non-200 response.\n"
] | [
5
] | [] | [] | [
"exception",
"google_app_engine",
"python",
"task",
"task_queue"
] | stackoverflow_0003717466_exception_google_app_engine_python_task_task_queue.txt |
Q:
Google App Engine to Twisted
I was about to migrate the GAE-OpenSocial project to Twisted Matrix and Nevow. I am very new to Nevow templating and couldn't find good documentation other than given in Divmod's Nevow Project page. Is there any books relating to Nevow? I am having trouble serving static files in Nevow... | Google App Engine to Twisted | I was about to migrate the GAE-OpenSocial project to Twisted Matrix and Nevow. I am very new to Nevow templating and couldn't find good documentation other than given in Divmod's Nevow Project page. Is there any books relating to Nevow? I am having trouble serving static files in Nevow. For app engine its easy to defin... | [
"There is a large collection of examples in Nevow's source directory, Nevow/examples/. These are all runnable examples. You can start a server which will serve an index page for them like so:\nexarkun@boson:~/Projects/Divmod/trunk/Nevow/examples$ twistd -ny examples.tac\n... [-] Log opened.\n... [-] twistd 10.1.0... | [
3
] | [] | [] | [
"google_app_engine",
"nevow",
"python",
"templates",
"twisted"
] | stackoverflow_0003715639_google_app_engine_nevow_python_templates_twisted.txt |
Q:
Python installation
i have a machine with two users accounts.
i installed python in the first account without any problem but when am gone to install into the second account it cause the following error
checking for C compiler default output file name... configure: error: C compiler cannot create executables
caus... | Python installation | i have a machine with two users accounts.
i installed python in the first account without any problem but when am gone to install into the second account it cause the following error
checking for C compiler default output file name... configure: error: C compiler cannot create executables
caused when execute the follo... | [
"When you execute ./configure in what folder you are (absolute path) ?\nCheck if this folder and sub-folders are read-writable for your \"second\" user account.\nSeems you have no write access ...\nAnyway, why do you want to install the same python two times ?\n",
"Take a look at the contents of config.log, it li... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003717544_python.txt |
Q:
Is it possible to code images into a python script?
Instead of using directories to reference an image, is it possible to code an image into the program directly?
A:
You can use the base64 module to embed data into your programs. From the base64 documentation:
>>> import base64
>>> encoded = base64.b64encode('... | Is it possible to code images into a python script? | Instead of using directories to reference an image, is it possible to code an image into the program directly?
| [
"You can use the base64 module to embed data into your programs. From the base64 documentation: \n>>> import base64\n>>> encoded = base64.b64encode('data to be encoded')\n>>> encoded\n'ZGF0YSB0byBiZSBlbmNvZGVk' \n>>> data = base64.b64decode(encoded)\n>>> data\n'data to be encoded'\n\nUsing this ability you can base... | [
9,
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003715244_python.txt |
Q:
Selenium-rc: How do you use CaptureNetworkTraffic in python
I've found many tutorials for selenium in java in which you first start selenium using s.start("captureNetworkTraffic=True"), but in python start() does not take any arguments.
How do you pass this argument? Or don't you need it in python?
A:
I changed... | Selenium-rc: How do you use CaptureNetworkTraffic in python | I've found many tutorials for selenium in java in which you first start selenium using s.start("captureNetworkTraffic=True"), but in python start() does not take any arguments.
How do you pass this argument? Or don't you need it in python?
| [
"I changed the start in selenium.py:\ndef start(self, captureNetworkTraffic=False):\n l = [self.browserStartCommand, self.browserURL, self.extensionJs]\n if captureNetworkTraffic:\n l.append(\"captureNetworkTraffic=true\")\n result = self.get_string(\"getNewBrowserSession\", l)\n\nThe you do:\nsel =... | [
5,
1
] | [] | [] | [
"python",
"selenium_rc"
] | stackoverflow_0003712278_python_selenium_rc.txt |
Q:
problem with python print function
I am trying to this function:
def sleep(sec):
for i in range(sec):
print(".", end=" ");
time.sleep(1);
the problem is that it waits for the for loop to finish then it prints everything.
If I use the normal print with \n in the end everything works as it shoul... | problem with python print function | I am trying to this function:
def sleep(sec):
for i in range(sec):
print(".", end=" ");
time.sleep(1);
the problem is that it waits for the for loop to finish then it prints everything.
If I use the normal print with \n in the end everything works as it should. But with the end=" "
it does not.
| [
"The stdout is line buffered. You need to flush the output manually.\nimport sys\n\ndef sleep(sec):\n for i in range(sec):\n print(\".\", end=\" \")\n sys.stdout.flush()\n time.sleep(1)\n\n"
] | [
5
] | [] | [] | [
"printing",
"python",
"python_3.x"
] | stackoverflow_0003718082_printing_python_python_3.x.txt |
Q:
Memory error (MemoryError) when creating a boolean NumPy array (Python)
I'm using NumPy with Python 2.6.2. I'm trying to create a small (length 3), simple boolean array. The following gives me a MemoryError, which I think it ought not to.
import numpy as np
cond = np.fromiter((x in [2] for x in [0, 1, 2]), dtype =... | Memory error (MemoryError) when creating a boolean NumPy array (Python) | I'm using NumPy with Python 2.6.2. I'm trying to create a small (length 3), simple boolean array. The following gives me a MemoryError, which I think it ought not to.
import numpy as np
cond = np.fromiter((x in [2] for x in [0, 1, 2]), dtype = np.bool)
The error it gives me is:
MemoryError: cannot allocate array memor... | [
"You should not get any error.\nWith Python 2.6.5 or Python 2.7, and Numpy 1.5.0, I don't get any error. I therefore think that updating your software could very well solve the problem that you observe.\n",
"I can reproduce the problem with numpy 1.1 (but not with anything newer). Obviously, upgrading to a more... | [
1,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003717418_numpy_python.txt |
Q:
Getting tests to parallelize using nose in python
I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all the .py files and executes them.
I now want to parallelize them s... | Getting tests to parallelize using nose in python | I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all the .py files and executes them.
I now want to parallelize them so that all the tests in all .py files are treated as be... | [
"It seems that nose, actually the multiprocess plugin, will make test run in parallel. The caveat is that the way it works, you can end up not executing test on multiple processes. The plugin creates a test queue, spawns multiple processes and then each process consumes the queue concurrently. There is no test disp... | [
12
] | [] | [] | [
"nose",
"nosetests",
"python"
] | stackoverflow_0003111915_nose_nosetests_python.txt |
Q:
Is there a better/more pythonified way to do this?
I've been teaching myself Python at my new job, and really enjoying the language. I've written a short class to do some basic data manipulation, and I'm pretty confident about it.
But old habits from my structured/modular programming days are hard to break, and I... | Is there a better/more pythonified way to do this? | I've been teaching myself Python at my new job, and really enjoying the language. I've written a short class to do some basic data manipulation, and I'm pretty confident about it.
But old habits from my structured/modular programming days are hard to break, and I know there must be a better way to write this. So, I wa... | [
"Here are my five cents:\n\nConstructor should be called __init__.\nYou could abolish some code by using random.sample, it does what your next() and sublist() does but it's prepackaged.\nOverride __iter__ (define the method in your class) and you can get rid of RandomIter. You can read more about at it in the docs ... | [
6,
5
] | [] | [] | [
"optimization",
"python",
"random",
"string"
] | stackoverflow_0003718284_optimization_python_random_string.txt |
Q:
Multi-panel time series of lines and filled contours using matplotlib?
If I wanted to make a combined image like the one shown below (original source here),
could you point me to the matplotlib objects do I need to assemble? I've been trying to work with AxesImage objects and I've also downloaded SciKits Timeseri... | Multi-panel time series of lines and filled contours using matplotlib? | If I wanted to make a combined image like the one shown below (original source here),
could you point me to the matplotlib objects do I need to assemble? I've been trying to work with AxesImage objects and I've also downloaded SciKits Timeseries - but do I need this, or can is it as easy to use strptime, mktime, and ... | [
"You shouldn't need any custom axes. The Timeseries Scikit is great, but you don't need it at all to work with dates in matplotlib...\nYou'll probably want to use the various functions in matplotlib.dates, plot_date to plot your values, imshow (and/or pcolor in some cases) to plot your specgrams of various sorts, ... | [
11
] | [] | [] | [
"matplotlib",
"python",
"scipy"
] | stackoverflow_0003716528_matplotlib_python_scipy.txt |
Q:
Accessing and manipulating the values ( in list form) of a dictionary
I have a dictionary with keys and a list attached as value to each key.
I have to traverse list value attached to each key and segregate them into two different lists with '0' and '1' ( as '0' and '1' are the values in the list) also with the co... | Accessing and manipulating the values ( in list form) of a dictionary | I have a dictionary with keys and a list attached as value to each key.
I have to traverse list value attached to each key and segregate them into two different lists with '0' and '1' ( as '0' and '1' are the values in the list) also with the count of '0' , '1' and the total. Please let me know how should i go abut doi... | [
"#to loop through a dictionary\ntotal_0 = 0\nlist_0 =[]\ntotal_1 = 0\nlist_1 = []\nsomedict = {'key1':[1,1,1,0,1,0]}\nfor key,value in somedict.items():\n # now loop through each list of your dict, since value keep your list\n for item in value:\n if item == 1: \n total_1 += 1\n l... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003718622_python.txt |
Q:
Python set error reporting level like in PHP
How can I set error reporting and warning outputs in Python like in PHP error_reporting(E_LEVEL)?
A:
A vaguely related option might be the setting of level in the logging module of the Python standard library, and I quote from Python's docs:
import logging
LOG_FILENAM... | Python set error reporting level like in PHP | How can I set error reporting and warning outputs in Python like in PHP error_reporting(E_LEVEL)?
| [
"A vaguely related option might be the setting of level in the logging module of the Python standard library, and I quote from Python's docs:\nimport logging\nLOG_FILENAME = 'example.log'\nlogging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)\n\nlogging.debug('This message should go to the log file')\n\nTh... | [
1
] | [] | [] | [
"php",
"python",
"warnings"
] | stackoverflow_0003718630_php_python_warnings.txt |
Q:
How do I convert this C code into Python?
I am trying to convert this C code I have into a python script so it's readily accessible by more people, but I am having problems understanding this one snippet.
int i, t;
for (i = 0; i < N; i++) {
t = (int)(T*drand48());
z[i] = t;
Nwt[w[i]][t]++;
Ndt[d[i]][t]... | How do I convert this C code into Python? | I am trying to convert this C code I have into a python script so it's readily accessible by more people, but I am having problems understanding this one snippet.
int i, t;
for (i = 0; i < N; i++) {
t = (int)(T*drand48());
z[i] = t;
Nwt[w[i]][t]++;
Ndt[d[i]][t]++;
Nt[t]++;
}
N is a value (sum of one col... | [
"A suggestion for the Python part of things is to use numpy arrays to represent the matrices (and possibly the arrays too). But to be honest, you should not be concerned with that right now. That C-code looks ugly. Apart from that, different languages use different approaches to achieve the same thing. That is what... | [
2,
1,
1,
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003718768_c_python.txt |
Q:
PyQt ListView with groups
How can i create connection groups inside a QListView with PyQt.
The group name should not be selectable.
Example: http://www.shrani.si/f/T/bB/gSpSsYt/connectionlist.jpg :)
A:
There are basically two approaches: add items that are the "section headings" that can be set disabled (see set... | PyQt ListView with groups | How can i create connection groups inside a QListView with PyQt.
The group name should not be selectable.
Example: http://www.shrani.si/f/T/bB/gSpSsYt/connectionlist.jpg :)
| [
"There are basically two approaches: add items that are the \"section headings\" that can be set disabled (see setFlags), or use a QTreeView.\n"
] | [
3
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0003717109_pyqt_python_qt.txt |
Q:
Modifying Python code to use SSL for a REST call
I have Python code to call a REST service that is something like this:
import urllib
import urllib2
username = 'foo'
password = 'bar'
passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
passwordManager .add_password(None, MY_APP_PATH, username, passwo... | Modifying Python code to use SSL for a REST call | I have Python code to call a REST service that is something like this:
import urllib
import urllib2
username = 'foo'
password = 'bar'
passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
passwordManager .add_password(None, MY_APP_PATH, username, password)
authHandler = urllib2.HTTPBasicAuthHandler(passwo... | [
"Unfortunately, urllib2 and httplib, at least up to Python 2.7 don't do any certificate verification for when using HTTPS. The result is that you're exchanging information with a server you haven't necessarily identified (it's a bit like exchanging a secret with someone whose identity you haven't verified): this de... | [
3,
1
] | [] | [] | [
"python",
"rest",
"ssl"
] | stackoverflow_0003704405_python_rest_ssl.txt |
Q:
TypeError uploading image file to Amazon S3 in Django using BOTO Library
I am a total beginner to programming and Django so I'd appreciate help that beginner can get his head round!
I was following a tutorial to show how to upload images to an Amazon S3 account with the Boto library but I think it is for an older ... | TypeError uploading image file to Amazon S3 in Django using BOTO Library | I am a total beginner to programming and Django so I'd appreciate help that beginner can get his head round!
I was following a tutorial to show how to upload images to an Amazon S3 account with the Boto library but I think it is for an older version of Django (I'm on 1.1.2 and Python 2.65) and something has changed. I ... | [
"I think your problem is this line:\ncontent = file['content']\n\nFrom the Django docs:\n\nEach value in FILES is an UploadedFile object containing the following attributes:\n\nread(num_bytes=None) -- Read a number of bytes from the file.\nname -- The name of the uploaded file.\nsize -- The size, in bytes, of the u... | [
7,
0
] | [] | [] | [
"amazon_s3",
"boto",
"django",
"file_upload",
"python"
] | stackoverflow_0003414778_amazon_s3_boto_django_file_upload_python.txt |
Q:
Need to remove duplicates from a list of dictionaries and alter data for the remaining duplicate (python)
Consider this short python list of dictionaries (first dictionary item is a string, second item is a Widget object):
raw_results =
[{'src': 'tag', 'widget': <Widget: to complete a form today>}, # dupe... | Need to remove duplicates from a list of dictionaries and alter data for the remaining duplicate (python) | Consider this short python list of dictionaries (first dictionary item is a string, second item is a Widget object):
raw_results =
[{'src': 'tag', 'widget': <Widget: to complete a form today>}, # dupe 1a
{'src': 'tag', 'widget': <Widget: a newspaper>}, # dupe 2a
{'src': 'zip', 'widge... | [
"def find_widget(widget, L):\n for i, v in enumerate(L):\n if v[widget] == widget:\n return i\n\nknown_widgets= set()\nprocessed_results = []\n\nfor x in raw_results:\n widget = x['widget']\n if widget in known_widgets:\n processed_widgets[find_widget(widget, processed_results)]['src']... | [
2,
1
] | [] | [] | [
"dictionary",
"duplicates",
"list",
"python"
] | stackoverflow_0003704674_dictionary_duplicates_list_python.txt |
Q:
How to search for most recent excel files in remore directories in PYTHON?
This is the code that lists all the subdirectories from FTP server. How do I search for the most recent Excel files sitting in these multiple Subdirectories directory? As shown in the results, I want to go through all the ls**** subdirect... | How to search for most recent excel files in remore directories in PYTHON? | This is the code that lists all the subdirectories from FTP server. How do I search for the most recent Excel files sitting in these multiple Subdirectories directory? As shown in the results, I want to go through all the ls**** subdirectories and notify me if there is an Excel file with today's date.
Thanks in advan... | [
"You're going to want to register a callback function in ftp.retlines like so\ndef callback(line):\n try:\n #only use this code if you'll be dealing with that FTP server alone\n #look into dateutil module which parses dates with more flexibility\n when = datetime.strptime(re.search('[A-z]{3}... | [
1
] | [] | [] | [
"ftp",
"ftplib",
"python"
] | stackoverflow_0003719885_ftp_ftplib_python.txt |
Q:
python: Is there a stronger version of json other than the built in one
I use the built in json for python 2.6. I'm having tons of trouble parsing jsons like this:
{
name: 'some name'
value: 'some value'
}
I found two reasons -
' doesn't work. You need "
the keys of the dictionary need to be strings. I.e "nam... | python: Is there a stronger version of json other than the built in one | I use the built in json for python 2.6. I'm having tons of trouble parsing jsons like this:
{
name: 'some name'
value: 'some value'
}
I found two reasons -
' doesn't work. You need "
the keys of the dictionary need to be strings. I.e "name"/"value"
Am I missing something? Is there a way to parse this kind of dict... | [
"I think that what you want is not a \"stronger\" parser but a broken parser that will parse broken code. See the standard\nspecifically,\n\nThe keys of an object are defined to be strings\nStrings are defined to be \"\" or \"chars\" where chars has the pretty much obvious meaning\n\nThere's someplace on the intern... | [
4,
2,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0003720428_json_python.txt |
Q:
Numpy Modular arithmetic
How can I define in numpy a matrix that uses operations modulo 2?
For example:
0 0 1 0 1 0
1 1 + 0 1 = 1 0
Thanks!
A:
This operation is called "xor".
>>> import numpy
>>> x = numpy.array([[0,0],[1,1]])
>>> y = numpy.array([[1,0],[0,1]])
>>> x ^ y
array([[1, 0],
... | Numpy Modular arithmetic | How can I define in numpy a matrix that uses operations modulo 2?
For example:
0 0 1 0 1 0
1 1 + 0 1 = 1 0
Thanks!
| [
"This operation is called \"xor\".\n>>> import numpy\n>>> x = numpy.array([[0,0],[1,1]])\n>>> y = numpy.array([[1,0],[0,1]])\n>>> x ^ y\narray([[1, 0],\n [1, 0]])\n\nBTW, (element-wise) multiplication modulo 2 can be done with \"and\".\n>>> x & y\narray([[0, 0],\n [0, 1]])\n\n",
"You could subclass nu... | [
9,
2
] | [] | [] | [
"math",
"modular",
"numpy",
"python"
] | stackoverflow_0003719957_math_modular_numpy_python.txt |
Q:
Server Costs for a Computing-Intense Application?
I have a scientific application that I built in Python (the application's 'critical areas' are optimized with Cython, for increased speed).
Every instance of the application is given a text file (with parameters) an an input. The application reads the parameters fr... | Server Costs for a Computing-Intense Application? | I have a scientific application that I built in Python (the application's 'critical areas' are optimized with Cython, for increased speed).
Every instance of the application is given a text file (with parameters) an an input. The application reads the parameters from the text file and, using data that is stored in the ... | [
"You can spin up Amazon EC2 standard instances (1.7GB / 1 slow core) for $0.085 per hour, or 23GB / 8core \"cluster compute\" instances for $1.60 an hour. \n\"One EC2 Compute Unit equals 1.0-1.2 GHz 2007 Xeon processor.\"\nAccording to the tool, 10,000 \"High-CPU Medium\" instances with 5 EC2 Compute Units and 1.7G... | [
1,
0
] | [] | [] | [
"cython",
"python",
"server_hardware",
"ubuntu"
] | stackoverflow_0003720667_cython_python_server_hardware_ubuntu.txt |
Q:
How to plot a figure of my purpose in python?
in python, I would like to use:
from pylab import *
Then use plot provided in this module. However, the curves I plot were not what I want:
Say two lists:
x = [1, 2, 3, 4]
y = [1.4, 5.6, 6, 3.5]
and I am after a plot method that can plot the following chart:
Plot a lin... | How to plot a figure of my purpose in python? | in python, I would like to use:
from pylab import *
Then use plot provided in this module. However, the curves I plot were not what I want:
Say two lists:
x = [1, 2, 3, 4]
y = [1.4, 5.6, 6, 3.5]
and I am after a plot method that can plot the following chart:
Plot a line that joins the points: (1, 0) and (1, 1.4)
Plot a... | [
"Maybe you want just vertical lines? You could use vlines(x, [0], y). See this example\nYou could also have a look at this page (screenshots) to help you select the right function.\n",
"Do you mean a bar chart? If so, just use the bar function:\nbar(x, y)\n\n"
] | [
4,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003720499_matplotlib_python.txt |
Q:
Applying conditions to dictionary key values while traversing through them
The Dictionary is as given below:
goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'Grade':[1,0,0,1,0,1,0,1,0,1]}
I want to code this way that i should get the count of "1" and also "0" in Class when my grade has value "1" and also vice versa i... | Applying conditions to dictionary key values while traversing through them | The Dictionary is as given below:
goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'Grade':[1,0,0,1,0,1,0,1,0,1]}
I want to code this way that i should get the count of "1" and also "0" in Class when my grade has value "1" and also vice versa i.e. when my grade has value "0".
So i will have to traverse through the list val... | [
"This counts the number of cs (classes) which are 1 when g (grades) is 1:\nIn [5]: sum(c for c,g in zip(goodDay['Class'],goodDay['Grade']) if g)\nOut[5]: 4\n\nAnd this gives the number of gs that are 1 when c is 1:\nIn [6]: sum(g for c,g in zip(goodDay['Class'],goodDay['Grade']) if c)\nOut[6]: 4\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003720802_dictionary_python.txt |
Q:
App Engine Bulk Loader Performance
I am using the App Engine Bulk loader (Python Runtime) to bulk upload entities to the data store. The data that i am uploading is stored in a proprietary format, so i have implemented by own connector (registerd it in bulkload_config.py) to convert it to the intermediate python d... | App Engine Bulk Loader Performance | I am using the App Engine Bulk loader (Python Runtime) to bulk upload entities to the data store. The data that i am uploading is stored in a proprietary format, so i have implemented by own connector (registerd it in bulkload_config.py) to convert it to the intermediate python dictionary.
import google.appengine.ext.b... | [
"There is parameter called rps_limit that determines the number of entities to upload per second. This was the major bottleneck. The default value for this is 20. \nAlso increase the bandwidth_limit to something reasonable. \nI increased rps_limit to 500 and everything improved. I achieved 5.5 - 6 seconds per 1000 ... | [
4
] | [] | [] | [
"bulk_load",
"bulkloader",
"google_app_engine",
"performance",
"python"
] | stackoverflow_0003670941_bulk_load_bulkloader_google_app_engine_performance_python.txt |
Q:
win32: moving mouse with SetCursorPos vs. mouse_event
Is there any difference between moving the mouse in windows using the following two techniques?
win32api.SetCursorPos((x,y))
vs:
nx = x*65535/win32api.GetSystemMetrics(0)
ny = y*65535/win32api.GetSystemMetrics(1)
win32api.mouse_event(win32con.MOUSEEVENTF_ABSOL... | win32: moving mouse with SetCursorPos vs. mouse_event | Is there any difference between moving the mouse in windows using the following two techniques?
win32api.SetCursorPos((x,y))
vs:
nx = x*65535/win32api.GetSystemMetrics(0)
ny = y*65535/win32api.GetSystemMetrics(1)
win32api.mouse_event(win32con.MOUSEEVENTF_ABSOLUTE|win32con.MOUSEEVENTF_MOVE,nx,ny)
Does anything happen ... | [
"I believe that mouse_event works by inserting the events into the mouse input stream where as SetCursorPos just moves the cursor around the screen. I don't believe that SetCursorPos generates any input events either (though I may be wrong).\nThe practical implications are that when you use SetCursorPos, it just mo... | [
5
] | [] | [] | [
"automation",
"input",
"python",
"winapi"
] | stackoverflow_0003720938_automation_input_python_winapi.txt |
Q:
Example use of assert in Python?
I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the func... | Example use of assert in Python? | I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python id... | [
"A good guideline is using assert when its triggering means a bug in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with an assert. This assert failing means your assumption isn't correct, which means your code isn't correct.\n",
"tend to use ... | [
23,
16,
3,
3
] | [] | [] | [
"assert",
"exception",
"python"
] | stackoverflow_0003721126_assert_exception_python.txt |
Q:
win32: simulate a click without simulating mouse movement?
I'm trying to simulate a mouse click on a window. I currently have success doing this as follows (I'm using Python, but it should apply to general win32):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
win32api.mouse_e... | win32: simulate a click without simulating mouse movement? | I'm trying to simulate a mouse click on a window. I currently have success doing this as follows (I'm using Python, but it should apply to general win32):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
This works fine. However,... | [
"Try WindowFromPoint() function:\nPOINT pt;\n pt.x = 30; // This is your click coordinates\n pt.y = 30;\n\nHWND hWnd = WindowFromPoint(pt);\nLPARAM lParam = MAKELPARAM(pt.x, pt.y);\nPostMessage(hWnd, WM_RBUTTONDOWN, MK_RBUTTON, lParam);\nPostMessage(hWnd, WM_RBUTTONUP, MK_RBUTTON, lParam);\n\n",
"This doesn... | [
11,
4
] | [] | [] | [
"automation",
"input",
"mouse",
"python",
"winapi"
] | stackoverflow_0003720968_automation_input_mouse_python_winapi.txt |
Q:
How to authenticate the administrator username in Windows
I want to authenticate the administrator username's password.
The administrator username is not a domain account but a local system account.
I am trying to do this in Python, but any code even if it is .NET, VC++ would be fine.
Thanks
A:
You can either L... | How to authenticate the administrator username in Windows | I want to authenticate the administrator username's password.
The administrator username is not a domain account but a local system account.
I am trying to do this in Python, but any code even if it is .NET, VC++ would be fine.
Thanks
| [
"You can either LogonUser (and be sure to CloseHandle after) or call NetUserChangePassword (with old and new passwords the same). Anything in .NET or Python will likely wrap LogonUser.\n"
] | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0003721178_python_windows.txt |
Q:
Python 3.1 image library
So, is there an image processing library for Python 3.x? There is Python Imaging Library (PIL) but the last supported Python version is 2.7 ("A version for 3.X will be released later.")
A:
PyQt provides image processing functionality and is available for Python 3, if you can live with ... | Python 3.1 image library | So, is there an image processing library for Python 3.x? There is Python Imaging Library (PIL) but the last supported Python version is 2.7 ("A version for 3.X will be released later.")
| [
"PyQt provides image processing functionality and is available for Python 3, if you can live with a dependency of that size and with such license restrictions.\n"
] | [
3
] | [] | [] | [
"image",
"image_processing",
"python"
] | stackoverflow_0003721329_image_image_processing_python.txt |
Q:
Readable convention for unpacking single value tuple
There are some related questions about unpacking single-value tuples, but I'd like to know if there is a preferred method in terms of readability for sharing and maintaining code. I'm finding these to be a source of confusion or misreading among colleagues when ... | Readable convention for unpacking single value tuple | There are some related questions about unpacking single-value tuples, but I'd like to know if there is a preferred method in terms of readability for sharing and maintaining code. I'm finding these to be a source of confusion or misreading among colleagues when they involve a long function chain such as an ORM query.
... | [
"How about using explicit parenthesis to indicate that you are unpacking a tuple? \n(value, ) = long().chained().expression().that().returns().tuple()\n\nAfter all explicit is better than implicit. \n"
] | [
22
] | [] | [] | [
"coding_style",
"python",
"tuples"
] | stackoverflow_0003721477_coding_style_python_tuples.txt |
Q:
twisted: how to communicate elegantly between reactor code and threaded code?
I have a client connected to a server using twisted. The client has a thread which might potentially be doing things in the background. When the reactor is shutting down, I have to:
1) check if the thread is doing things
2) stop it if it... | twisted: how to communicate elegantly between reactor code and threaded code? | I have a client connected to a server using twisted. The client has a thread which might potentially be doing things in the background. When the reactor is shutting down, I have to:
1) check if the thread is doing things
2) stop it if it is
What's an elegant way to do this? The best I can do is some confused thing lik... | [
"Ah the real answer is to use the defer.inlineCallbacks decorator. The above code now becomes:\n@defer.inlineCallbacks\ndef procShutdownStuff(self):\n isWorking = yield deferToThread(self.stuff.isWorking)\n\n if isWorking:\n yield deferToThread(self.stuff.shutdown)\n\ndef cleanup(self):\n return sel... | [
6,
5,
0
] | [] | [] | [
"multithreading",
"python",
"shutdown",
"twisted"
] | stackoverflow_0003462698_multithreading_python_shutdown_twisted.txt |
Q:
Easy way of overriding default methods in custom Python classes?
I have a class called Cell:
class Cell:
def __init__(self, value, color, size):
self._value = value
self._color = color
self._size = size
# and other methods...
Cell._value will store a string, integer, etc. (whatev... | Easy way of overriding default methods in custom Python classes? | I have a class called Cell:
class Cell:
def __init__(self, value, color, size):
self._value = value
self._color = color
self._size = size
# and other methods...
Cell._value will store a string, integer, etc. (whatever I am using that object for). I want all default methods that would ... | [
"If I understand you correctly, you're looking for an easy way to delegate an object's method to a property of that object?\nYou can avoid some of the repetitiveness by defining a decorator:\ndef delegate(method, prop):\n def decorate(cls):\n setattr(cls, method,\n lambda self, *args, **kwargs:... | [
13,
0
] | [] | [] | [
"class",
"methods",
"overriding",
"python"
] | stackoverflow_0003720717_class_methods_overriding_python.txt |
Q:
python import problem
although there are many posts on the internet as well as some posts on stack overflow, I still want to ask about this nasty python "import" problem.
OK. so, the open source code organization is usually like this:
project/src/model.py;
project/test/testmodel.py
if I put the famous __init__.py ... | python import problem | although there are many posts on the internet as well as some posts on stack overflow, I still want to ask about this nasty python "import" problem.
OK. so, the open source code organization is usually like this:
project/src/model.py;
project/test/testmodel.py
if I put the famous __init__.py in project directory and al... | [
"You shoud not add the project directory to your pythonpath but it's parent, e.g. imagine the setup\n/home/user/develop/project/src/model\n\nYou'd add /home/user/develop to PYTHONPATH\nIf that still doesn't work, make sure you don't have a 'project.py' insite project/src/model. \n",
"Make sure you have the parent... | [
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003721415_python.txt |
Q:
Selenium issues with IE tests
When I change mt test browser to IE using the following line of code:
self.selenium = selenium("localhost", 4444, "*iexplore", "http://www.mydomain.net/")
I get the following error:
Exception: Failed to start new browser session: java.lang.RuntimeException: SystemRoot apparently not ... | Selenium issues with IE tests | When I change mt test browser to IE using the following line of code:
self.selenium = selenium("localhost", 4444, "*iexplore", "http://www.mydomain.net/")
I get the following error:
Exception: Failed to start new browser session: java.lang.RuntimeException: SystemRoot apparently not set!
It works perfectly fine using... | [
"How could the Selenium RC server (which is what I guess you are using) possibly start an IE instance on an Ubuntu machine?! IIRC all browser instances started by the Selenium RC server have to be local to the server. So if you want to test with IE, you have to run the SRC on a Windows box. Makes sense?!\n"
] | [
6
] | [] | [] | [
"internet_explorer",
"python",
"selenium",
"ubuntu"
] | stackoverflow_0003721451_internet_explorer_python_selenium_ubuntu.txt |
Q:
Parsing unicode attachment names on incoming mail to Google App Engine
I have an app engine app that receives incoming mail with attachments. I check the attachment filename to make sure that the extension is correct. If the filename has umlauts or accented characters in it the encoding makes the filename unreadab... | Parsing unicode attachment names on incoming mail to Google App Engine | I have an app engine app that receives incoming mail with attachments. I check the attachment filename to make sure that the extension is correct. If the filename has umlauts or accented characters in it the encoding makes the filename unreadable to my methods, so I don't know how to check the file type.
For example, i... | [
"That's an RFC2047 encoded-word. You can partially decode it with the email package, although it still needs stitching together afterwards:\nimport email.header\ndef parseHeader(h):\n return ''.join(s.decode(c or 'us-ascii') for s, c in email.header.decode_header(h))\n\n>>> parseHeader('=?ISO-8859-1?B?WnVtQnL8Y2... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003721528_google_app_engine_python.txt |
Q:
customize ticks for AxesImage?
I have created an image plot with ax = imshow(). ax is an AxesImage object, but I can't seem to find the function or attribute I need to acess to customize the tick labels. The ordinary pyplots seem to have set_ticks and set_ticklabels methods, but these do not appear to be available... | customize ticks for AxesImage? | I have created an image plot with ax = imshow(). ax is an AxesImage object, but I can't seem to find the function or attribute I need to acess to customize the tick labels. The ordinary pyplots seem to have set_ticks and set_ticklabels methods, but these do not appear to be available for the AxesImage class. Any ideas?... | [
"For what it's worth, you're slightly misunderstanding what imshow() returns, and how matplotlib axes are structured in general... \nAn AxesImage object is responsible for the image displayed (e.g. colormaps, data, etc), but not the axis that the image resides in. It has no control over things like ticks and tick ... | [
10
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003716339_matplotlib_python.txt |
Q:
What is the ruby equivalent of the python BeautifulSoup library?
I'm looking for a forgiving HTML parser for scraping HTML and extracting data in Ruby. I've had success using BeautifulSoup for this - what is the ruby equivalent?
A:
Nokogiri
Also see:
Nokogiri vs Hpricot before making a choice.
Nokogiri seems to ... | What is the ruby equivalent of the python BeautifulSoup library? | I'm looking for a forgiving HTML parser for scraping HTML and extracting data in Ruby. I've had success using BeautifulSoup for this - what is the ruby equivalent?
| [
"Nokogiri\nAlso see:\nNokogiri vs Hpricot before making a choice.\nNokogiri seems to outdo hpricot performance-wise (haven't benchmarked myself) and has a nice syntax IMO.\n",
"There was a Rubyful Soup gem, which was a Ruby port of BeautifulSoup, but it's no longer maintained and their site now recommends hpricot... | [
6,
0
] | [] | [] | [
"beautifulsoup",
"python",
"ruby"
] | stackoverflow_0003722117_beautifulsoup_python_ruby.txt |
Q:
Strings in Python 3
I am programing VIX API from python 2.5, but now I want to port the code to python 3.2
This function opens the virtual machine:
self.jobHandle = self.VixLib.vix.VixVM_Open(self.hostHandle,
"C:\\MyVirtualMachine.vmx", None, None)
Previusly this functi... | Strings in Python 3 | I am programing VIX API from python 2.5, but now I want to port the code to python 3.2
This function opens the virtual machine:
self.jobHandle = self.VixLib.vix.VixVM_Open(self.hostHandle,
"C:\\MyVirtualMachine.vmx", None, None)
Previusly this function is imported from Vix.d... | [
"Your second argument has to be encoded to a format that the VIX API will understand, since Python 3.x now creates all strings as Unicode. The simplest approach would be to modify your second argument to read:\n\"C:\\\\MyVirtualMachine.vmx\".encode('ascii','ignore')\n\nwhich should give you a variable of type byte... | [
5
] | [] | [] | [
"ctypes",
"python",
"python_3.x",
"string",
"unicode"
] | stackoverflow_0003721995_ctypes_python_python_3.x_string_unicode.txt |
Q:
How do I say "not" using a regex when extracting a group of text?
I am trying to extract a section of text that looks something like this:
Thing 2A blah blah Thing 2A blah blah Thing 3
Where the "3" above could actually be ANY single digit. The code I have that doesn't work is:
((Thing\s2A).+?(Thing\s\d))
Since ... | How do I say "not" using a regex when extracting a group of text? | I am trying to extract a section of text that looks something like this:
Thing 2A blah blah Thing 2A blah blah Thing 3
Where the "3" above could actually be ANY single digit. The code I have that doesn't work is:
((Thing\s2A).+?(Thing\s\d))
Since the 3 could be any single digit, I cannot simply replace the "\d" with ... | [
"Is this what you're trying to do?\n((Thing\\s2A).+?(Thing\\s[0-9]))\nEdit: Oh I get it, you want a digit not followed by an A. Use a forward lookahead\n((Thing\\s2A).+?(Thing\\s[0-9](?!A))\nThat's assuming you want it not followed by an A. Replace the A with whatever you DON'T want to follow the digit\n((Thing\\s2... | [
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003722132_python_regex.txt |
Q:
complete beginner trying to create a flat file database in python
trying to keep it stupidly simple. Is it a bad idea to move a txt file into and out of a python list? the txt files will probably get to about 2-5k entries. what is the preferred method to create a simple flat file databse?
A:
It might or might ... | complete beginner trying to create a flat file database in python | trying to keep it stupidly simple. Is it a bad idea to move a txt file into and out of a python list? the txt files will probably get to about 2-5k entries. what is the preferred method to create a simple flat file databse?
| [
"It might or might not be a bad idea. It depends on what you are trying to achieve, how much memory you have and how big those lines are on average. It also depends on what you are doing with that data. Maybe it is worth it to read and process file line by line? In any case, database assumes indexes, what are you g... | [
3,
0
] | [] | [] | [
"flat_file",
"python"
] | stackoverflow_0003722178_flat_file_python.txt |
Q:
Python ''.format(): "tuple index out of range"?
Consider the following snippet:
>>> def foo(port, out, udp=False, ipv6=False, data=''):
... if not data:
... data = 'foo {family} {:port} {direction}'.format(
... family=('ipv6' if ipv6 else 'ipv4'),
... ... | Python ''.format(): "tuple index out of range"? | Consider the following snippet:
>>> def foo(port, out, udp=False, ipv6=False, data=''):
... if not data:
... data = 'foo {family} {:port} {direction}'.format(
... family=('ipv6' if ipv6 else 'ipv4'),
... port=port,
... d... | [
"Watch the colon. Move it from the front of the port area:\nEither\ndata = 'foo {family} {port:} {direction}'.format(\n\nOr\ndata = 'foo {family} :{port} {direction}'.format(\n\nThe results of the two options are:\n>>> foo(12345, out=True)\n'foo ipv4 12345 out'\n>>> foo(12345, out=True)\n'foo ipv4 :12345 out' \n... | [
2,
0
] | [] | [] | [
"formatting",
"python",
"string"
] | stackoverflow_0003722771_formatting_python_string.txt |
Q:
What is in your Python Interactive Startup Script?
Are there any common timesavers that people put in Python Interactive Startup scripts? I made a dopey one to help me know where I am when I try to do relative file operations or imports, using a win32 module to change the name of the console window.
import sys
im... | What is in your Python Interactive Startup Script? | Are there any common timesavers that people put in Python Interactive Startup scripts? I made a dopey one to help me know where I am when I try to do relative file operations or imports, using a win32 module to change the name of the console window.
import sys
import os
import win32api
__title_prefix = 'Python %i.%i.%... | [
"I also use see, an easier on the eye replacement for Python's dir.\nfrom see import see\n\nAn example of use of see as opposed to dir follows:\n>>> k = {}\n>>> dir(k)\n['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__','__doc__',\n'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem_... | [
5,
4,
1
] | [] | [] | [
"interactive",
"python",
"startup"
] | stackoverflow_0003613418_interactive_python_startup.txt |
Q:
What is the escape character for % in python's string method
I am trying to pass a string which has a '%' in it (its actually a sql query string). How do I pass the % (do I have to use a specific escape character?
eg:
compute_answertime("%how do I%")
A:
Use another % to escape it
>>> compute_answertime("%%how do... | What is the escape character for % in python's string method | I am trying to pass a string which has a '%' in it (its actually a sql query string). How do I pass the % (do I have to use a specific escape character?
eg:
compute_answertime("%how do I%")
| [
"Use another % to escape it\n>>> compute_answertime(\"%%how do I%%\")\n\n",
"use %%..........\n",
"You can use:\n%%; DROP TABLE Students; --\n\nSorry, couldn't resist.\n"
] | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003718322_python.txt |
Q:
Pre declared dictionary size limit?
I have a big dictionary i constantly reference in my code so i have it initialized at the top:
import ...
myDictionary = {'a':'avalue','b':'bvalue',...}
code ...
But when i try to get values, some of the keys are not found. It appears as though Python is chopping my dictiona... | Pre declared dictionary size limit? | I have a big dictionary i constantly reference in my code so i have it initialized at the top:
import ...
myDictionary = {'a':'avalue','b':'bvalue',...}
code ...
But when i try to get values, some of the keys are not found. It appears as though Python is chopping my dictionary due to a size limit. I tried searchin... | [
"One thing you might want to look for is that the keys in your dictionary are not duplicates. For example, in the following code:\n>>> d = {'1': 'hello', '2': 'world', '1': 'new'}\n>>> d\n{'1': 'new', '2': 'world'}\n>>> \n\nbecause I used the key '1' twice, only the last one appeared and thus I was left with a dict... | [
4,
2
] | [] | [] | [
"dictionary",
"limit",
"predefined_variables",
"python",
"size"
] | stackoverflow_0003722527_dictionary_limit_predefined_variables_python_size.txt |
Q:
Python char encoding
I have the following code :
msgtxt = "é"
msg = MIMEText(msgtxt)
msg.set_charset('ISO-8859-1')
msg['Subject'] = "subject"
msg['From'] = "from@mail.com"
msg['To'] = "to@mail.com"
serv.sendmail("from@mail.com","to@mail.com", msg.as_string())
The e-mail arrive with é as its body instead of the ... | Python char encoding | I have the following code :
msgtxt = "é"
msg = MIMEText(msgtxt)
msg.set_charset('ISO-8859-1')
msg['Subject'] = "subject"
msg['From'] = "from@mail.com"
msg['To'] = "to@mail.com"
serv.sendmail("from@mail.com","to@mail.com", msg.as_string())
The e-mail arrive with é as its body instead of the expected é
I have tried :
... | [
"msgtxt = \"é\"\nmsg.set_charset('ISO-8859-1')\n\nWell, what's the encoding of the source file containing this code? If it's UTF-8, which is a good default choice, just writing the é will have given you the two-byte string '\\xc3\\xa9', which, when viewed as ISO-8859-1, looks like é.\nIf you want to use non-ASCII ... | [
1,
0
] | [] | [] | [
"encoding",
"python",
"smtplib"
] | stackoverflow_0003722075_encoding_python_smtplib.txt |
Q:
Is it safe to replace MacOS X default Python interpreter?
I have the default Python 2.6.1 installed as /usr/bin/python and Python 3.1.2 installed in /usr/local/bin/python3.1. Considering that I use only 3.x syntax, is it safe to replace the default interpreter (2.6) with the 3.1 one (python-config included) using ... | Is it safe to replace MacOS X default Python interpreter? | I have the default Python 2.6.1 installed as /usr/bin/python and Python 3.1.2 installed in /usr/local/bin/python3.1. Considering that I use only 3.x syntax, is it safe to replace the default interpreter (2.6) with the 3.1 one (python-config included) using symlinks (and removing old Python binary)? Or is the system rel... | [
"If you're only using Python 3, start your scripts with:\n#! /usr/bin/env python3.1\n\nAnd you'll be using the right version, without doinking the system about.\nedit: BTW this idea is suggested by the Python docs. Each script will be running the version of Python they depend on. Since Python 3 is not backward comp... | [
8,
2,
1
] | [] | [] | [
"macos",
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0003723183_macos_python_python_2.x_python_3.x.txt |
Q:
Python: compiling regexp problems
I have a interesting problem. I have a list of lists, and I want all except the first element of each list compiled into a regular expression. And then put back into the list. The lists start as strings.
The following code doesn't work. It doesn't raise an error, it just doesn't s... | Python: compiling regexp problems | I have a interesting problem. I have a list of lists, and I want all except the first element of each list compiled into a regular expression. And then put back into the list. The lists start as strings.
The following code doesn't work. It doesn't raise an error, it just doesn't seem to do anything. I think I have iden... | [
"#!/usr/bin/env python\n\nimport re\n\nlol = [\n [\"unix\", \".*\", \"cool(, eh)?\"],\n [\"windows\", \"_*.*\", \"[wft]*\"],\n]\n\n# think of `il` as inner list and `ii` as inner item (if you need) ...\nprint [ ii[:1] + map(re.compile, ii[1:]) for ii in [ il for il in lol ]]\n\n# ... or, since list comprehens... | [
2,
1,
0
] | [] | [] | [
"list",
"python",
"regex"
] | stackoverflow_0003723251_list_python_regex.txt |
Q:
Operating on a file's content despite a failure in the 'with' block
I've just written a utility in Python to do something I need (irrelevant, but it's to generate a ctags-compatible tag file for an in-house DSL).
Anyway- I'm opening and reading the file in the context of a with statement, and I'm curious, how do p... | Operating on a file's content despite a failure in the 'with' block | I've just written a utility in Python to do something I need (irrelevant, but it's to generate a ctags-compatible tag file for an in-house DSL).
Anyway- I'm opening and reading the file in the context of a with statement, and I'm curious, how do people tend to handle failures in that process?
My solution is
with open(f... | [
"What I would do is as you said:\ncontent = ''\nwith open(filename, 'rt') as f:\n content = f.read()\n\nmatches = re.findall(REGEX, content)\n\nas the cost for regexing and checking matches would be negligable for an empty string.\nHowever, closing the file immediately isn't that important as long as it is close... | [
1
] | [] | [] | [
"python",
"with_statement"
] | stackoverflow_0003723212_python_with_statement.txt |
Q:
Form from Model with File Upload
I'm trying to mimic the admin interface for the Photologue app on the front end. To achieve this, I have thus far created a bit of code in the view:
def galleryuploader(request):
GalleryFormSet = modelformset_factory(GalleryUpload)
if request.method == 'POST':
f... | Form from Model with File Upload | I'm trying to mimic the admin interface for the Photologue app on the front end. To achieve this, I have thus far created a bit of code in the view:
def galleryuploader(request):
GalleryFormSet = modelformset_factory(GalleryUpload)
if request.method == 'POST':
formset = GalleryFormSet(request.POST, ... | [
"Add the enctype=\"multipart/form-data\" attribute to your form tag. Also you'll need to actually do something with the uploaded files. Here's the example from the django docs:\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\n\n# Imaginary function to handle an uploa... | [
3
] | [] | [] | [
"django",
"django_forms",
"forms",
"python",
"webforms"
] | stackoverflow_0003723293_django_django_forms_forms_python_webforms.txt |
Q:
Executing py2exe fails with can't open file 'setup.py'
I'm using py2exe and I get the following errors in command prompt.
C:\Users\Me>C:\Python26\My_scripts\python.exe setup.py py2exe
C:\Python26\My_scripts\python.exe: can't open file 'setup.py': [Errno 2] No such
file or directory
What am I doing wrong... | Executing py2exe fails with can't open file 'setup.py' | I'm using py2exe and I get the following errors in command prompt.
C:\Users\Me>C:\Python26\My_scripts\python.exe setup.py py2exe
C:\Python26\My_scripts\python.exe: can't open file 'setup.py': [Errno 2] No such
file or directory
What am I doing wrong?
| [
"Since your comment confirmed what I expected, I'll follow up with an answer post.\nYou invoked python from the directory you were in when you called the executable. In this case, according to your prompt, you invoked it from C:\\Users\\Me. Therefore, python is trying to find setup.py under this directory (which do... | [
3,
1
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0003723026_py2exe_python.txt |
Q:
list(y) behavior is "wrong" on first call
I have an iterator with a __len__ method defined. Questions:
If you call list(y) and y has a __len__ method defined, then __len__ is called.
1) Why?
In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see t... | list(y) behavior is "wrong" on first call | I have an iterator with a __len__ method defined. Questions:
If you call list(y) and y has a __len__ method defined, then __len__ is called.
1) Why?
In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see that on the first call, I receive an empty list,... | [
"\nIf you call list(y) and y has a\n len method defined, then len is called. why?\n\nBecause it's faster to build the resulting list with the final length, if known from the start, than to begin with an empty list and append one item at a time. And __len__ is, and must be, 100% guaranteed to be reliable.\nIOW, d... | [
6
] | [] | [] | [
"iterator",
"list",
"python"
] | stackoverflow_0003723337_iterator_list_python.txt |
Q:
why i can't get the data form Model.all() using google app engine
this is my code in main.py
class marker_data(db.Model):
geo_pt = db.GeoPtProperty()
class HomePage(BaseRequestHandler):
def get(self):
a=marker_data()
a.geo_pt=db.GeoPt(-34.397, 150.644)
a.put()
datas=marker_d... | why i can't get the data form Model.all() using google app engine | this is my code in main.py
class marker_data(db.Model):
geo_pt = db.GeoPtProperty()
class HomePage(BaseRequestHandler):
def get(self):
a=marker_data()
a.geo_pt=db.GeoPt(-34.397, 150.644)
a.put()
datas=marker_data.all()
self.render_template('3.1.html',{'datas':datas})
and... | [
"The 'i' is interpreted by the templating engine on the server side, so you need:\n{% for i in datas %}\n console.log({{ i }});\n{% endfor %}\n\n",
"In addition to the syntax error sje397 mentioned, the .all() method returns a Query object and I think you'll need to call .fetch(n) or .get() on that to retrieve... | [
4,
0
] | [] | [] | [
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0003723521_google_app_engine_javascript_python.txt |
Q:
C data structures
Is there a C data structure equatable to the following python structure?
data = {'X': 1, 'Y': 2}
Basically I want a structure where I can give it an pre-defined string and have it come out with an integer.
A:
The data-structure you are looking for is called a "hash table" (or "hash map"). Y... | C data structures | Is there a C data structure equatable to the following python structure?
data = {'X': 1, 'Y': 2}
Basically I want a structure where I can give it an pre-defined string and have it come out with an integer.
| [
"The data-structure you are looking for is called a \"hash table\" (or \"hash map\"). You can find the source code for one here.\nA hash table is a mutable mapping of an integer (usually derived from a string) to another value, just like the dict from Python, which your sample code instantiates.\nIt's called a \"ha... | [
7,
3,
2,
2,
1,
1,
1
] | [] | [] | [
"c",
"data_structures",
"dictionary",
"hashtable",
"python"
] | stackoverflow_0003723314_c_data_structures_dictionary_hashtable_python.txt |
Q:
Upload files without FieldStorage
How could i upload a file to a server without using FieldStorage in python?
A:
Here is a toy program snippet that should help get you started. Try reading RFC 1867 as well for more guidance.
#!/usr/bin/python
import os
import sys
buf = sys.stdin.read(512)
print "Content-type... | Upload files without FieldStorage | How could i upload a file to a server without using FieldStorage in python?
| [
"Here is a toy program snippet that should help get you started. Try reading RFC 1867 as well for more guidance.\n\n#!/usr/bin/python\n\nimport os\nimport sys\n\nbuf = sys.stdin.read(512)\n\nprint \"Content-type: text/html\\n\\n\";\nprint '<html>'\nprint '''\n<form method=\"post\" action=\"\" enctype=\"multipart/fo... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003671981_python_python_3.x.txt |
Q:
python: timing of __new__ in metaclass
The following code doesn't compile; it says
NameError: name 'fields' is not
defined
in the last line. Is it because __new__ isn't called until after the fields assignment is reached? What should I do?
class Meta(type):
def __new__(mcs, name, bases, attr):
attr... | python: timing of __new__ in metaclass | The following code doesn't compile; it says
NameError: name 'fields' is not
defined
in the last line. Is it because __new__ isn't called until after the fields assignment is reached? What should I do?
class Meta(type):
def __new__(mcs, name, bases, attr):
attr['fields'] = {}
return type.__new__(... | [
"The fields['key'] = 'value' runs before the metaclass machinery kicks in.\nclass foo(object):\n var1 = 'bar'\n\n def foobar(self):\n pass\n\nwhen python hits the class statement, it enters a new local namespace.\n\nit evaluates the var1 = 'bar' statement. this is equivalent to locals()['var1'] = 'bar'... | [
4
] | [] | [] | [
"metaclass",
"namespaces",
"python"
] | stackoverflow_0003723979_metaclass_namespaces_python.txt |
Q:
Storing and retrieving a list of Tuples using ConfigParser
I would like store some configuration data in a config file. Here's a sample section:
[URLs]
Google, www.google.com
Hotmail, www.hotmail.com
Yahoo, www.yahoo.com
Is it possible to read this into a list of tuples using the ConfigParser module? If not, what... | Storing and retrieving a list of Tuples using ConfigParser | I would like store some configuration data in a config file. Here's a sample section:
[URLs]
Google, www.google.com
Hotmail, www.hotmail.com
Yahoo, www.yahoo.com
Is it possible to read this into a list of tuples using the ConfigParser module? If not, what do I use?
| [
"Can you change the separator from comma (,) to a semicolon (:) or use the equals (=) sign? In that case ConfigParser will automatically do it for you. \nFor e.g. I parsed your sample data after changing the comma to equals:\n# urls.cfg\n[URLs]\nGoogle=www.google.com\nHotmail=www.hotmail.com\nYahoo=www.yahoo.com\n\... | [
11,
3
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0003724107_configparser_python.txt |
Q:
Python subprocess how to determine if child process hangs?
How do I know is there my child process got hang while operating?
A:
Well, how do you tell the difference between a stuck process and a process that takes longer than usual to complete? The short answer is: No, you can't detect if your child process is s... | Python subprocess how to determine if child process hangs? | How do I know is there my child process got hang while operating?
| [
"Well, how do you tell the difference between a stuck process and a process that takes longer than usual to complete? The short answer is: No, you can't detect if your child process is stuck.\nI would say that to be able to detect this you need some kind of continuous communication with the process (e.g. look at lo... | [
2,
1
] | [] | [] | [
"parent_child",
"process",
"python",
"subprocess"
] | stackoverflow_0003724238_parent_child_process_python_subprocess.txt |
Q:
Django model form with selected rows
I have a django model roughly as shown below:
class Event(db.Model):
creator = db.ReferenceProperty(User, required= True)
title = db.TextProperty(required = True)
description = db.TextProperty(required = True)
class Ticket(db.Model):
user = db.ReferenceProperty(Us... | Django model form with selected rows | I have a django model roughly as shown below:
class Event(db.Model):
creator = db.ReferenceProperty(User, required= True)
title = db.TextProperty(required = True)
description = db.TextProperty(required = True)
class Ticket(db.Model):
user = db.ReferenceProperty(User, required = True)
event = db.Referen... | [
"This is how I'd go about it if this were a pure Django application (rather than app engine). You may perhaps find it useful.\nThe key is to override the __init__() method of your ModelForm class to supply the currently logged in user instance.\n# forms.py\nclass TicketForm(forms.ModelForm):\n def __init__(self,... | [
1
] | [] | [] | [
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0003724488_django_forms_google_app_engine_python.txt |
Q:
Efficient way to store dictionary (hash) in file with python?
I'm implementing a Unix userland tool that needs to store a hash on the disk. The hash will be read every run of the program, pretty frequently. The hash needs to store "name:path" values only.
I looked at the bsddb standard library module for python, b... | Efficient way to store dictionary (hash) in file with python? | I'm implementing a Unix userland tool that needs to store a hash on the disk. The hash will be read every run of the program, pretty frequently. The hash needs to store "name:path" values only.
I looked at the bsddb standard library module for python, but I can see it will be deprecated in Python 3. I also saw the pick... | [
"I would start with the shelve module and see if that isn't too slow. It does exactly what you want.\nimport shelve\n\nd = shelve.open('filename')\n\nd['name'] = 'path'\n\nd.close()\n\nor to read from it\nd = shelve.open('filename')\n\nd = hash['name']\n\nIt's essentially a wrapper around pickle that provides a dic... | [
5,
0,
0
] | [] | [] | [
"dictionary",
"file",
"python",
"serialization"
] | stackoverflow_0003724540_dictionary_file_python_serialization.txt |
Q:
Cross platform solution for getting current login name in Python
I'm looking for a cross platform solution for getting current login/username in Python.
I was surprised that os.getlogin() is only supported under Unix and even there is not necessarily returning what you would expect.
A:
getpass.getuser() is your ... | Cross platform solution for getting current login name in Python | I'm looking for a cross platform solution for getting current login/username in Python.
I was surprised that os.getlogin() is only supported under Unix and even there is not necessarily returning what you would expect.
| [
"getpass.getuser() is your friend.\n",
"Here is what I use:\nimport os\nusername = getattr(os, \"getlogin\", None)\nif not username:\n for var in ['USER', 'USERNAME','LOGNAME']:\n if var in os.environ:\n username = os.environ[var]\nprint(\"username: %s\" % (username))\n\n"
] | [
11,
1
] | [] | [] | [
"authentication",
"python"
] | stackoverflow_0003724634_authentication_python.txt |
Q:
Python ssl problem with multiprocessing
I want to send data from a client to the server in a TLS TCP socket from multiple client subprocesses so I share the same ssl socket with all subprocesses. Communication works with one subprocess, but if I use more than one subprocesses, the TLS server crashes with an ssl.SS... | Python ssl problem with multiprocessing | I want to send data from a client to the server in a TLS TCP socket from multiple client subprocesses so I share the same ssl socket with all subprocesses. Communication works with one subprocess, but if I use more than one subprocesses, the TLS server crashes with an ssl.SSLError (SSL3_GET_RECORD:decryption failed or ... | [
"The problem is that you're re-using the same connection for both processes. The way SSL encrypts data makes this fail -- the two processes would have to communicate with each other about the state of the shared SSL connection. Even if you do make it work, or if you didn't use SSL, the data would arrive at the serv... | [
35
] | [] | [] | [
"multiprocessing",
"python",
"ssl"
] | stackoverflow_0003724900_multiprocessing_python_ssl.txt |
Q:
Why aren't persistent connections supported by URLLib2?
After scanning the urllib2 source, it seems that connections are automatically closed even if you do specify keep-alive.
Why is this?
As it is now I just use httplib for my persistent connections... but wonder why this is disabled (or maybe just ambiguous) i... | Why aren't persistent connections supported by URLLib2? | After scanning the urllib2 source, it seems that connections are automatically closed even if you do specify keep-alive.
Why is this?
As it is now I just use httplib for my persistent connections... but wonder why this is disabled (or maybe just ambiguous) in urllib2.
| [
"It's a well-known limit of urllib2 (and urllib as well). IMHO the best attempt so far to fix it and make it right is Garry Bodsworth's coda_network for Python 2.6 or 2.7 -- replacement, patched versions of urllib2 (and some other modules) to support keep-alive (and a bunch of other smaller but quite welcome fixes... | [
7,
3
] | [] | [] | [
"keep_alive",
"python",
"urllib2"
] | stackoverflow_0003722577_keep_alive_python_urllib2.txt |
Q:
Python ctypes, C++ object destruction
Consider the following python ctypes - c++ binding:
// C++
class A
{
public:
void someFunc();
};
A* A_new() { return new A(); }
void A_someFunc(A* obj) { obj->someFunc(); }
void A_destruct(A* obj) { delete obj; }
# python
from ctypes import cdll
libA = cdll.LoadLibrary(... | Python ctypes, C++ object destruction | Consider the following python ctypes - c++ binding:
// C++
class A
{
public:
void someFunc();
};
A* A_new() { return new A(); }
void A_someFunc(A* obj) { obj->someFunc(); }
void A_destruct(A* obj) { delete obj; }
# python
from ctypes import cdll
libA = cdll.LoadLibrary(some_path)
class A:
def __init__(self)... | [
"You could implement the __del__ method, which calls a destructor function you would have to define:\nC++\nclass A\n{\npublic:\n void someFunc();\n};\n\nA* A_new() { return new A(); }\nvoid delete_A(A* obj) { delete obj; }\nvoid A_someFunc(A* obj) { obj->someFunc(); }\n\nPython\nfrom ctypes import cdll\n\nlibA =... | [
10,
2,
2
] | [] | [] | [
"c++",
"ctypes",
"python"
] | stackoverflow_0003724987_c++_ctypes_python.txt |
Q:
Python package/module lazily loading submodules
Interesting usecase today: I need to migrate a module in our codebase following code changes. The old mynamespace.Document will disappear and I want to ensure smooth migration by replacing this package by a code object that will dynamically import the correct path an... | Python package/module lazily loading submodules | Interesting usecase today: I need to migrate a module in our codebase following code changes. The old mynamespace.Document will disappear and I want to ensure smooth migration by replacing this package by a code object that will dynamically import the correct path and migrate the corresponding objects.
In short:
# inst... | [
"The problem is that python will bypass the entry in for document in sys.modules and load the file for submodule directly. Of course this doesn't exist.\ndemonstration:\n>>> import multiprocessing\n>>> multiprocessing.heap = None\n>>> import multiprocessing.heap\n>>> multiprocessing.heap\n<module 'multiprocessing.h... | [
4
] | [] | [] | [
"dynamic",
"import",
"python"
] | stackoverflow_0003725262_dynamic_import_python.txt |
Q:
Python String split with multiple regex
Hi I have Python String as shown below:
<html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html>
From above string I am interested in two words
JDICOM
Thu Sep 16 10:13:34 CDT 2010
I tried find, findall, split but it did not help because ... | Python String split with multiple regex | Hi I have Python String as shown below:
<html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html>
From above string I am interested in two words
JDICOM
Thu Sep 16 10:13:34 CDT 2010
I tried find, findall, split but it did not help because of multiple regex.
I am quite new to python.... | [
"Statutory Warning: don't use regular expressions to parse (X)HTML. You are much better off using a parser such as BeautifulSoup. \nFor e.g. \n>>> from BeautifulSoup import BeautifulSoup\n>>> html = \"\"\"<html><table border = 1><tr><td>JDICOM</td><td>Thu Sep 16 10:13:34 CDT 2010</td></tr></html>\"\"\"\n>>> soup = ... | [
4
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0003725677_html_python_regex.txt |
Q:
SCons configuration file and default values
I have a project which I build using SCons (and MinGW/gcc depending on the platform). This project depends on several other libraries (lets call them libfoo and libbar) which can be installed on different places for different users.
Currently, my SConstruct file embeds h... | SCons configuration file and default values | I have a project which I build using SCons (and MinGW/gcc depending on the platform). This project depends on several other libraries (lets call them libfoo and libbar) which can be installed on different places for different users.
Currently, my SConstruct file embeds hard-coded path to those libraries (say, something... | [
"SCons has a feature called \"Variables\". You can set it up so that it reads from command line argument variables pretty easily. So in your case you would do something like this from the command line:\nscons LIBFOO=C:\\custom_path\\libfoo\n\n... and the variable would be remembered between runs. So next time you j... | [
6
] | [] | [] | [
"configuration",
"python",
"scons"
] | stackoverflow_0003725205_configuration_python_scons.txt |
Q:
regular expression help which includes "." in word separation
expr = "name + partner_id.country_id.name + city + ' ' + 123 + '123' + 12*2/58%45"
print re.findall('\w+[.]',expr)
['name',
'partner_id',
'country_id',
'name',
'city',
'123',
'123',
'12',
'2',
'58',
'45']
I want to include "." so result sho... | regular expression help which includes "." in word separation | expr = "name + partner_id.country_id.name + city + ' ' + 123 + '123' + 12*2/58%45"
print re.findall('\w+[.]',expr)
['name',
'partner_id',
'country_id',
'name',
'city',
'123',
'123',
'12',
'2',
'58',
'45']
I want to include "." so result should be like
['name',
'partner_id.country_id.name',
'city',
'123... | [
"Try the regex:\n[\\w.]+\n\nExplanation:\n\n[...] is the char class\n\\w is a char of a word, short for\n[a-zA-Z0-9_]\n. is generally a meta char to match\nany char but inside a char class its\ntreated as a literal .\n+ for one or more\n\n",
"Try this:\nre.findall('[\\w.]+',expr)\n\nThis finds blocks of character... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003725782_python_regex.txt |
Q:
Ruby's tap idiom in Python
There is a useful Ruby idiom that uses tap which allows you to create an object, do some operations on it and return it (I use a list here only as an example, my real code is more involved):
def foo
[].tap do |a|
b = 1 + 2
# ... and some more processing, maybe some logging, etc... | Ruby's tap idiom in Python | There is a useful Ruby idiom that uses tap which allows you to create an object, do some operations on it and return it (I use a list here only as an example, my real code is more involved):
def foo
[].tap do |a|
b = 1 + 2
# ... and some more processing, maybe some logging, etc.
a << b
end
end
>> foo
=... | [
"Short answer: Ruby encourages method chaining, Python doesn't.\nI guess the right question is: What is Ruby's tap useful for?\nNow I don't know a lot about Ruby, but by googling I got the impression that tap is conceptually useful as method chaining.\nIn Ruby, the style: SomeObject.doThis().doThat().andAnotherThin... | [
27,
8,
7,
1
] | [
"I partly agree with others in that it doesn't make much sense to implement this in Python. However, IMHO, Mark Byers's way is the way, but why lambdas(and all that comes with them)? can't you write a separate function to be called when needed?\nAnother way to do basically the same could be \nmap(afunction(), avari... | [
-1,
-1
] | [
"idioms",
"python",
"ruby"
] | stackoverflow_0003725214_idioms_python_ruby.txt |
Q:
How do I use a Django custom template tag in a template?
I’ve written a custom template tag:
def mytag(para):
return something
In my template I am getting a value {{value}}. Now I am using {{value|mytag}} to apply the tag to the value, and it is throwing a syntax error.
A:
Your example looks like a filter. ... | How do I use a Django custom template tag in a template? | I’ve written a custom template tag:
def mytag(para):
return something
In my template I am getting a value {{value}}. Now I am using {{value|mytag}} to apply the tag to the value, and it is throwing a syntax error.
| [
"Your example looks like a filter. If that's all you want, it's fairly simple. Paul's links to the documentation should provide a fairly clear explanation of how and why to do things. Here's a quick start that should get you up and running though.\n\nCreate a folder in your app called \"templatetags\" with an empty... | [
5,
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003726000_django_django_templates_python.txt |
Q:
What's the recommended way to return a boolean for a collection being non-empty in python?
I came across the question Python: What is the best way to check if a list is empty? on SO.
Now if I wanted to return a True (False) depending on whether a collection coll is non-empty (empty) from a function, what's the re... | What's the recommended way to return a boolean for a collection being non-empty in python? | I came across the question Python: What is the best way to check if a list is empty? on SO.
Now if I wanted to return a True (False) depending on whether a collection coll is non-empty (empty) from a function, what's the recommended way of doing this ? return not not coll ?
| [
"You could use\nreturn bool(coll)\n\n"
] | [
11
] | [] | [] | [
"collections",
"python"
] | stackoverflow_0003726692_collections_python.txt |
Q:
Django: What is `sys.path` supposed to be?
When developing a Django application, what is sys.path supposed to contain? The directory which contains the project, or the directory of the project, or both?
A:
sys.path should and will have the directory of the project. Depending on what your setup is, it may also co... | Django: What is `sys.path` supposed to be? | When developing a Django application, what is sys.path supposed to contain? The directory which contains the project, or the directory of the project, or both?
| [
"sys.path should and will have the directory of the project. Depending on what your setup is, it may also contain the directory which contains the project. \nHowever, if the motivation behind this question is to ensure that certain files can be found, then you should note that sys.path is just like a normal list an... | [
3,
0
] | [] | [] | [
"django",
"python",
"pythonpath"
] | stackoverflow_0003726705_django_python_pythonpath.txt |
Q:
Using QWebPage via socks
I'm confused a bit on usage of QWebPage via socks using httplib2 (http/socks5/socks4).
Is there any issues or workaround on it?
A:
Problem seem to be solved using QNetworkAccessManager
QNetworkAccessManager.proxyAuthenticationRequired(proxy, authenticator)
proxy – QNetworkProxy
authent... | Using QWebPage via socks | I'm confused a bit on usage of QWebPage via socks using httplib2 (http/socks5/socks4).
Is there any issues or workaround on it?
| [
"Problem seem to be solved using QNetworkAccessManager \nQNetworkAccessManager.proxyAuthenticationRequired(proxy, authenticator)\n\nproxy – QNetworkProxy\nauthenticator – QAuthenticator\n\n"
] | [
0
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0003108941_pyqt4_python.txt |
Q:
How to call an executable as independent process using python in windows
After calling an exe using python script in windows, the exe should run independent of this python script and once it is initiated the control should comeback to python script and executes the further script and control of .py file will die. ... | How to call an executable as independent process using python in windows | After calling an exe using python script in windows, the exe should run independent of this python script and once it is initiated the control should comeback to python script and executes the further script and control of .py file will die. But on other side before finishing execution, the exe should call this python ... | [
"I sounds as if you want the callee to callback the caller (sorry for the alliteration :) Since you are using Python 3.1 maybe the subprocess module will provide the intended behavior. It is not a true callback per se, but the calling program can perform decisions based on the output of the called program (exe in t... | [
1
] | [] | [] | [
"python",
"python_3.x",
"windows"
] | stackoverflow_0003725859_python_python_3.x_windows.txt |
Q:
Getting started with Django-Instant Django
I've been trying to get Django running and when going through the intro to projects it seems that I keep having trouble when I get to the 'sync database' section. When using InstantDjango this doesn't seem to be as much of a problem. My question is, can one just do Djang... | Getting started with Django-Instant Django | I've been trying to get Django running and when going through the intro to projects it seems that I keep having trouble when I get to the 'sync database' section. When using InstantDjango this doesn't seem to be as much of a problem. My question is, can one just do Django development with the InstantDjango program or ... | [
"InstantDjango uses sqlite by default. What database did you set your normal django to use? and you did you create that database before you ran the syncdb?\nInstantDjango uses different packaging for all the django required libraries (portable versions) which might be less stable but they should work for your devel... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000738433_django_python.txt |
Q:
Get Active Directory group members using PyWin32
I need to list all Active Directory group's members - can I do this without using LDAP queries with PyWin's win32security, for instance?
I can lookup accounts' sids and names using it (LookupAccountSid and LookupAccountName), but how about getting all group member... | Get Active Directory group members using PyWin32 | I need to list all Active Directory group's members - can I do this without using LDAP queries with PyWin's win32security, for instance?
I can lookup accounts' sids and names using it (LookupAccountSid and LookupAccountName), but how about getting all group members? For now I cannot figure out what functions I should... | [
"This active directory module wraps an interface around win32com.client.\n\nactive_directory - a lightweight\n wrapper around COM support for\n Microsoft's Active Directory\nActive Directory is Microsoft's answer\n to LDAP, the industry-standard \n directory service holding information\n about users, computer... | [
3
] | [] | [] | [
"python",
"pywin32"
] | stackoverflow_0003726811_python_pywin32.txt |
Q:
Why isn't posting a status update to Facebook working?
I had a working Python integration to Facebook, using the Graph API and the https://graph.facebook.com/<<id>>/feed URL, for about a month.
And then all of a sudden a few days ago, I started getting this back whenever I tried to post a status update:
{"error":{... | Why isn't posting a status update to Facebook working? | I had a working Python integration to Facebook, using the Graph API and the https://graph.facebook.com/<<id>>/feed URL, for about a month.
And then all of a sudden a few days ago, I started getting this back whenever I tried to post a status update:
{"error":{"type":"OAuthException","message":"(#200) The user hasn't au... | [
"So I now have my app working again. I ended up using the JavaScript API from Facebook, using that to login the user, set the cookie, and then I use the Python SDK from Facebook to make the actual status update. It works.\nHow this is different from what I was doing (my own Python code for doing the same stuff) i... | [
0
] | [] | [] | [
"facebook",
"oauth",
"python"
] | stackoverflow_0003712207_facebook_oauth_python.txt |
Q:
specify dtype of each object in a python numpy array
This is a similar question using dtypes in a list
The following snippet creates a "typical test array", the purpose of this array is to test an assortment of things in my program. Is there a way or is it even possible to change the type of elements in an array?... | specify dtype of each object in a python numpy array |
This is a similar question using dtypes in a list
The following snippet creates a "typical test array", the purpose of this array is to test an assortment of things in my program. Is there a way or is it even possible to change the type of elements in an array?
import numpy as np
import random
from random import unif... | [
"The way to do this in numpy is to use a structured array.\nHowever, in many cases where you're using heterogeneous data, a simple python list is a much better choice. (Or, though it wasn't widely available when this answer was written, a pandas.DataFrame is absolutely ideal for this scenario.)\nRegardless, the ex... | [
9,
4
] | [] | [] | [
"arrays",
"numpy",
"python",
"scipy"
] | stackoverflow_0003727369_arrays_numpy_python_scipy.txt |
Q:
Sorting while preserving order in python
What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order.
I.e. sorting a:
a=[2.3, 1.23, 3.4, 0.4]
returns something like
a_sorted = [0.4, 1.23, 2.3, 3.4]
a_order = [4, 2, 1, 3]
If you catch my drift.
A:
You could do ... | Sorting while preserving order in python | What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order.
I.e. sorting a:
a=[2.3, 1.23, 3.4, 0.4]
returns something like
a_sorted = [0.4, 1.23, 2.3, 3.4]
a_order = [4, 2, 1, 3]
If you catch my drift.
| [
"You could do something like this:\n>>> sorted(enumerate(a), key=lambda x: x[1])\n[(3, 0.4), (1, 1.23), (0, 2.3), (2, 3.4)]\n\nIf you need to indexing to start with 1 instead of 0, enumerate accepts the second parameter.\n",
"\nUse enumerate to generate the sequence numbers.\nUse sorted with a key to sort by the ... | [
17,
5,
3,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003728017_python_sorting.txt |
Q:
BeautifulSoup or regex HTML table to data structure?
I've got an HTML table that I'm trying to parse the information from. However, some of the tables span multiple rows/columns, so what I would like to do is use something like BeautifulSoup to parse the table into some type of Python structure. I'm thinking of ju... | BeautifulSoup or regex HTML table to data structure? | I've got an HTML table that I'm trying to parse the information from. However, some of the tables span multiple rows/columns, so what I would like to do is use something like BeautifulSoup to parse the table into some type of Python structure. I'm thinking of just using a list of lists so I would turn something like
<t... | [
"There was a recent discussion on the python group on linkedin about a similar issue, and apparently lxml is the most recommended pythonic parser for html pages.\nhttp://www.linkedin.com/groupItem?view=&gid=25827&type=member&item=27735259&qid=d2948a0e-6c0c-4256-851b-5e7007859553&goback=.gmp_25827\n",
"You'll prob... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python",
"regex"
] | stackoverflow_0003727661_beautifulsoup_python_regex.txt |
Q:
python: multiple inheritance and __add__() in base class
I've got a base class where I want to handle __add__() and want to support when __add__ing two subclass instances - that is have the methods of both subclasses in the resulting instance.
import copy
class Base(dict):
def __init__(self, **data):
... | python: multiple inheritance and __add__() in base class | I've got a base class where I want to handle __add__() and want to support when __add__ing two subclass instances - that is have the methods of both subclasses in the resulting instance.
import copy
class Base(dict):
def __init__(self, **data):
self.update(data)
def __add__(self, other):
resul... | [
"In general this is a bad idea. You're trying to inject methods into a type. That being said, you can certainly do this in python, but you'll have to realize that you want to create a new type each time you do this. Here's an example:\nimport copy\n\nclass Base(dict):\n global_class_cache = {}\n\n def __init_... | [
1,
0
] | [] | [] | [
"multiple_inheritance",
"python"
] | stackoverflow_0003728166_multiple_inheritance_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.