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:
how to create non-rectangular bounding box around specific values in 2d numpy array?
I have a 2D numpy array. I want to find the non rectangular bounding box around specific values of the array. Rectangular bounding box has already been solved in the Question:How to select all locations of unique elements in numpy... | how to create non-rectangular bounding box around specific values in 2d numpy array? | I have a 2D numpy array. I want to find the non rectangular bounding box around specific values of the array. Rectangular bounding box has already been solved in the Question:How to select all locations of unique elements in numpy 2d array with bounding box around them?
Lets consider the following example
array([[1, 1,... | [
"You can use a segmentation algorithm based on a graph partition method. For example, you can use Random Walker. But you will have to alter the weights in the following way.\nFor every pixel v_i let g_i be the pixel's color. While the original algorithm defines w_{ij} as:\nw_{ij} = exp{-beta*(g_i - g_j)^2)}\n\nYou ... | [
1
] | [] | [] | [
"image_processing",
"numpy",
"python"
] | stackoverflow_0007741383_image_processing_numpy_python.txt |
Q:
Dbus/GLib Main Loop, Background Thread
I'm starting out with DBus and event driven programming in general. The service that I'm trying to create really consists of three parts but two are really "server" things.
1) The actual DBus server talks to a remote website over HTTPS, manages sessions, and conveys info the ... | Dbus/GLib Main Loop, Background Thread | I'm starting out with DBus and event driven programming in general. The service that I'm trying to create really consists of three parts but two are really "server" things.
1) The actual DBus server talks to a remote website over HTTPS, manages sessions, and conveys info the clients.
2) The other part of the service ca... | [
"You have to explicitly enable multithreading when using gobject by calling gobject.threads_init(). See the PyGTK FAQ for background info.\nNext to that, for the purpose you're describing, timeouts seem to be a better fit. Use as follows:\n# Enable timer\nself.timer = gobject.timeout_add(time_in_ms, self.remote.kee... | [
6
] | [] | [] | [
"dbus",
"glib",
"python"
] | stackoverflow_0007741035_dbus_glib_python.txt |
Q:
append field to record array?
If I define a structured array:
import numpy as np
x = np.array([(1, 'O', 1)],
dtype=np.dtype([('step', 'int32'),
('symbol', '|S1'),
('index', 'int32')]))
seems fine until I do this:
import numpy.lib.recfunctions ... | append field to record array? | If I define a structured array:
import numpy as np
x = np.array([(1, 'O', 1)],
dtype=np.dtype([('step', 'int32'),
('symbol', '|S1'),
('index', 'int32')]))
seems fine until I do this:
import numpy.lib.recfunctions as rec
rec.append_fields(x,'x',x['i... | [
"Thanks all. On NumPy 1.4.1 this was giving me the error but I just upgraded to the git 2.0 version and it works fine.\n"
] | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007740243_numpy_python.txt |
Q:
pydev: find all references to a function
This has probably been asked before but I can't seem to find the answer. I've moved from windows to Linux and started using PyDev (Aptana) recently but what I cannot seem to find is how to find all references to a function.
A:
Ctrl+Shift+G will find all the references to ... | pydev: find all references to a function | This has probably been asked before but I can't seem to find the answer. I've moved from windows to Linux and started using PyDev (Aptana) recently but what I cannot seem to find is how to find all references to a function.
| [
"Ctrl+Shift+G will find all the references to a function in PyDev (F3 will go to the definition of a function).\n",
"I believe what you are looking for is F3. If not all of the key bindings for pydev are listed at:\nhttp://pydev.org/manual_adv_keybindings.html\n"
] | [
42,
3
] | [] | [] | [
"pydev",
"python"
] | stackoverflow_0007731324_pydev_python.txt |
Q:
Django - Receiving JSON from Google Maps API
I am trying to retrieve some data from the Google Maps API from a Django app.
req = 'http://maps.google.com/maps/nav?q=from:London%20to:Manchester'
data = urllib.urlopen(req).read()
jsondata = simplejson.loads(data)
However, the above gives me the following error:
Unic... | Django - Receiving JSON from Google Maps API | I am trying to retrieve some data from the Google Maps API from a Django app.
req = 'http://maps.google.com/maps/nav?q=from:London%20to:Manchester'
data = urllib.urlopen(req).read()
jsondata = simplejson.loads(data)
However, the above gives me the following error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa... | [
"Google maps returns response in ISO-8859-1 encoding. You need to decode the data bytestring before passing it to simplejson:\njsondata = simplejson.loads(data.decode('ISO-8859-1'))\n\n"
] | [
2
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0007742198_django_json_python.txt |
Q:
Python After 5:00pm
When a function runs I need it to check the current system time and if its past 5:00pm to do something.
current_time = datetime.datetime.now()
if current_time > {code to represent 17:00 hours}:
do stuff
Edit for clarification:
Orders are being sent into my software which handles the pickin... | Python After 5:00pm | When a function runs I need it to check the current system time and if its past 5:00pm to do something.
current_time = datetime.datetime.now()
if current_time > {code to represent 17:00 hours}:
do stuff
Edit for clarification:
Orders are being sent into my software which handles the picking/packing of orders in a ... | [
"if datetime.datetime.now().hour >= 17:\n pass\n\n",
"Sure, it's easy:\n>>> import datetime\n>>> datetime.datetime.now().time()\ndatetime.time(10, 36, 5, 572343)\n>>> datetime.datetime.now().time() >= datetime.time(17,0,0)\nFalse\n>>> datetime.datetime.now().time() >= datetime.time(8,0,0)\nTrue\n\n"
] | [
10,
4
] | [] | [] | [
"python"
] | stackoverflow_0007742605_python.txt |
Q:
How to enable Eclipse debugging features in a web application?
I am using Django framework for my Python Web Application using Eclipse IDE and PyDev Plugin.
How can I use the debugging features?
UPDATES1
particularly using http://pydev.org/updates plugin
UPDATES2
I already did the following:
.pydevproject
<?xml ve... | How to enable Eclipse debugging features in a web application? | I am using Django framework for my Python Web Application using Eclipse IDE and PyDev Plugin.
How can I use the debugging features?
UPDATES1
particularly using http://pydev.org/updates plugin
UPDATES2
I already did the following:
.pydevproject
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev versi... | [
"Here are some how-tos:\n\nhttp://matt.geek.nz/2009/02/debugging-django-apps-with-eclipse-and-pydev/\nDjango debugging with Eclipse and PyDev\nhttp://brill.no/debugging-django-apps-with-eclipse/\n\n",
"To configure PyDev to work with Django see: http://pydev.org/manual_adv_django.html \nSo, if you execute without... | [
1,
1
] | [] | [] | [
"debugging",
"django",
"eclipse",
"pydev",
"python"
] | stackoverflow_0007734030_debugging_django_eclipse_pydev_python.txt |
Q:
Idiomatic Way to Transfer Django Model Validation Errors to a Form
Please help me understand if the following choices I have made are idiomatic/good and if not, how to improve.
1) Model Validation over Form Validation
I prefer to use the new model validation over form validation whenever possible as it seems a mor... | Idiomatic Way to Transfer Django Model Validation Errors to a Form | Please help me understand if the following choices I have made are idiomatic/good and if not, how to improve.
1) Model Validation over Form Validation
I prefer to use the new model validation over form validation whenever possible as it seems a more DRY and fundamental way to create rules for the data. Two examples for... | [
"[Edited - hope this answers your comments]\nI'll be brief and direct but do not want be impolite :)\n1) Model Validation over Form Validation \nI guess that the rule of thumb could be that as long as the rule is really associated with the model, yes, it's better to do validation at model level.\nFor multiple-model... | [
5,
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007736596_django_python.txt |
Q:
discover path of python module
Possible Duplicate:
Retrieving python module path
Suppose I have code in 3 python files. x.py, y.py, z.py.
x calls y and y calls z. In the code in z.py, I want to know what directory x.py is in.
Is there a function that will tell me this?
EDIT
forget z.py. I just want y.py to p... | discover path of python module |
Possible Duplicate:
Retrieving python module path
Suppose I have code in 3 python files. x.py, y.py, z.py.
x calls y and y calls z. In the code in z.py, I want to know what directory x.py is in.
Is there a function that will tell me this?
EDIT
forget z.py. I just want y.py to print out the path of x.py.
EDIT
No... | [
"If the code in z.py has indirectly imported x.py, it will be in sys.modules. So try:\nmodule = sys.modules.get('x')\nif module is not None:\n print module.__file__\n\n",
"Import x and evaluate x.__file__.\n",
"In this circumstance those imports may lead to chain imports. So, in some functions namespace impo... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007740945_python.txt |
Q:
Tkinter - Why is my background/frame not re-painting?
I am not sure if I am on the right track here-- but I started GUI programming with Python.
I have all of my buttons and entries worked out. The main problem I am having is with the method that rolls my die and places the result.
def roll(self):
self.die =... | Tkinter - Why is my background/frame not re-painting? | I am not sure if I am on the right track here-- but I started GUI programming with Python.
I have all of my buttons and entries worked out. The main problem I am having is with the method that rolls my die and places the result.
def roll(self):
self.die = Die(int(self.sides.get())) # gets from label
t = self.... | [
"It seems to me that you're not using objects at their best values. You should modify you code in this way:\n\neach time you need a new roll, you instantiate a new Die. Why not keeping the same instance?\neach time you want to display the roll, you instantiate a new Label. Maybe you're not aware of this, but you ca... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0007735003_python_tkinter_user_interface.txt |
Q:
How to test equivalence of ranges
One of my unittests checks to see if a range is set up correctly after reading a log file, and I'd like to just test var == range(0,10). However, range(0,1) == range(0,1) evaluates to False in Python 3.
Is there a straightforward way to test the equivalence of ranges in Python 3?... | How to test equivalence of ranges | One of my unittests checks to see if a range is set up correctly after reading a log file, and I'd like to just test var == range(0,10). However, range(0,1) == range(0,1) evaluates to False in Python 3.
Is there a straightforward way to test the equivalence of ranges in Python 3?
| [
"In Python3, range returns an iterable of type range. Two ranges are equal if and only if they are identical (i.e. share the same id.) To test equality of its contents, convert the range to a list:\nlist(range(0,1)) == list(range(0,1))\n\nThis works fine for short ranges. For very long ranges, Charles G Waldman's s... | [
10,
6,
1,
1
] | [] | [] | [
"python",
"python_3.x",
"unit_testing"
] | stackoverflow_0007740796_python_python_3.x_unit_testing.txt |
Q:
Sorting a dictionary by value then by key
This seems like it has to be a dupe but my SO-searching-fu is poor today...
Say I have a dictionary of integer key/values, how can I sort the dictionary by the values descending, then by the key descending (for common values).
Input:
{12:2, 9:1, 14:2}
{100:1, 90:4, 99:3, ... | Sorting a dictionary by value then by key | This seems like it has to be a dupe but my SO-searching-fu is poor today...
Say I have a dictionary of integer key/values, how can I sort the dictionary by the values descending, then by the key descending (for common values).
Input:
{12:2, 9:1, 14:2}
{100:1, 90:4, 99:3, 92:1, 101:1}
Output:
[(14,2), (12,2), (9,1)] ... | [
"In [62]: y={100:1, 90:4, 99:3, 92:1, 101:1}\nIn [63]: sorted(y.items(), key=lambda x: (x[1],x[0]), reverse=True)\nOut[63]: [(90, 4), (99, 3), (101, 1), (100, 1), (92, 1)]\n\nThe key=lambda x: (x[1],x[0]) tells sorted that for each item x in y.items(), use (x[1],x[0]) as the proxy value to be sorted. Since x is of ... | [
91,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007742752_python.txt |
Q:
Can you force an FTP client to use binary from the server side
We have devices that run a proprietary FTP client on them. They retrieve media files (AVI videos and Images) as well as XML files from our web service utilizing a python based FTP server. The problem I'm having is that the FTP client wants to download ... | Can you force an FTP client to use binary from the server side | We have devices that run a proprietary FTP client on them. They retrieve media files (AVI videos and Images) as well as XML files from our web service utilizing a python based FTP server. The problem I'm having is that the FTP client wants to download the media files in ASCII mode instead of binary mode. I'd like to co... | [
"You can override the default behaviour or you ftp server by using a custom FTPHandler and overriding the FTPHandler.ftp_TYPE(filetype) method and this way force your server to serve file in binary mode self._current_type = \"i\".\n"
] | [
2
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0007742965_ftp_python.txt |
Q:
Build a list using specific keys in a dict (python)?
I'm implementing the Dijkstra search algorithm in Python. At the end of the search, I reconstruct the shortest path using a predecessor map, starting with the destination node's predecessor. For example:
path = []
path.append(destination)
previous = predecessor_... | Build a list using specific keys in a dict (python)? | I'm implementing the Dijkstra search algorithm in Python. At the end of the search, I reconstruct the shortest path using a predecessor map, starting with the destination node's predecessor. For example:
path = []
path.append(destination)
previous = predecessor_map[destination]
while previous != origin:
path.append... | [
"The only suggestion that I have is to get rid of the slight code duplication:\npath = []\nprevious = destination\nwhile previous != origin:\n path.append(previous)\n previous = predecessor_map[previous]\n\nBeyond that, I think your code is actually very clear and is unlikely to benefit from any attempts to s... | [
7,
4,
3,
1,
1,
0
] | [] | [] | [
"dictionary",
"dijkstra",
"list",
"python",
"search"
] | stackoverflow_0007741662_dictionary_dijkstra_list_python_search.txt |
Q:
Getting NoneType while trying to get updated date from RSS using python
I have the following code which works well when I try to get the date from any RSS feed(Using Universal feed Parser):
for entry in RSS_FEED.entries:
FEED_DATE=entry.updated_parsed
FEED_DATE_STRING = datetime.fromtimestamp(mktime(FEED_D... | Getting NoneType while trying to get updated date from RSS using python | I have the following code which works well when I try to get the date from any RSS feed(Using Universal feed Parser):
for entry in RSS_FEED.entries:
FEED_DATE=entry.updated_parsed
FEED_DATE_STRING = datetime.fromtimestamp(mktime(FEED_DATE))
FEED_DATE_STRING = str(FEED_DATE_STRING)
FEED_DATE_STRING = Dat... | [
"Assuming that you're using the feedparser package to parse the rss: the reason for the error in the log file is that you are using a date format that feedparser does not understand. This means entry.updated_parsed will get set to None. The problem seems to be the fourth element in the time field. If the dates are ... | [
0
] | [] | [] | [
"date",
"datetime",
"python",
"rss"
] | stackoverflow_0007742011_date_datetime_python_rss.txt |
Q:
how to show a message from a blender script?
Is there a way to show a simple message box with a text from a blender script? For example if i'm having an error during execution.
A:
Update: The link does not exist officially any longer and I stopped developing for Blender. The old 2.5 cookbook is still available i... | how to show a message from a blender script? | Is there a way to show a simple message box with a text from a blender script? For example if i'm having an error during execution.
| [
"Update: The link does not exist officially any longer and I stopped developing for Blender. The old 2.5 cookbook is still available in the internet archive at:\nhttps://web.archive.org/web/20120824033549/http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Interface#A_popup_dialog\n\nHave a ... | [
9
] | [] | [] | [
"blender",
"python",
"scripting"
] | stackoverflow_0007697532_blender_python_scripting.txt |
Q:
Pygame quick pixel reading
Alright, hopefully someone can help me with this because I'm at a loss here.
I'm working on a game in python that uses the camera as the main controller. To play the game, you move a simple light around, and that controls the game.
So far, I've managed to get the camera image to a surfac... | Pygame quick pixel reading | Alright, hopefully someone can help me with this because I'm at a loss here.
I'm working on a game in python that uses the camera as the main controller. To play the game, you move a simple light around, and that controls the game.
So far, I've managed to get the camera image to a surface, and display it on the screen.... | [
"It seems that the surfarray object is backed by numpy arrays, so your chances of getting it faster are relying on their native methods.\nTake a look at this: numpy.argmax\nYou might need to transform your 3d array to a 2d luminosity matrix first (but don't do it with nested loops! XD). Maybe you'll need some resha... | [
2,
0
] | [] | [] | [
"algorithm",
"image",
"image_processing",
"pygame",
"python"
] | stackoverflow_0007743545_algorithm_image_image_processing_pygame_python.txt |
Q:
Removing characters from a tuple
Im using
Users = win32net.NetGroupGetUsers(IP,'none',0),
to get all the local users on a system. The output is a tuple,
(([{'name': u'Administrator'}, {'name': u'Guest'}, {'name': u'Tom'}], 3, 0),)
I want to clean this up so it just prints out "Administrator, Guest, Tom". I tried... | Removing characters from a tuple | Im using
Users = win32net.NetGroupGetUsers(IP,'none',0),
to get all the local users on a system. The output is a tuple,
(([{'name': u'Administrator'}, {'name': u'Guest'}, {'name': u'Tom'}], 3, 0),)
I want to clean this up so it just prints out "Administrator, Guest, Tom". I tried using strip and replace but you cant ... | [
"', '.join(user['name'] for user in Users[0][0])\n\n",
"This should not end with a comma:\nUsers = win32net.NetGroupGetUsers(IP,'none',0), \n\nThe trailing comma turns the result into a single item tuple containing the result, which is itself a tuple. \nThe data you want is in Users[0].\n>>> print Users[0]\n[{'... | [
4,
4,
2
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0007743827_python_string_tuples.txt |
Q:
How to share globals between imported modules?
I have two modules, a.py and b.py. I want the globals from a.py to be available in b.py like this:
a.py:
#!/usr/bin/env python
var = "this is global"
import b
b.foo()
b.py:
#!/usr/bin/env python
var = "this is global"
def foo():
print var
Currently, I re-dec... | How to share globals between imported modules? | I have two modules, a.py and b.py. I want the globals from a.py to be available in b.py like this:
a.py:
#!/usr/bin/env python
var = "this is global"
import b
b.foo()
b.py:
#!/usr/bin/env python
var = "this is global"
def foo():
print var
Currently, I re-declare the globals in each module. There must be an ea... | [
"Create a settings module that has shared globals if that's what you want. That way you're only importing and referencing each global one time, and you're keeping them isolated within the namespace of the settings module. It's a good thing.\n#settings.py\nvar = 'this is global'\n\n# a.py\nimport settings\nimport b\... | [
3,
2,
2
] | [] | [] | [
"global",
"python",
"variables"
] | stackoverflow_0007743905_global_python_variables.txt |
Q:
how to detect if a point lies in a non-rectangular region in a 2D numpy array?
I have a 2D array. Lets suppose that it has some connected region which is non rectangular. Consider the following example
array([[1, 1, 2, 2],\
[0, 1, 0, 1],\
[3, 0, 1, 4],\
[0, 3, 1, 1]])
In above array all t... | how to detect if a point lies in a non-rectangular region in a 2D numpy array? | I have a 2D array. Lets suppose that it has some connected region which is non rectangular. Consider the following example
array([[1, 1, 2, 2],\
[0, 1, 0, 1],\
[3, 0, 1, 4],\
[0, 3, 1, 1]])
In above array all the ones are connected. I know all these coordinates which are stored lets say as a 2... | [
"areas = array([[1, 1, 2, 2],\\\n [0, 1, 0, 1],\\\n [3, 0, 1, 4],\\\n [0, 3, 1, 1]])\n\ndef is_in_area(x,y, area_num):\n return areas[round(x), round(y)] == area_num\n\nIs this what you're going for?\nOf course, you might want some bounds checking in there.\n"
] | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007743949_numpy_python.txt |
Q:
How to remove trailing whitespace in PyDev plugin for Eclipse
Ideally, eclipse should remove all trailing whitespace when I save the file. I know there is option for this in C++/Java plugins for eclipse, but I couldnt find one for PyDev. Is there one? If not, whats the easiest way to achieve this?
A:
Check in:
P... | How to remove trailing whitespace in PyDev plugin for Eclipse | Ideally, eclipse should remove all trailing whitespace when I save the file. I know there is option for this in C++/Java plugins for eclipse, but I couldnt find one for PyDev. Is there one? If not, whats the easiest way to achieve this?
| [
"Check in:\nPreferences > PyDev > Editor > Code Style > Code Formatter\nand check the \"Right trim lines?\" check box.\n",
"i stumbled accros this usefull [site][1]\n[1]: http://andrei.gmxhome.de/anyedit/ hope this could help\n"
] | [
46,
12
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0007744258_eclipse_pydev_python.txt |
Q:
AppEngine: switching to Python 2.7
For tons of reasons, I would like to go ahead and switch to Python 2.7. The new python version requires using the High Replication Datastore. As far as I can see, converting to it is not really possible: the only way is to create a new app, with new ID, and copy over the datastor... | AppEngine: switching to Python 2.7 | For tons of reasons, I would like to go ahead and switch to Python 2.7. The new python version requires using the High Replication Datastore. As far as I can see, converting to it is not really possible: the only way is to create a new app, with new ID, and copy over the datastore. Changing my app ID is something I am ... | [
"There is no way to avoid changing the app ID, but you can request that the old ID be aliased so requests to old_appid.appspot.com will be handled by the new application. If you're serving the application on your own domain, of course, the app ID is irrelevant.\nThe Master/Slave datastore will almost certainly neve... | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007743653_google_app_engine_python.txt |
Q:
How Can I Detect Changes To A Text File During The Execution Of A Python Script?
I am working with a temperamental web app that I'm not going to name. It runs into problems from time to time, and when it does, it writes stack traces and error messages to an exception.log file. I want to know about these problems i... | How Can I Detect Changes To A Text File During The Execution Of A Python Script? | I am working with a temperamental web app that I'm not going to name. It runs into problems from time to time, and when it does, it writes stack traces and error messages to an exception.log file. I want to know about these problems in a timely manner, so I've got a Python script that scans the log regularly (hooray fo... | [
"I would avoid deleting the exception log while the web app is still running. Just scan the log for updates without making any changes.\n#lastKnownSizeOfFile is saved somewhere so it persists between executions of this script\nif size(file) > lastKnownSizeOfFile: #found an update!\n amountToRead = size(file) - l... | [
2,
1
] | [] | [] | [
"file_io",
"logging",
"python"
] | stackoverflow_0007744226_file_io_logging_python.txt |
Q:
MongoDB ORM for Python?
I am trying to migrate from sqlalchemy(SQlite) to using mongodb. I would like schema vertification. I amm looking at mongokit, but I want something which is similar to mappers, so that it would save from the object's property, and not a dict.
i would like a mapper so that i can use existi... | MongoDB ORM for Python? | I am trying to migrate from sqlalchemy(SQlite) to using mongodb. I would like schema vertification. I amm looking at mongokit, but I want something which is similar to mappers, so that it would save from the object's property, and not a dict.
i would like a mapper so that i can use existing objects without modifying ... | [
"Another option is MongoEngine. The ORM for MongoEngine is very similar to the ORM used by Django.\nExample (from the tutorial):\nclass Post(Document):\n title = StringField(max_length=120, required=True)\n author = ReferenceField(User)\n\nclass TextPost(Post):\n content = StringField()\n\nclass ImagePost(... | [
76,
41,
31,
15
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0002781682_mongodb_python.txt |
Q:
Printing unescaped white space to shell
Consider this line of Python code:
s = "This string has \n\r whitespace"
How do I make
print s
give me
This string has \n\r whitespace
instead of
This string has
whitespace
as it does now.
A:
do you want a raw string ?
s = r"This string has \n\r whitespace"
or to trans... | Printing unescaped white space to shell | Consider this line of Python code:
s = "This string has \n\r whitespace"
How do I make
print s
give me
This string has \n\r whitespace
instead of
This string has
whitespace
as it does now.
| [
"do you want a raw string ?\ns = r\"This string has \\n\\r whitespace\"\n\nor to transform special characters to it's representation?\nrepr(s)\n\n",
" print s.encode('string-escape')\n\n",
"You want the repr function.\nprint repr(s)\n\n",
"You can use python's formatting capabilities to print the string in it... | [
24,
9,
4,
1
] | [] | [] | [
"escaping",
"python"
] | stackoverflow_0007744518_escaping_python.txt |
Q:
How do i speed up a python nested loop?
I'm trying to calculate the gravity effect of a buried object by calculating the effect on each side of the body then summing up the contributions to get one measurement at one station, an repeating for a number of stations. the code is as follows( the body is a square and t... | How do i speed up a python nested loop? | I'm trying to calculate the gravity effect of a buried object by calculating the effect on each side of the body then summing up the contributions to get one measurement at one station, an repeating for a number of stations. the code is as follows( the body is a square and the code calculates clockwise around it, that'... | [
"Your xcorn and zcorn values repeat, so consider caching the result of some of the computations.\nTake a look at the timeit and profile modules to get more information about what is taking the most computational time.\n",
"It is very inefficient to access individual elements of a numpy array in a Python loop. For... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007744065_python.txt |
Q:
Scrapy spider is not working
Since nothing so far is working I started a new project with
python scrapy-ctl.py startproject Nu
I followed the tutorial exactly, and created the folders, and a new spider
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExt... | Scrapy spider is not working | Since nothing so far is working I started a new project with
python scrapy-ctl.py startproject Nu
I followed the tutorial exactly, and created the folders, and a new spider
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import... | [
"Please also check the version of scrapy. The latest version uses \"name\" instead of \"domain_name\" attribute to uniquely identify a spider.\n",
"Have you included the spider in SPIDER_MODULES list in your scrapy_settings.py?\nIt's not written in the tutorial anywhere that you should to this, but you do have to... | [
6,
3,
3,
2,
2
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0001806990_python_scrapy.txt |
Q:
If I give a POP server invalid credentials using poplib, why can't I try again with the correct ones?
I'm writing a script to login to Hotmail. It asks the user to enter a password and if they get the password right, all is well.
If they get the password wrong the first time however, the valid password will not w... | If I give a POP server invalid credentials using poplib, why can't I try again with the correct ones? | I'm writing a script to login to Hotmail. It asks the user to enter a password and if they get the password right, all is well.
If they get the password wrong the first time however, the valid password will not work on subsequent attempts.
This is what I'm using for the user to enter their password:
import poplib
M =... | [
"Okay, I guess you only get one login attempt with an object from poplib. The solution was to move the declaration of \"M\" down into the while loop (I swear I tried that before posting, but I must have stuffed it up somehow).\n",
"As far as I managed an ISP mail server, brute force attacks were a big problem for... | [
1,
0
] | [] | [] | [
"poplib",
"python"
] | stackoverflow_0006971506_poplib_python.txt |
Q:
cherrypy password form
I am trying to make a user registration and login for an application I'm working on using the form below.
<html><form method="get" action="login">
Email Address: <input name="email" type="text"><br/>
Password: <input name="password" type="password"><br/>
<input type="submit" value="Submit" ... | cherrypy password form | I am trying to make a user registration and login for an application I'm working on using the form below.
<html><form method="get" action="login">
Email Address: <input name="email" type="text"><br/>
Password: <input name="password" type="password"><br/>
<input type="submit" value="Submit" />
</form>
</html>
However ... | [
"They show up in the URL because your form is using the GET method, you should be using POST and processing the values on the server side.\n",
"In addition to the POST/GET confusion Shawn points out, you might be interested to look at Cherrypy's built-in authentication tool.\n"
] | [
2,
0
] | [] | [] | [
"cherrypy",
"forms",
"html",
"passwords",
"python"
] | stackoverflow_0007744918_cherrypy_forms_html_passwords_python.txt |
Q:
Multiple context `with` statement in Python 2.6
I like the convenience of the multiple context with statement in Python 2.7:
with open('a.txt') as a, open('b.txt') as b:
do_many_amazing_things(a, b)
However, I need to maintain compatibility with 2.6.
with was brought to 2.5 via __future__, but I am unable to f... | Multiple context `with` statement in Python 2.6 | I like the convenience of the multiple context with statement in Python 2.7:
with open('a.txt') as a, open('b.txt') as b:
do_many_amazing_things(a, b)
However, I need to maintain compatibility with 2.6.
with was brought to 2.5 via __future__, but I am unable to find anything about the multiple context version being... | [
"If no backward-compatible equivalent of this is possible, I would handle it by making the multiple-context with statement a set of single-context, nested with statements.\nwith open('a.txt') as a: \n with open('b.txt') as b:\n do_many_amazing_things(a, b)\n\nEDIT to address your edit:\nIf you insist on n... | [
20
] | [] | [] | [
"python"
] | stackoverflow_0007745164_python.txt |
Q:
Converting .py to .exe in python 2.5: doesnt execute .exe program directly
I have successfully converted my .py script to .exe but the problem is that it wont get executed when I press the .exe icon. A black screen pops up for a fraction of a second and then disappears.
I tried executing it through the command pro... | Converting .py to .exe in python 2.5: doesnt execute .exe program directly | I have successfully converted my .py script to .exe but the problem is that it wont get executed when I press the .exe icon. A black screen pops up for a fraction of a second and then disappears.
I tried executing it through the command prompt and it did get executed but doesn't run if I click the .exe directly. Just w... | [
"Your shell disappears because the program finishes.\nEnd your program with a raw_input('enter to finish') line and the console will stay allowing you to see the result. \n",
"How do you know it got executed when you ran it from command prompt? If the app just outputs something and exits, you will see the behavi... | [
2,
0
] | [] | [] | [
"console_application",
"executable",
"python"
] | stackoverflow_0007745136_console_application_executable_python.txt |
Q:
Underlying mechanism for Python class member lookup
In Python, if I define three classes:
class A:
name = 'oliver'
hailstone_ending = [4,2,1]
class B:
def __init__(self):
self.name = 'oliver'
self.hailstone_ending = [4,2,1]
class C:
pass
c = C()
c.name = 'oliver'
c.hailstone_endi... | Underlying mechanism for Python class member lookup | In Python, if I define three classes:
class A:
name = 'oliver'
hailstone_ending = [4,2,1]
class B:
def __init__(self):
self.name = 'oliver'
self.hailstone_ending = [4,2,1]
class C:
pass
c = C()
c.name = 'oliver'
c.hailstone_ending = [4,2,1]
Under the hood, does member lookup function... | [
"In python, each class and each instance gets a dictionary. A uses the class dictionary. The examples for classes B and C are using the instance dictionaries. B will not be equivalent to A -- python is not intended to be fast, it would be very hard if not impossible to prove that no instances of B would get muta... | [
2,
2
] | [] | [] | [
"dictionary",
"lookup",
"member",
"python"
] | stackoverflow_0007745365_dictionary_lookup_member_python.txt |
Q:
Neural Network based ranking of documents
I'm planning of implementing a document ranker which uses neural networks. How can one rate a document by taking in to consideration the ratings of similar articles?. Any good python libraries for doing this?. Can anyone recommend a good book for AI, with python code.
EDIT... | Neural Network based ranking of documents | I'm planning of implementing a document ranker which uses neural networks. How can one rate a document by taking in to consideration the ratings of similar articles?. Any good python libraries for doing this?. Can anyone recommend a good book for AI, with python code.
EDIT
I'm planning to make a recommendation engine w... | [
"The problem you are trying to solve is called \"collaborative filtering\". \nNeural Networks\nOne state-of-the-art neural network method is Deep Belief Networks and Restricted Boltzman Machines. For a fast python implementation for a GPU (CUDA) see here. Another option is PyBrain.\nAcademic papers on your specific... | [
12,
6,
5,
4,
1,
1
] | [] | [] | [
"machine_learning",
"neural_network",
"python"
] | stackoverflow_0007554873_machine_learning_neural_network_python.txt |
Q:
Using Groupby to Group a Column in an Access Table in Python
I have been playing with the groupby function from the itertools module for a while now (like days)
for k, g in groupby(data, keyfunc):
I am really having trouble understanding the syntax. I've tried a variety of different things, but I really don't kn... | Using Groupby to Group a Column in an Access Table in Python | I have been playing with the groupby function from the itertools module for a while now (like days)
for k, g in groupby(data, keyfunc):
I am really having trouble understanding the syntax. I've tried a variety of different things, but I really don't know what to put in for "data" and "keyfunc" and get it to return th... | [
"import itertools as it\nfor key, group in it.groupby(cursor, lambda row: row.ROAD_TYPE):\n for sec_col,pairs in it.groupby(group, lambda row: row.SECOND_COLUMN):\n for row in pairs:\n print('{t} {s}'.format(t=row.ROAD_TYPE,s=row.SECOND_COLUMN))\n print\n print\n\nHere are two exampl... | [
1,
1,
1
] | [] | [] | [
"group_by",
"python"
] | stackoverflow_0007744220_group_by_python.txt |
Q:
grab lines form file in python
i am trying to grab some lines form lines in a huge file. For example suppose
f =
a b
c d
e s
m n
h g
.
.
.
The code I am trying to used is as follows
import re
f = open('f.txt')
y = [a,s, ...] # the laters that i would like to grab it with the line form the file f
grab = y
for l... | grab lines form file in python | i am trying to grab some lines form lines in a huge file. For example suppose
f =
a b
c d
e s
m n
h g
.
.
.
The code I am trying to used is as follows
import re
f = open('f.txt')
y = [a,s, ...] # the laters that i would like to grab it with the line form the file f
grab = y
for line in f:
match = grab.search(li... | [
"With the following code you will print lines from f if any of the chars in y is in the line.\nYou can modify it easily if what you want is to get lines where both chars are in y\nfor line in f:\n letters = line.split()\n for letter in letters:\n if letter in y:\n print line\n break\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007745939_python.txt |
Q:
How to expand a list to function arguments in Python
Is there syntax that allows you to expand a list into the arguments of a function call?
Example:
# Trivial example function, not meant to do anything useful.
def foo(x,y,z):
return "%d, %d, %d" %(x,y,z)
# List of values that I want to pass into foo.
values =... | How to expand a list to function arguments in Python | Is there syntax that allows you to expand a list into the arguments of a function call?
Example:
# Trivial example function, not meant to do anything useful.
def foo(x,y,z):
return "%d, %d, %d" %(x,y,z)
# List of values that I want to pass into foo.
values = [1,2,3]
# I want to do something like this, and get the ... | [
"It exists, but it's hard to search for. I think most people call it the \"splat\" operator.\nIt's in the documentation as \"Unpacking argument lists\".\nYou'd use it like this for positional arguments:\nvalues = [1, 2]\nfoo(*values)\n\nThere's also one for dictionaries to call with named arguments:\nd = {'a': 1, '... | [
234,
88,
17,
16
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0007745952_arguments_python.txt |
Q:
what's the difference in effect of backgrounding vs forking?
Goal: Create a long running process from a python script.
I started with a simple unix/linux daemon in Python. But, then I also created an init script that just sents the python script (with a while loop) into the background like this: python test.p... | what's the difference in effect of backgrounding vs forking? | Goal: Create a long running process from a python script.
I started with a simple unix/linux daemon in Python. But, then I also created an init script that just sents the python script (with a while loop) into the background like this: python test.py & I'm wondering what the difference, in effect, is between the ... | [
"They are the same thing. The only difference is the python daemon should set the parent process which means if you kill the parent process the child should die too.\n"
] | [
1
] | [] | [] | [
"background_process",
"daemon",
"init",
"python"
] | stackoverflow_0007745707_background_process_daemon_init_python.txt |
Q:
making snapshots of postgres db
im trying to write a python script that takes snapshots of a postgres database and restores those snapshots. trying to get pg_dump > data.sql to work has been a nightmare and i came across an idea that i wanted to run past you guys.
the idea is to follow this logic for taking the s... | making snapshots of postgres db | im trying to write a python script that takes snapshots of a postgres database and restores those snapshots. trying to get pg_dump > data.sql to work has been a nightmare and i came across an idea that i wanted to run past you guys.
the idea is to follow this logic for taking the snapshot:
1 - stop the postgres daemon... | [
"If your question is how to run commands from a Python script, you can use subprocess.Popen() to run shell commands such as sudo /etc/init.d/postgresql-x.x stop, etc.\nBut, in my opinion, you should use pg_dump and pg_restore utilities, they will do the work in a more safe and efficient way, and don't need to stop ... | [
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0007743948_postgresql_python.txt |
Q:
How to tie a row in a particular model to a field in another in django
I have a problem with the following (simplified version) models:
Sponsor(models.Model):
sponsor_name = models.CharField()
Concerts(models.Model):
artist_name = models.CharField()
sponsor = models.ManyToMany(Sponsor)
I go to the... | How to tie a row in a particular model to a field in another in django | I have a problem with the following (simplified version) models:
Sponsor(models.Model):
sponsor_name = models.CharField()
Concerts(models.Model):
artist_name = models.CharField()
sponsor = models.ManyToMany(Sponsor)
I go to the admin interface and add a new Sponsor, it automatically shows on any concer... | [
"I think you're mistaking possible values with actually chosen Sponsor in Concert model in django-admin interface. \nTry this python manage.py shell and then from yourapp.yourmodel import Concerts; Concerts.objects.sponsor_set.all(). \nResult should contain only selected Sponsors for that model (I bet you'll see em... | [
2,
1
] | [] | [] | [
"database_design",
"django",
"foreign_key_relationship",
"many_to_many",
"python"
] | stackoverflow_0007746039_database_design_django_foreign_key_relationship_many_to_many_python.txt |
Q:
Python join all combinations of elements within each list
I have a list of tuples each with two elements: [('1','11'),('2','22'),('3','33'),...n]
How would I find all the combinations of each tuple with only selecting one element of the tuple at a time?
The example results:
[[1,2,3],[11,2,3],[11,2,3],[11,22,33... | Python join all combinations of elements within each list | I have a list of tuples each with two elements: [('1','11'),('2','22'),('3','33'),...n]
How would I find all the combinations of each tuple with only selecting one element of the tuple at a time?
The example results:
[[1,2,3],[11,2,3],[11,2,3],[11,22,33],[11,2,33],[11,22,3],[1,22,3],[1,22,33],[1,2,33]]`
itertool... | [
"Use itertools.product:\nIn [88]: import itertools as it\nIn [89]: list(it.product(('1','11'),('2','22'),('3','33')))\nOut[89]: \n[('1', '2', '3'),\n ('1', '2', '33'),\n ('1', '22', '3'),\n ('1', '22', '33'),\n ('11', '2', '3'),\n ('11', '2', '33'),\n ('11', '22', '3'),\n ('11', '22', '33')]\n\n",
"Did you read t... | [
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0007746777_python.txt |
Q:
in Python using the multiprocessing module, how can I determine which object caused a PicklingError?
I have a complex Python program. I'm trying to use the multiprocess Pool to parallelize it. I get the error message
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed.
The t... | in Python using the multiprocessing module, how can I determine which object caused a PicklingError? | I have a complex Python program. I'm trying to use the multiprocess Pool to parallelize it. I get the error message
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed.
The traceback shows the statemen return send(obj)
My hypothesis is that its the "obj" that is causing the probl... | [
"Why not just add some logging right before return send(obj)? At a very minimum, this could help:\nprint repr(obj)\nreturn send(obj)\n\nOr, to only print when it results in an error:\ntry:\n return send(obj)\nexcept:\n print '***', repr(obj)\n raise\n\n",
"The error you're seeing could be caused by passing ... | [
0,
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0007746484_multiprocessing_python.txt |
Q:
Python Tkinter GUI:add text from an entry widget in a pop up window to a listbox in a different window?
I am trying to add an entry from a toplevel window into a listbox in the main window.
So far I have managed to create a button that opens a new window containing 4 entry widgets(name, address, phone number and D... | Python Tkinter GUI:add text from an entry widget in a pop up window to a listbox in a different window? | I am trying to add an entry from a toplevel window into a listbox in the main window.
So far I have managed to create a button that opens a new window containing 4 entry widgets(name, address, phone number and DOB). Is there any way, after I press the OK button on the pop up window, that all four entries are added to t... | [
"Unless I'm missing something in your problem description, the OK button command just needs to copy the values from the Entry fields to the Listbox. Was there more to it than that?\nfrom tkinter import Tk, Frame, Label, Entry, Button, Listbox\n\ndef ok_button():\n li.delete(0, \"end\")\n for i in range(len(f... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007730190_python_tkinter.txt |
Q:
Python Post to form with anti-scrape protection
Trying to scrape the content off a site with Python, that has a simple form authentication with username and password, but also has a hidden field called "foil" that contains what looks like a randomly generated string each time the page is loaded. In order to succes... | Python Post to form with anti-scrape protection | Trying to scrape the content off a site with Python, that has a simple form authentication with username and password, but also has a hidden field called "foil" that contains what looks like a randomly generated string each time the page is loaded. In order to successfully login that value must be included in the conte... | [
"You import cookielib but it does not seem like you're using any CookieJars:\njar = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))\n\nThen use the same opener for both initial form fetching and login form submission. I assume it's a cookie-based protection where a value that ... | [
2
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0007734307_python_web_scraping.txt |
Q:
Double-decoding unicode in python
I am working against an application that seems keen on returning, what I believe to be, double UTF-8 encoded strings.
I send the string u'XüYß' encoded using UTF-8, thus becoming X\u00fcY\u00df (equal to X\xc3\xbcY\xc3\x9f).
The server should simply echo what I sent it, yet return... | Double-decoding unicode in python | I am working against an application that seems keen on returning, what I believe to be, double UTF-8 encoded strings.
I send the string u'XüYß' encoded using UTF-8, thus becoming X\u00fcY\u00df (equal to X\xc3\xbcY\xc3\x9f).
The server should simply echo what I sent it, yet returns the following: X\xc3\x83\xc2\xbcY\xc3... | [
"ret.decode() tries implicitly to encode ret with the system encoding - in your case ascii.\nIf you explicitly encode the unicode string, you should be fine. There is a builtin encoding that does what you need:\n>>> 'X\\xc3\\xbcY\\xc3\\x9f'.encode('raw_unicode_escape').decode('utf-8')\n'XüYß'\n\nReally, .encode('la... | [
27,
3,
0,
0
] | [] | [] | [
"python",
"unicode",
"utf_8"
] | stackoverflow_0004267019_python_unicode_utf_8.txt |
Q:
Using JSON in Python to send query to MongoDB
I'm trying to create the following query in Python for a connection I have to MongoDB.
db.deal.find({"id":"11223|14589"})
By using the writing the following code:
import json
unique_id = "11223|14589"
query = json.dumps({"id":"%s"}) %(unique_id)
Unfortunately, this... | Using JSON in Python to send query to MongoDB | I'm trying to create the following query in Python for a connection I have to MongoDB.
db.deal.find({"id":"11223|14589"})
By using the writing the following code:
import json
unique_id = "11223|14589"
query = json.dumps({"id":"%s"}) %(unique_id)
Unfortunately, this creates a string, and the results I don't get any ... | [
"Not sure what you're trying to achieve here.\nFirst of all, you should not have to serialize anything into JSON. Especially not replace parts of the string after it's serialized.\nSecond, is unique_id one value that you're looking for? If so, just pass it to the query:\nunique_id = '11223|14589'\nfoo.find({'id': u... | [
1
] | [] | [] | [
"pymongo",
"python"
] | stackoverflow_0007746964_pymongo_python.txt |
Q:
Create custom number data type within range?
In Ada, you can define a custom data type such as this
type Day_Of_Month is range 1 .. 31;
So now you can create a Day_Of_Month variable that can only hold an int between 1 and 31. This is nice because we don't have to keep doing conditional checks when want to update ... | Create custom number data type within range? | In Ada, you can define a custom data type such as this
type Day_Of_Month is range 1 .. 31;
So now you can create a Day_Of_Month variable that can only hold an int between 1 and 31. This is nice because we don't have to keep doing conditional checks when want to update the value, with proper exception handling.
Is ther... | [
"If this datatype is going to get used often, it might be worth creating a class for it and overwriting operators so it works more seamlessly. That way, all the exception handling is still internal to the datatype, and it gives you plenty of flexibility to define things like, for your example, differences in the nu... | [
1,
0
] | [] | [] | [
"python",
"types"
] | stackoverflow_0007744695_python_types.txt |
Q:
How to len(generator())
Python generators are very useful. They have advantages over functions that return lists. However, you could len(list_returning_function()). Is there a way to len(generator_function())?
UPDATE:
Of course len(list(generator_function())) would work.....
I'm trying to use a generator I've crea... | How to len(generator()) | Python generators are very useful. They have advantages over functions that return lists. However, you could len(list_returning_function()). Is there a way to len(generator_function())?
UPDATE:
Of course len(list(generator_function())) would work.....
I'm trying to use a generator I've created inside a new generator I'... | [
"The conversion to list that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:\nsum(1 for x in generator)\n\nOf course, be aware ... | [
329,
71,
20,
18,
10,
8,
7,
5
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0007460836_generator_python.txt |
Q:
In bash, "which" gives an incorrect path - Python versions
Can anyone explain how python 2.6 could be getting run by default on my machine? It looks like python points to 2.7, so it seems like which isn't giving me correct information.
~> python --version
Python 2.6.5
~> which python
/opt/local/bin/python
~> /opt... | In bash, "which" gives an incorrect path - Python versions | Can anyone explain how python 2.6 could be getting run by default on my machine? It looks like python points to 2.7, so it seems like which isn't giving me correct information.
~> python --version
Python 2.6.5
~> which python
/opt/local/bin/python
~> /opt/local/bin/python --version
Python 2.7.2
~> ls -l /opt/local/bin... | [
"Bash uses an internal hash table to optimize $PATH lookups. When you install a new program with the same name as an existing program (python in this case) earlier in your $PATH, Bash doesn't know about it and continues to use the old one. The which executable does a full $PATH search and prints out the intended ... | [
26,
0
] | [] | [] | [
"bash",
"macos",
"python"
] | stackoverflow_0007746240_bash_macos_python.txt |
Q:
Python quit unexpectedly while running Django
I'm running Python 2.7.1 on 64-bit Mac OSX Lion. Python keeps crashing while I'm running my local Django 1.3 development server. The error log is below.
This is starting to get annoying. Any ideas?
Process: Python [22917] Path:
/System/Library/Frameworks/Py... | Python quit unexpectedly while running Django | I'm running Python 2.7.1 on 64-bit Mac OSX Lion. Python keeps crashing while I'm running my local Django 1.3 development server. The error log is below.
This is starting to get annoying. Any ideas?
Process: Python [22917] Path:
/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Co... | [
"It looks like its the mysql-extension that crashes, if you have XCode you can try to make sure you have the latest one compiled locally and installed.\n"
] | [
0
] | [] | [] | [
"crash",
"django",
"interpreter",
"osx_lion",
"python"
] | stackoverflow_0007745997_crash_django_interpreter_osx_lion_python.txt |
Q:
How can I make a python StreamWriter REQUIRE unicode input?
The python codecs module provides StreamWriter classes for transparently encoding output streams. For instance:
outstream = codecs.getwriter('utf8')(sys.__stdout__)
outstream.write(u'\u2713')
outstream.write(' A-OK!\n') # I want this to fail!
outstream.c... | How can I make a python StreamWriter REQUIRE unicode input? | The python codecs module provides StreamWriter classes for transparently encoding output streams. For instance:
outstream = codecs.getwriter('utf8')(sys.__stdout__)
outstream.write(u'\u2713')
outstream.write(' A-OK!\n') # I want this to fail!
outstream.close()
However the problem I have with the default StreamWriter ... | [
"If possible, do what you're trying to do in Python 3, which has a much stronger distinction between unicode and bytes. Failing that, you'll need to subclass StreamWriter, for example:\nimport codecs\n\nclass StrictUTF8Writer(codecs.StreamWriter):\n '''A StreamWriter for utf8 that requires written objects be uni... | [
3
] | [] | [] | [
"codec",
"python",
"unicode"
] | stackoverflow_0007747344_codec_python_unicode.txt |
Q:
Python reference to callback in dictionary
I have a class that specifies a set of callback functions (shown here as cb1 and cb2). I keep a map of these which I want to call after some event.
class Foo:
cb1 = None
cb2 = None
def test(self, input):
for (name, callback) in map:
if na... | Python reference to callback in dictionary | I have a class that specifies a set of callback functions (shown here as cb1 and cb2). I keep a map of these which I want to call after some event.
class Foo:
cb1 = None
cb2 = None
def test(self, input):
for (name, callback) in map:
if name == input:
if callback: callba... | [
"Why not make your class explicitly handle registration?\nimport collections\n\nclass Foo(object):\n handlers = None\n\n def __init__(self):\n self.handlers = collections.defaultdict(set)\n\n def register(self, event, callback):\n self.handlers[event].add(callback)\n\n def fire(self, event... | [
13,
1,
0,
0
] | [
"To the contrary, everything is \"by reference\" in Python. But you're copying a reference to None into your dictionary, and changing the original slot doesn't do anything to that reference. If you want to retain an extra level of indirection, then the simplest way would be to store strings. If all of your callback... | [
-1
] | [
"callback",
"python"
] | stackoverflow_0007747611_callback_python.txt |
Q:
Python - Get build-id from an ELF file
I'm trying to extract the build-id from and ELF file (Linux kernel module).
Right now it's using:
subprocess.check_output(['eu-readelf', '-n', filename]).split()[-1]
I was wondering is there's a more pythony way to achieve the same result?
Thanks, Alex.
A:
Calling the eu-r... | Python - Get build-id from an ELF file | I'm trying to extract the build-id from and ELF file (Linux kernel module).
Right now it's using:
subprocess.check_output(['eu-readelf', '-n', filename]).split()[-1]
I was wondering is there's a more pythony way to achieve the same result?
Thanks, Alex.
| [
"Calling the eu-readelf command from python, as you have done, is the most elegant and readable approach. Since python stresses readability, I'd say this is the most Pythonic approach.\n"
] | [
2
] | [] | [] | [
"build",
"elf",
"python"
] | stackoverflow_0007744795_build_elf_python.txt |
Q:
Can't get filter to work for querying datastore in Google App Engine (Python)
Not sure what's going wrong. I'm trying to query a simple string in a datastore, but the query always comes out empty.
models.py:
from google.appengine.ext import db
from google.appengine.api import datastore_types
class Post(db.Model)... | Can't get filter to work for querying datastore in Google App Engine (Python) | Not sure what's going wrong. I'm trying to query a simple string in a datastore, but the query always comes out empty.
models.py:
from google.appengine.ext import db
from google.appengine.api import datastore_types
class Post(db.Model):
author = db.TextProperty()
title = db.TextProperty()
slug = db.TextPr... | [
"TextPropertys are not indexed, and can't be filtered on. Use StringProperty if you need an index.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007746604_google_app_engine_python.txt |
Q:
Is Pro Django book still relevant?
I want to dig deeper into Django's internals and the official online documentation only goes so far toward that end.
The reviews for Marty Alchin's Pro Django are fantastic (I've read Pro Python and really enjoyed it). However, the book is from 2008 and is based on Django v1.0. ... | Is Pro Django book still relevant? | I want to dig deeper into Django's internals and the official online documentation only goes so far toward that end.
The reviews for Marty Alchin's Pro Django are fantastic (I've read Pro Python and really enjoyed it). However, the book is from 2008 and is based on Django v1.0. My company builds off v1.3.
Is this bo... | [
"It's not my place to speak about its worth or recommendations, but I wrote the book with Django 1.0 in mind precisely to make sure it stayed relevant as long as possible. The aspects of Django that I documented are still present and functional, and the general aspects of Python are also still valid. They may have ... | [
23,
8,
2
] | [] | [] | [
"django",
"metaprogramming",
"python"
] | stackoverflow_0007746344_django_metaprogramming_python.txt |
Q:
Greeting program
I have been learning how to program in Python using the book "Python the Absolute Beginners Guide." The problem I am having is that when using eclipse-pydev it won't allow me to use the if statement. Here is the code I have written...
name = input("What is your name? ")
print(name)
print("Hello" n... | Greeting program | I have been learning how to program in Python using the book "Python the Absolute Beginners Guide." The problem I am having is that when using eclipse-pydev it won't allow me to use the if statement. Here is the code I have written...
name = input("What is your name? ")
print(name)
print("Hello" name )
The result was ... | [
"Use raw_input instead of input.\nPython developers probably should have renamed those functions so it's more clear and beginners don't get confused so easily.\nWhen you type caleb into the prompt with input it's trying to evaluate caleb which looks like a variable. The variable caleb hasn't been defined, so it's r... | [
9,
4,
3
] | [] | [] | [
"eclipse",
"if_statement",
"new_operator",
"pydev",
"python"
] | stackoverflow_0007747871_eclipse_if_statement_new_operator_pydev_python.txt |
Q:
ImportError: couldn't find library
I am encountering these errors frequently when I install python libraries and I'm wondering what I am doing wrong
the current example is the libchromaprint library
http://acoustid.org/chromaprint
I install it and everything, try to run the python example, get:
Traceback (most... | ImportError: couldn't find library | I am encountering these errors frequently when I install python libraries and I'm wondering what I am doing wrong
the current example is the libchromaprint library
http://acoustid.org/chromaprint
I install it and everything, try to run the python example, get:
Traceback (most recent call last):
File "examples/fpw... | [
"Python does not use your usual library path. The chromaprint you're looking for should be somewhere like /usr/lib/pymodules/python2.6.\nFrom the python interpreter do:\n>>> import sys\n>>> sys.path\n\nThis will show you the directories python searches for a module.\n"
] | [
0
] | [] | [] | [
"python",
"shared_libraries"
] | stackoverflow_0007744471_python_shared_libraries.txt |
Q:
getters/setters for a python class that inherits dict
To aid in serializing to JSON, I commonly build a class that inherits from the python dict class. If the class is supposed to have specific fields, I want there to be methods to get & set.
Currently, I construct a class like:
class MyRequest(dict):
def __i... | getters/setters for a python class that inherits dict | To aid in serializing to JSON, I commonly build a class that inherits from the python dict class. If the class is supposed to have specific fields, I want there to be methods to get & set.
Currently, I construct a class like:
class MyRequest(dict):
def __init__(self, firstName=None, lastName=None):
self['f... | [
"How about:\nclass MyRequest(dict):\n def __init__(self, firstName=None, lastName=None):\n self['firstName'] = firstName\n self['lastName'] = lastName\n\n def __getattr__(self, name):\n return self[name]\n\n def __setattr__(self, name, value):\n self[name] = value\n\nNote that t... | [
2,
1
] | [] | [] | [
"dictionary",
"getter_setter",
"python"
] | stackoverflow_0007747952_dictionary_getter_setter_python.txt |
Q:
Python XLWT: Write a list into a cell
I am trying to write a list into a cell using Python XLWT. Is this possible?
I am currently getting an error:
Exception: Unexpected data type <type 'list'>
The code:
for x in result:
sheet1.write(row2,0,x[0])
sheet1.write(row2,1,x[1])
x[1] will be a list.... | Python XLWT: Write a list into a cell | I am trying to write a list into a cell using Python XLWT. Is this possible?
I am currently getting an error:
Exception: Unexpected data type <type 'list'>
The code:
for x in result:
sheet1.write(row2,0,x[0])
sheet1.write(row2,1,x[1])
x[1] will be a list.
Thanks!
| [
"Try converting it to a string first:\nfor x in result:\n sheet1.write(row2,0,str(x[0]))\n sheet1.write(row2,1,str(x[1]))\n\n"
] | [
5
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0007747997_python_xlwt.txt |
Q:
Using CherryPy with Routes dispatching
I'm trying to switch a CherryPy application from standard CherryPy dispatching to RoutesDispatcher.
The following python code routes /correctly using standard CherryPy dispatching. My goal is to convert this same code to run using RoutesDispatcher. I've flailed around with ... | Using CherryPy with Routes dispatching | I'm trying to switch a CherryPy application from standard CherryPy dispatching to RoutesDispatcher.
The following python code routes /correctly using standard CherryPy dispatching. My goal is to convert this same code to run using RoutesDispatcher. I've flailed around with snippets I've found but have not been able t... | [
"Here is the code that I eventually got working. Changes I needed to make that were not immediately obvious to me:\n\nI had to move my configuration from a file to a dictionary so that I could add the dispatcher to it.\nI had to include a call to cherrypy.mount before cherrypy.quickstart.\nI had to include dispatc... | [
5
] | [] | [] | [
"cherrypy",
"python",
"routes"
] | stackoverflow_0007656286_cherrypy_python_routes.txt |
Q:
Making a list of all sublists of a list, starting from the beginning of the original list
For example, if x is [1,2,3,4] then
my program returns
[ [], [1], [1,2], [1,2,3], [1,2,3,4] ]
A:
That would be:
[x[:i] for i in range(len(x) + 1)]
A:
x = [1, 2, 3, 4]
print [x[:i] for i in xrange(len(x) + 1)]
... | Making a list of all sublists of a list, starting from the beginning of the original list | For example, if x is [1,2,3,4] then
my program returns
[ [], [1], [1,2], [1,2,3], [1,2,3,4] ]
| [
"That would be:\n[x[:i] for i in range(len(x) + 1)]\n\n",
"x = [1, 2, 3, 4]\nprint [x[:i] for i in xrange(len(x) + 1)]\n\n"
] | [
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0007748318_python.txt |
Q:
Running command with browser
I want to have a "control panel" on a website, and when a button is pressed, I want it to run a command on the server (my computer). The panel is to run different python scripts I wrote (one script for each button), and I want to run the panel on my Mac, my iPod touch, and my wii. Th... | Running command with browser | I want to have a "control panel" on a website, and when a button is pressed, I want it to run a command on the server (my computer). The panel is to run different python scripts I wrote (one script for each button), and I want to run the panel on my Mac, my iPod touch, and my wii. The best way I see for this is a web... | [
"Here are three options:\n\nHave each button submit a form with the name of the script in a hidden field. The server will receive the form parameters and can then branch off to run the appropriate script.\nHave each button hooked to it's own unique URL and use javascript on the button click to just set window.loca... | [
0,
0,
0
] | [] | [] | [
"controls",
"javascript",
"macos",
"python",
"unix"
] | stackoverflow_0007747852_controls_javascript_macos_python_unix.txt |
Q:
Python - Running a function but the number isnt decreased when told to
I have a function which defines a number, than determines what the last digit is, and than does a formula based on the last number, UNTIL the number reaches '1'
YES this is project Euler Problem 14
after the function runs, the original number i... | Python - Running a function but the number isnt decreased when told to | I have a function which defines a number, than determines what the last digit is, and than does a formula based on the last number, UNTIL the number reaches '1'
YES this is project Euler Problem 14
after the function runs, the original number is to be decreased by 1
and then the function is to be run again.
i already r... | [
"Local variables don't exist outside of their enclosing function. Every time you call this function you're getting a whole new variable number, value and count and your assignments are all run again.\nIf you want variables that outlive your function two options are to make them globals or to make the function a met... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007748464_python.txt |
Q:
Is there anyone familiar with Plurk API?
I try to fetch some data from Plurk using its "search" function.
http://www.plurk.com/API#search
I know I have to provide my app key and app secret, so I registered for my application.
But after I read official document:
http://www.plurk.com/API
and Python library it provid... | Is there anyone familiar with Plurk API? | I try to fetch some data from Plurk using its "search" function.
http://www.plurk.com/API#search
I know I have to provide my app key and app secret, so I registered for my application.
But after I read official document:
http://www.plurk.com/API
and Python library it provides:
https://github.com/clsung/plurk-oauth
I st... | [
"Finally, I got the answer by myself.\nTo setup the Plurk API, first you need \"Python setuptool\"(google it, and then download it)\nafterwards, move to the directory where Plurk API placed under cmd mode, then type 'python setup.py'\nnotice that you need install Python 2.6+ to install the Python setuptool\nand her... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007219624_python.txt |
Q:
List Comprehension for removing duplicates of characters in a string
Possible Duplicate:
How do you remove duplicates from a list whilst preserving order?
So the idea is the program takes a string of characters and removes the same
string with any duplicated character only appearing
onc... | List Comprehension for removing duplicates of characters in a string |
Possible Duplicate:
How do you remove duplicates from a list whilst preserving order?
So the idea is the program takes a string of characters and removes the same
string with any duplicated character only appearing
once -- removing any duplicated copy of a character.
So Iowa stays Iowa but ... | [
"Here is an inefficient method:\nx = 'eventually'\nnewx = ''.join([c for i,c in enumerate(x) if c not in x[:i]])\n\nI don't think that there is an efficient way to do it in a list comprehension.\n",
"Here it is as an O(n) (average case) generator expression. The others are all roughly O(n2).\nchars = set()\nstrin... | [
3,
3,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007748834_python.txt |
Q:
Maximum number of TCP connections in Python?
I am working in Python on localhost. I wrote a raw server just read TCP socket, say in port 50001.
Then I tried max client connections:
def rawMultiConn(threadnum = 10000):
g_event = threading.Event()
def threadfn():
sockets = [socket.socket(socket.AF_I... | Maximum number of TCP connections in Python? | I am working in Python on localhost. I wrote a raw server just read TCP socket, say in port 50001.
Then I tried max client connections:
def rawMultiConn(threadnum = 10000):
g_event = threading.Event()
def threadfn():
sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for i ... | [
"Check the ulimit and quota for the box and the user running the script. /etc/security/limits.conf may also contain resource restrictions that you might want to modify. \nTry running ulimit -s unlimited.\nAlso, ulimit -n will show the max number of open file descriptors/sockets allowed. That may need modificatio... | [
3
] | [] | [] | [
"connection",
"python",
"tcp"
] | stackoverflow_0007748898_connection_python_tcp.txt |
Q:
How to make a function that counts how many times each element is equal to 2 elements to its right
I know i need to use a list comprehension but for the life of me I cannot figure out what would be the correct way to denote this. An example of this running right would be for "evening" the output being 2, once
... | How to make a function that counts how many times each element is equal to 2 elements to its right | I know i need to use a list comprehension but for the life of me I cannot figure out what would be the correct way to denote this. An example of this running right would be for "evening" the output being 2, once
for 'e' and once for 'n'
| [
"The list comprehension gives the letters that have the same letter two places to the right. We simply take the length of the resulting list:\ns = \"evening\"\nans = len([x for x in xrange(len(s)-2) if s[x] == s[x+2]])\nprint ans\n\n",
"s='evening'\nprint len([x for x,y in zip(s, s[2:]) if x==y])\n\nOutput:\n2\n\... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007748587_python.txt |
Q:
mod_wsgi on Snow Leopard python version mismatch
I'm trying to run mod_wsgi 3.1 under Apache 2.2.14 using a non-default python installation on Mac OS X 10.6.
After downloading the mod_wsgi source I run:
sudo apachectl -k stop
then
./configure --with-python=/usr/local/Cellar/python/2.6.4/bin/python
make
sudo make ... | mod_wsgi on Snow Leopard python version mismatch | I'm trying to run mod_wsgi 3.1 under Apache 2.2.14 using a non-default python installation on Mac OS X 10.6.
After downloading the mod_wsgi source I run:
sudo apachectl -k stop
then
./configure --with-python=/usr/local/Cellar/python/2.6.4/bin/python
make
sudo make install
I then start up apache again
sudo apachectl -... | [
"This post is old, but still turns up in searches about mac + homebrew + python, so I thought I'd add some useful information. I was having the problem as the OP, just with a different module (uwsgi). I learned that you don't have to abandon homebrew. Homebrew can, in fact, install python as a framework; you just h... | [
2,
0,
0
] | [] | [] | [
"apache",
"makefile",
"mod_wsgi",
"python"
] | stackoverflow_0001942462_apache_makefile_mod_wsgi_python.txt |
Q:
Aide with error when trying to get email poplib
This what ive tried so far :
# view and delete e-mail using the POP3 protocol
import sys, getpass, poplib, re
# change according to your needs
POPHOST = "pop3.126.com"
POPUSER = "Username"
POPPASS = "pass"
# the number of message body lines to retrieve
MAXLINES = ... | Aide with error when trying to get email poplib | This what ive tried so far :
# view and delete e-mail using the POP3 protocol
import sys, getpass, poplib, re
# change according to your needs
POPHOST = "pop3.126.com"
POPUSER = "Username"
POPPASS = "pass"
# the number of message body lines to retrieve
MAXLINES = 10
HEADERS = "From To Subject".split()
# headers you... | [
"i have found code that works...here it is:\nimport poplib\n\nM = poplib.POP3_SSL('pop3.live.com', 995) #Connect to hotmail pop3 server\nM.set_debuglevel(2)\nsuccess = False;\nuser = \"email@hotmail.com\"\n\nwhile success == False:\n try:\n password = raw_input(\"password: \")\n M.user(user)\n ... | [
1
] | [] | [] | [
"email",
"poplib",
"python"
] | stackoverflow_0007734837_email_poplib_python.txt |
Q:
Can I variabalize an object like a dictionary reference in python
I have a series of dictionaries that hold values that I want to combine at the end . The combination is messy so I can't just combine the dictionaries I have to work based on keys and make some careful choices. When I created the dictionaries I cr... | Can I variabalize an object like a dictionary reference in python | I have a series of dictionaries that hold values that I want to combine at the end . The combination is messy so I can't just combine the dictionaries I have to work based on keys and make some careful choices. When I created the dictionaries I created them in the form item#Dict expecting to do something like
for va... | [
"You can use the locals function to get a dictionary containing variables in the current local scope:\n>>> var0 = 7\n>>> var1 = 3\n>>> var2 = 4\n>>> var3 = 5\n>>> for i in range(4):\n... print 'var', i, 'is', locals()['var%d' % i]\n... \nvar 0 is 7\nvar 1 is 3\nvar 2 is 4\nvar 3 is 5\n\nAlthough, I don't really ... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"python",
"variable_assignment"
] | stackoverflow_0007748596_dictionary_python_variable_assignment.txt |
Q:
3D/4D graphics with Python and wxPython?
In my day job as a PhD student, I do geological modeling. In my spare time (mainly for fun), I am learning Python and trying to write a simple program to view 3D geocellular models.
geological model http://img710.imageshack.us/img710/6503/sgems.png
The geocellular model is... | 3D/4D graphics with Python and wxPython? | In my day job as a PhD student, I do geological modeling. In my spare time (mainly for fun), I am learning Python and trying to write a simple program to view 3D geocellular models.
geological model http://img710.imageshack.us/img710/6503/sgems.png
The geocellular model is just a 3D grid where every grid cell has some... | [
"What you are looking for is called voxel visualization, voxel grid or such. I would seriously consider MayaVi (never used it, but I keep eye on it), it seems to have something very close here.\nParaview, built atop VTK just like MayaVi, might be a good option, too.\nI think going straight to VTK for visualization ... | [
13,
10,
7,
3,
1
] | [] | [] | [
"3d",
"graphics",
"python",
"vtk",
"wxpython"
] | stackoverflow_0007694692_3d_graphics_python_vtk_wxpython.txt |
Q:
Optimization of color inversion - Python Tkinter library
I attempted today to create a Python code to invert the colors of a .gif image using the Tkinter library. The code works and does exactly what I expected, but it takes about 50 seconds to run on a 3.4ghz processor. I'm having trouble seeing what I could chan... | Optimization of color inversion - Python Tkinter library | I attempted today to create a Python code to invert the colors of a .gif image using the Tkinter library. The code works and does exactly what I expected, but it takes about 50 seconds to run on a 3.4ghz processor. I'm having trouble seeing what I could change to optimize this. Basically, I loop through every pixel in ... | [
"Try this:\ndef Display(self):\n self.imageDisplay = PhotoImage(file='C:\\image.gif')\n for x in xrange(0, self.imageDisplay.width()):\n for y in xrange(0, self.imageDisplay.height()):\n raw = self.imageDisplay.get(x, y)\n rgb = tuple(255 - int(component) for component in raw.spli... | [
4
] | [] | [] | [
"colors",
"gif",
"inversion",
"python",
"tkinter"
] | stackoverflow_0007749435_colors_gif_inversion_python_tkinter.txt |
Q:
PyArray_BOOL declaration & working with Numpy array of bools in C extension
I have a NumPy array of bools in my code that I wish to write a C extension to.
When I try to get a contiguous array in order to use in my C routine, I use:
arr_mask = (PyArrayObject *)
PyArray_ContiguousFromObject(mask, PyArray_BOOL, ... | PyArray_BOOL declaration & working with Numpy array of bools in C extension | I have a NumPy array of bools in my code that I wish to write a C extension to.
When I try to get a contiguous array in order to use in my C routine, I use:
arr_mask = (PyArrayObject *)
PyArray_ContiguousFromObject(mask, PyArray_BOOL, 2, 2);
But I get the compiler error that PyArray_BOOL is not declared.
xor_mask... | [
"You need to use NPY_BOOL rather than PyArray_BOOL. Also, you will need to be using the numpy header rather than the numeric header if you are still using the numeric header like in one of your other questions.\n"
] | [
1
] | [] | [] | [
"numpy",
"python",
"python_c_api"
] | stackoverflow_0007743656_numpy_python_python_c_api.txt |
Q:
a StringIO like class, that extends django.core.files.File
class MyModel(models.Model)
image = models.FileField(upload_to="blagh blagh...")
#more spam...
I have a file in memory and I want to save it via Django FileField save method, like this:
photo.image.save(name, buffer) # second arg should be django File
... | a StringIO like class, that extends django.core.files.File | class MyModel(models.Model)
image = models.FileField(upload_to="blagh blagh...")
#more spam...
I have a file in memory and I want to save it via Django FileField save method, like this:
photo.image.save(name, buffer) # second arg should be django File
I've tried to use StringIO, but it doesn't extend django.core.fi... | [
"You can use ContentFile instead of File\nfrom django.core.files.base import ContentFile\n\nphoto.image.save(name, ContentFile(buffer))\n\n",
"If you've got a stream of bytes, which you'd like to save to a FileField/ImageField, here's some code that might help:\n>>> from django.core.files.uploadedfile import InMe... | [
34,
8,
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003330677_django_python.txt |
Q:
Is it possible to write code for login functionality without using django's authenticate & login method?
Till now I have used django's default authenticate and login method for login code for my project.See the code below,
"my login code"
def login(request):
if request.method == 'POST':
username = requ... | Is it possible to write code for login functionality without using django's authenticate & login method? | Till now I have used django's default authenticate and login method for login code for my project.See the code below,
"my login code"
def login(request):
if request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
if(len(username.strip... | [
"Simple answer: of course you can write your own. This module is just that a python module that is built for you to use without a lot of work.\nReal answer: they do probably everything that you want and more already and the whole philosophy of Django is DRY (Don't Repeat Yourself), so if it is built-in and can hand... | [
1
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0007749726_authentication_django_python.txt |
Q:
How to annotate all the objects with a new property?
class Author(Model):
state = models.CharField('ST')
class Essay(Model):
authors = models.ManyToManyField("Author",
through='EssayAuthor')
>> mylist
[ <Essay: A1>, <Essay: B4>, <Essay: C9>, <Essay: A3> ... ]
mylist is a QuerySet.
I want to add... | How to annotate all the objects with a new property? | class Author(Model):
state = models.CharField('ST')
class Essay(Model):
authors = models.ManyToManyField("Author",
through='EssayAuthor')
>> mylist
[ <Essay: A1>, <Essay: B4>, <Essay: C9>, <Essay: A3> ... ]
mylist is a QuerySet.
I want to add another property to each instances of Essay in mylist wit... | [
"Could you just do this in your model class?\nclass Essay(Model):\n authors = models.ManyToManyField(\"Author\",\n through='EssayAuthor')\n\n @property\n def state(self):\n if self.authors.count():\n return self.authors[0].state\n else:\n return null\n\nI don't th... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007749430_django_python.txt |
Q:
wxPython ListCtrl : write Colored text
Trying to write string to a ListCtrl , I don't understand the logic completely. Is this the proper way?
self.rightPanel = wx.ListCtrl(spliter, -1, style=wx.LC_REPORT)
self.rightPanel.InsertColumn(0, 'LineNumber')
self.rightPanel.InsertColumn(1, 'log')
self.rig... | wxPython ListCtrl : write Colored text | Trying to write string to a ListCtrl , I don't understand the logic completely. Is this the proper way?
self.rightPanel = wx.ListCtrl(spliter, -1, style=wx.LC_REPORT)
self.rightPanel.InsertColumn(0, 'LineNumber')
self.rightPanel.InsertColumn(1, 'log')
self.rightPanel.SetColumnWidth(0, 8)
self.rightP... | [
"SetTextColour() and SetBackgroundColour() are methods of the entire listctrl, not of items.\nFor items you should use (valid only for report mode): \nGetItemTextColour(idx_item)\nSetItemTextColour(idx_item, col)\n\nInsertItem(index, item) (item here is an instance of wx.ListItem) is one of the InsertItem() methods... | [
5
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007748371_python_wxpython.txt |
Q:
invalid syntax - python
I have a set of arguments and all of their dest is 'search_and', 'search_not', 'search_start', 'search_then', and 'filename'
The code that I have to catch the error is
if ( options.filename is None) and ( (options.search_and is None) or (options.search_not is None) or (options.search_s... | invalid syntax - python | I have a set of arguments and all of their dest is 'search_and', 'search_not', 'search_start', 'search_then', and 'filename'
The code that I have to catch the error is
if ( options.filename is None) and ( (options.search_and is None) or (options.search_not is None) or (options.search_start is None) or (options.sea... | [
"The line before the if statement\nparser.add_option(\"-f\", \"--file\", type=\"string\", dest=\"filename\", help=\"file name\"\n\ndoes not have a closing ).\nPython interpreter usually complains about such syntax errors in next line.So, if you get a syntax error at any line, it is advisable to check the preceding ... | [
4,
1,
0,
0,
0
] | [] | [] | [
"if_statement",
"python",
"syntax"
] | stackoverflow_0007749591_if_statement_python_syntax.txt |
Q:
How to debug in this simple Python homework?
I need a little bit of help with a homework problem for school using python. The prompt is pretty simple, but I can't seem to figure it out.
'''
rem(A,B) returns the list
[A[0]%B[0], A[1]%B[1], ...] etc
>>> rem( (10,20,30), (7,8,9) )
[3, 4, 3]
>>> X = ... | How to debug in this simple Python homework? | I need a little bit of help with a homework problem for school using python. The prompt is pretty simple, but I can't seem to figure it out.
'''
rem(A,B) returns the list
[A[0]%B[0], A[1]%B[1], ...] etc
>>> rem( (10,20,30), (7,8,9) )
[3, 4, 3]
>>> X = [ i for i in range(10,18) ]
>>> Y = [ j+3 for j i... | [
"You need to pair up each element of A with its corresponding element in B, and then mod them.\n[x % y for (x, y) in zip(A, B)]\n\n",
"Ignacio's answer is correct and the most pythonic, this is the more basic way:\ndef rem(a,b):\n l = []\n for x in range(len(a)):\n l.append(a[x]%b[x])\n return l\... | [
5,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0007750028_list_comprehension_python.txt |
Q:
add method to loaded class/module in python
if I have something like
import mynewclass
Can I add some method to mynewclass? Something like the following in concept:
def newmethod(self,x):
return x + self.y
mynewclass.newmethod = newmethod
(I am using CPython 2.6)
A:
In Python the import statement is used ... | add method to loaded class/module in python | if I have something like
import mynewclass
Can I add some method to mynewclass? Something like the following in concept:
def newmethod(self,x):
return x + self.y
mynewclass.newmethod = newmethod
(I am using CPython 2.6)
| [
"In Python the import statement is used for modules, not classes... so to import a class you need something like\nfrom mymodule import MyClass\n\nMore to the point of your question the answer is yes. In Python classes are just regular objects and a class method is just a function stored in an object attribute.\nAtt... | [
39,
6
] | [] | [] | [
"python"
] | stackoverflow_0007749914_python.txt |
Q:
Is it possible to use a web page as a user interface to a program written in python, running locally, without a web server?
I have a program written in python, and I would like to make it easy to enter parameter values for this program through a GUI. I realise that I could create a GUI using python tools, but I am... | Is it possible to use a web page as a user interface to a program written in python, running locally, without a web server? | I have a program written in python, and I would like to make it easy to enter parameter values for this program through a GUI. I realise that I could create a GUI using python tools, but I am interested in using a html / javascript page and have the javascript code call my python script when the user clicks a button to... | [
"First of all, using something like bottle it is pretty simple to make a web server to run your script. Look at http://bottlepy.org/docs/dev/\nA good starting point is the code at http://bottlepy.org/docs/dev/tutorial.html#http-request-methods but you would put up a form asking for parameters rather than a login fo... | [
0,
0
] | [] | [] | [
"embedded_server",
"javascript",
"local",
"python"
] | stackoverflow_0007750821_embedded_server_javascript_local_python.txt |
Q:
How to get similar projects based on tags in Django
I have Project and Tag models in my application with a many-to-many relationship between them. On each project's page I want to list 3 additional projects that have the most tags in common with it. How can I perform this query?
class Tag(models.Model):
name = m... | How to get similar projects based on tags in Django | I have Project and Tag models in my application with a many-to-many relationship between them. On each project's page I want to list 3 additional projects that have the most tags in common with it. How can I perform this query?
class Tag(models.Model):
name = models.CharField(max_length=300)
class Project(models.Mod... | [
"It is possible to pack it all in one line:\nProject.objects.filter(tags__in=current_project.tags.all()).annotate(Count('name')).order_by('-name__count')[:3]\n\nOr, broken down in steps:\ntags = current_project.tags.all()\nmatches = Project.objects.filter(tags__in=tags).annotate(Count('name'))\nresults = matches.or... | [
4
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0007750232_django_django_orm_python.txt |
Q:
Using a dict subclass where dict is expected
Function A gets an ordinary dict as argument and does some processing.
def A(dict):
...
return
Now I have a class inherited from ordinary dict class:
class MyDict(dict):
def __getitem__(self, key):
return dict.__getitem__(self, key)
def __setite... | Using a dict subclass where dict is expected | Function A gets an ordinary dict as argument and does some processing.
def A(dict):
...
return
Now I have a class inherited from ordinary dict class:
class MyDict(dict):
def __getitem__(self, key):
return dict.__getitem__(self, key)
def __setitem__(self, key, val):
dict.__setitem__(self... | [
"That completely depends on what A() does. If it merely invokes the mapping protocol then you can use it no problem. If it requires more details about the type passed then there is a chance that it will fail to run correctly.\n"
] | [
2
] | [] | [] | [
"inheritance",
"polymorphism",
"python",
"xml_rpc"
] | stackoverflow_0007750959_inheritance_polymorphism_python_xml_rpc.txt |
Q:
Why doesn't id()'s result on IronPython equal to id()'s result on Python?
I really confuse that a behavior of id() function on IronPython who differ from Python. Let me show you the following code,
In IronPython:
>> s = "hello"
>> a = len(s)
>> id(a)
44
>> a = len(s)
>> id(a)
45
As you can see that, id()'s result... | Why doesn't id()'s result on IronPython equal to id()'s result on Python? | I really confuse that a behavior of id() function on IronPython who differ from Python. Let me show you the following code,
In IronPython:
>> s = "hello"
>> a = len(s)
>> id(a)
44
>> a = len(s)
>> id(a)
45
As you can see that, id()'s result is changed in every calls. In Python, however, not be changed.
In Python:
>> s... | [
"CPython has a cache of constant small integers that are used whenever needed. This pool of integers is an optimisation and improves the performance because a new object does not need to be allocated for every small integer as needed. Evidently IronPython handles this differently.\nThat said, the id() function retu... | [
2,
1
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0007751132_ironpython_python.txt |
Q:
PYTHON Add the contents of a string variable to the beginning of a function?
So what I have here is one function, which is in an object:
class objectOne:
def funct1(self):
#Do Stuff
And what I would like to do is have it so when I create two instaces of the object:
dog = objectOne()
cat = objectOne... | PYTHON Add the contents of a string variable to the beginning of a function? | So what I have here is one function, which is in an object:
class objectOne:
def funct1(self):
#Do Stuff
And what I would like to do is have it so when I create two instaces of the object:
dog = objectOne()
cat = objectOne()
When the variable "animal" i have created contains cat, then it would run:
cat... | [
"Use dictionary. Animals will be keys, objects will be items.\nExample:\nanimals = {}\nanimals['cat'] = objectOne()\nanimal = 'cat'\nanimals[animal].funct1()\n\n"
] | [
2
] | [] | [] | [
"function",
"object",
"python",
"variables"
] | stackoverflow_0007751424_function_object_python_variables.txt |
Q:
How to use listen on basic.return in python client of AMQP
I'd like to make sure that my message was delivered to a queue.
To do so I'm adding the mandatory param to the basic_publish.
What else should I do to receive the basic.return message if my message wasn't successfully delivered?
I can't use channel.wait()... | How to use listen on basic.return in python client of AMQP | I'd like to make sure that my message was delivered to a queue.
To do so I'm adding the mandatory param to the basic_publish.
What else should I do to receive the basic.return message if my message wasn't successfully delivered?
I can't use channel.wait() to listen for the basic.return because when my message is succe... | [
"It is currently impossible as the basic.return is sent asynchronously when a message is dropped in broker. When message was sent successfully no data is reported from server.\nSo pyAMQP can't listen for such messages.\nI've read few threads about this problem. Possible solution were:\n\nuse txAMQP, twisted version... | [
1,
1,
1
] | [] | [] | [
"amqp",
"py_amqplib",
"python",
"rabbitmq"
] | stackoverflow_0002191695_amqp_py_amqplib_python_rabbitmq.txt |
Q:
python filename=None
I'm new to Python. I heard that when we initialize a function we should always start by self but I didn't get the fileName=None. What does this argument stand for?
def __init__(self, fileName=None):
A:
It is a default value for the parameter fileName. If the caller does not specify a value, ... | python filename=None | I'm new to Python. I heard that when we initialize a function we should always start by self but I didn't get the fileName=None. What does this argument stand for?
def __init__(self, fileName=None):
| [
"It is a default value for the parameter fileName. If the caller does not specify a value, it will be set to None. This code demonstrates it:\ndef foo(bar=None):\n print bar\n\nfoo() # will print the default value\n>> None\nfoo(1) # will print the given value\n>> 1\n\nNote that default parameter values in Python... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007751751_python.txt |
Q:
The same method for class and instance
I have class Books and method select in it. Also there is an instance of that class called book. I want to be able to do both Books.select(where='...') and book.select(where='...'):
class Books():
def select(obj, where):
print(obj, where)
book = Books()
Books.sel... | The same method for class and instance | I have class Books and method select in it. Also there is an instance of that class called book. I want to be able to do both Books.select(where='...') and book.select(where='...'):
class Books():
def select(obj, where):
print(obj, where)
book = Books()
Books.select(where='asdf')
book.select(where='asdf')
... | [
"You could use a descriptor:\nclass Select(object):\n def __get__(self,obj,objtype):\n x=objtype if obj is None else obj\n def select(where):\n print(x,where)\n return select\nclass Books(object):\n select=Select()\n\nbook = Books()\nBooks.select(where='asdf')\nbook.select(wher... | [
3,
2,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0007750896_python_python_3.x.txt |
Q:
Discrete Fourier Transform: How to use fftshift correctly with fft
I want numerically compute the FFT on a numpy array Y. For testing, I'm using the Gaussian function Y = exp(-x^2). The (symbolic) Fourier Transform is Y' = constant * exp(-k^2/4).
import numpy
X = numpy.arange(-100,100)
Y = numpy.exp(-(X/5.0)**2)
... | Discrete Fourier Transform: How to use fftshift correctly with fft | I want numerically compute the FFT on a numpy array Y. For testing, I'm using the Gaussian function Y = exp(-x^2). The (symbolic) Fourier Transform is Y' = constant * exp(-k^2/4).
import numpy
X = numpy.arange(-100,100)
Y = numpy.exp(-(X/5.0)**2)
The naive approach fails:
from numpy.fft import *
from matplotlib impor... | [
"The FFT can be thought of as producing a set vectors each with an amplitude and phase. The fft_shift operation changes the reference point for a phase angle of zero, from the edge of the FFT aperture, to the center of the original input data vector.\nThe phase (and thus the real component of the complex vector) o... | [
4,
3
] | [] | [] | [
"fft",
"numpy",
"python"
] | stackoverflow_0007743769_fft_numpy_python.txt |
Q:
Temporarily stop a for control flow
for i in liste:
inp = input('Skriv et tall mellom 0 og 3 ')
if inp > (len(i)-1):
print 'HOOOOORE'
elif i[inp] == 'T':
print 'Du er videre til neste rom'
print 'Du er naa i rom ' + str(j)
j = j + 1
elif i[inp] == 'B':
print ... | Temporarily stop a for control flow | for i in liste:
inp = input('Skriv et tall mellom 0 og 3 ')
if inp > (len(i)-1):
print 'HOOOOORE'
elif i[inp] == 'T':
print 'Du er videre til neste rom'
print 'Du er naa i rom ' + str(j)
j = j + 1
elif i[inp] == 'B':
print 'Du falt i et bunnlost hull og er na do'
... | [
"What really solves you problem is to put that input() into a while, and use raw_input() instead:\nfor i in liste:\n inp = raw_input('Skriv et tall mellom 0 og 3 ')\n while inp > (len(i)-1):\n inp = raw_input('Skriv et tall mellom 0 og 3 ') # you may want to change the text here\n if i[inp] == 'T':\... | [
1,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0007751615_python_python_2.7.txt |
Q:
Complete control of a user profile through Open Graph
I'm attempting to design a program, in Python, to interact with facebook using my profile. I'd like to have my program be able to write to walls, send personal messages, like things, etc... using my profile.
I've created an app and written on my own wall. BUt ... | Complete control of a user profile through Open Graph | I'm attempting to design a program, in Python, to interact with facebook using my profile. I'd like to have my program be able to write to walls, send personal messages, like things, etc... using my profile.
I've created an app and written on my own wall. BUt i was only able to do that because i gave the app permissio... | [
"It is possible for a user, using an app, to write on someone else's wall.\nIf you have the 'stream_publish' permission, you can POST to \nhttp://graph.facebook.com/FRIEND_ID/feed?message=SOME_MESSAGE&access_token=TOKEN\n\nHowever, you must be careful not to spam people's walls or do this without the user's permiss... | [
0
] | [] | [] | [
"facebook",
"facebook_opengraph",
"python"
] | stackoverflow_0007748696_facebook_facebook_opengraph_python.txt |
Q:
Is there a way to identify an inherited method in Python?
I want to tell inherited methods apart from overloaded or newly defined methods. Is that possible with Python?
Example:
class A(object):
def spam(self):
print 'A spam'
def ham(self):
print 'A ham'
class B(A):
def spam(self):
print 'Overlo... | Is there a way to identify an inherited method in Python? | I want to tell inherited methods apart from overloaded or newly defined methods. Is that possible with Python?
Example:
class A(object):
def spam(self):
print 'A spam'
def ham(self):
print 'A ham'
class B(A):
def spam(self):
print 'Overloaded spam'
def eggs(self):
print 'Newly defined eggs'
De... | [
"I'm not sure it's a good idea, but you can probably do it by using hasattr and __dict__.\ndef magicmethod(clazz, method):\n if method not in clazz.__dict__: # Not defined in clazz : inherited\n return 'inherited'\n elif hasattr(super(clazz), method): # Present in parent : overloaded\n return ... | [
20,
8,
6,
2,
1
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0007751930_inheritance_python.txt |
Q:
Django e-commerce 1.2, missing settings.py file
I'm reading the Django 1.2 e-commerce book by Jesse Legg.
I have used Django before and had no problems doing the usual basic stuff (admin apps etc).
However I'm stumped on this one.
Near the bottom of Page 17 it says:
"""
we will create our settings file and a root ... | Django e-commerce 1.2, missing settings.py file | I'm reading the Django 1.2 e-commerce book by Jesse Legg.
I have used Django before and had no problems doing the usual basic stuff (admin apps etc).
However I'm stumped on this one.
Near the bottom of Page 17 it says:
"""
we will create our settings file and a root URLs file in our project module:
ecommerce_book/setti... | [
"python django-admin.py startproject ecommerce_book\n\nThough I'm not sure this initial settings.py will be the same you want. To the praticular settings.py contact authors or publishing.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007752134_django_python.txt |
Q:
how to switch from posix to windows with cygwin
im writing a python script that is being executed in cygwin. one of the things its doing is calling pg_dump and passing it a file name. my problem, python/cygwin is passing it a posix path and the windows version of pg_dump doesn't know what to do with it. is ther... | how to switch from posix to windows with cygwin | im writing a python script that is being executed in cygwin. one of the things its doing is calling pg_dump and passing it a file name. my problem, python/cygwin is passing it a posix path and the windows version of pg_dump doesn't know what to do with it. is there something that i can call to convert my posix path ... | [
"cygpath -w\n\nYou can read the manual page for more switches. Among them\n\n-w for windows\n-u for unix\n-a for absolute path\n\nYou need to be careful with escaping, make sure the path argument is a single shell word.\n",
"You can do the following:\n>>> posix_str = \"/cygdrive/c/Users/me/Code/myproj/pyBuildScri... | [
3,
1
] | [] | [] | [
"cygwin",
"python"
] | stackoverflow_0007752052_cygwin_python.txt |
Q:
Google App Engine, Does empty properties in datastore entities cost money
Google App Engine, Does empty properties in datastore entities cost money??
In 'Datastore Statistics' tab of my app's admin page
i get 'NULL 56 Bytes '
i guessed from the following docs that the empty properties will not use memory
"a gi... | Google App Engine, Does empty properties in datastore entities cost money | Google App Engine, Does empty properties in datastore entities cost money??
In 'Datastore Statistics' tab of my app's admin page
i get 'NULL 56 Bytes '
i guessed from the following docs that the empty properties will not use memory
"a given row in a Bigtable table may have different columns than any other row befor... | [
"Empty properties have to be stored as well, because the key exists, even if the value does not. There is a difference between an empty property and a non-existing property. \n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007752257_google_app_engine_python.txt |
Q:
How to assign names to automatic created class objects in Python
Let's say I have a class called "Map", and Map is constructed with argument "country". When instantiated Map should create a number of object of class "City", based upon a list of city names for country. But how do I name the "city" objects?
pseudoco... | How to assign names to automatic created class objects in Python | Let's say I have a class called "Map", and Map is constructed with argument "country". When instantiated Map should create a number of object of class "City", based upon a list of city names for country. But how do I name the "city" objects?
pseudocode:
class Map(object):
def __init__(self, country):
for i ... | [
"Again, as in my previous answer, I would put the objects in a dictionary. Advantage over creating them in a namespace is that they will be easier to maintain. I.e. if you would create them like you said, you would still need to know about them, probably by remembering their reference stored in list (or perhaps dic... | [
4,
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0007751610_oop_python.txt |
Q:
How to run fabric command in a certain environment
I defined different environments in my module :
__init__.py
def localdev():
"""
Work on local dev environment
"""
env.db_credentials = {'user':'username', 'pass':'passs','name':'mydb'}
env.uwsgi_command = 'uwsgi'
env.settings = 'local_dev'... | How to run fabric command in a certain environment | I defined different environments in my module :
__init__.py
def localdev():
"""
Work on local dev environment
"""
env.db_credentials = {'user':'username', 'pass':'passs','name':'mydb'}
env.uwsgi_command = 'uwsgi'
env.settings = 'local_dev'
env.hosts = ['dev@localhost']
dev production():
... | [
"You need to import init.py in fabfile.py. Arguments passed to fabric are used as function names in fabfile.py. As you don't import the module the function doesn't exist and so you get the command not found error.\n"
] | [
0
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0007752125_fabric_python.txt |
Q:
`Fatal Python error: PyThreadState_Get: no current thread` after `import cv´
I installed OpenCV via sudo brew install opencv.
Then I added PYTHONPATH* to my ~/.profile as brew info opencv says**. With env I checked that the path was loaded.
Now everytime I try to import cv, Python gives following error: Fatal P... | `Fatal Python error: PyThreadState_Get: no current thread` after `import cv´ | I installed OpenCV via sudo brew install opencv.
Then I added PYTHONPATH* to my ~/.profile as brew info opencv says**. With env I checked that the path was loaded.
Now everytime I try to import cv, Python gives following error: Fatal Python error: PyThreadState_Get: no current thread Abort trap.
What should I do?
*... | [
"cv 2.2 might well support it, but you MUST not mix versions like that. You must use the version built for 2.7 with 2.7, and the version built for 2.6 with 2.6\nI seem to think that cv is a python library that depends on a C library - in that case, you can not mix the libraries like that.\ncv will need to be re-com... | [
1
] | [] | [] | [
"homebrew",
"opencv",
"python"
] | stackoverflow_0007409272_homebrew_opencv_python.txt |
Q:
Python: load a UI from a separate file
G'day All,
I'm using tkinter for my GUI. Currently when I write an app most of the code is the interface widgets. I know how to import a file of defined functions and use them and I want to be able to "import" the UI. That way I can reuse the UI file and declutter the main... | Python: load a UI from a separate file | G'day All,
I'm using tkinter for my GUI. Currently when I write an app most of the code is the interface widgets. I know how to import a file of defined functions and use them and I want to be able to "import" the UI. That way I can reuse the UI file and declutter the main app.
The conceptual hurdle I'm facing is th... | [
"you could pass it as a parameter like import my_gui; my_gui.create(main); but for most situations I would recommend working the other way round -- have the GUI file be the file that you execute, and it imports the number-crunching functions from your core-functionality library\n",
"My recommendation is to not do... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007748557_python_tkinter.txt |
Q:
Floating Point Exception with Numpy and PyTables
I have a rather large HDF5 file generated by PyTables that I am attempting to read on a cluster. I am running into a problem with NumPy as I read in an individual chunk. Let's go with the example:
The total shape of the array within in the HDF5 file is,
In [13]: dat... | Floating Point Exception with Numpy and PyTables | I have a rather large HDF5 file generated by PyTables that I am attempting to read on a cluster. I am running into a problem with NumPy as I read in an individual chunk. Let's go with the example:
The total shape of the array within in the HDF5 file is,
In [13]: data.shape
Out[13]: (21933063, 800, 3)
Each entry in thi... | [
"Did you try to allocate such a big array before (like DaveP suggests)?\nIn [16]: N.empty((21000000,800,3))\n---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\n...\nValueError: array is too big.\n\nThis is on 32bi... | [
1
] | [] | [] | [
"hdf5",
"numpy",
"pytables",
"python"
] | stackoverflow_0007617142_hdf5_numpy_pytables_python.txt |
Q:
Python MySQLdb empty select query although manual query execution delivers results
I have written a python daemon that continuously polls a mysql database. It works fine when I continuously connect and reconnect to the database between queries as follows:
def connect(self):
self.connection = MySQLdb.connect(..... | Python MySQLdb empty select query although manual query execution delivers results | I have written a python daemon that continuously polls a mysql database. It works fine when I continuously connect and reconnect to the database between queries as follows:
def connect(self):
self.connection = MySQLdb.connect(...)
self.cursor = self.connection.cursor()
return self.cursor
def disconnect... | [
"You're probably querying an InnoDB table where another process inserts new data in the meantime. If that is the case, the MySQL sever automatically starts a new transaction for your connection, and since you don't call dbConnection.commit() or .rollback()anywhere, you're forever stuck in that transaction. InnoDB's... | [
9,
2
] | [] | [] | [
"daemon",
"mysql",
"python"
] | stackoverflow_0007752814_daemon_mysql_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.