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 do I find why a python scripts runs in significantly different running times on different machines?
The Facts:
I am working on a NoteBook with Intel Core 2 Duo 2,26 GHz and 4 Gigabyte of Ram.
It has a Apache Server and a MySQL Server running.
My Server (I did lshw | less) shows a 64 Bit CPU with 2,65 GHz and ... | How do I find why a python scripts runs in significantly different running times on different machines? | The Facts:
I am working on a NoteBook with Intel Core 2 Duo 2,26 GHz and 4 Gigabyte of Ram.
It has a Apache Server and a MySQL Server running.
My Server (I did lshw | less) shows a 64 Bit CPU with 2,65 GHz and 4 Gigabyte Ram, too. It has the XAMPP-Package running on it.
The Database structures (tables, indices, ...) a... | [
"What kind of server? If you're renting a VPS or similar you're contending with other users for CPU time.\nWhat platform is running on both? Tell us more about your situation!\n",
"I would check that the databases in question are of similar scope. You say they're the same structure, but are they sized similarly?... | [
2,
0
] | [] | [] | [
"mysql",
"python",
"runtime"
] | stackoverflow_0005944433_mysql_python_runtime.txt |
Q:
End of nonblocking file
How is end of file detected for a file in nonblocking mode?
A:
At least on POSIX (including Linux), the obvious answer is that nonblocking regular files don't exist. Regular files ALWAYS block, and O_NONBLOCK is silently ignored.
Similarly, poll()/select() et al. will always tell you tha... | End of nonblocking file | How is end of file detected for a file in nonblocking mode?
| [
"At least on POSIX (including Linux), the obvious answer is that nonblocking regular files don't exist. Regular files ALWAYS block, and O_NONBLOCK is silently ignored. \nSimilarly, poll()/select() et al. will always tell you that a fd pointing to a regular file is ready for I/O, regardless of whether the data is re... | [
15,
5,
1,
1,
1
] | [] | [] | [
"eof",
"file",
"nonblocking",
"python"
] | stackoverflow_0005648969_eof_file_nonblocking_python.txt |
Q:
Django: how to pass captured parameters in the url to extra parameters?
I remember reading somewhere that captured parameters in the url can be passed to extra parameters. For example:
url(r'^products/(?P<object_id>\d+)/$',
'someview',
{parameter: <object_id>},
name='someview'),
In this case, I want ... | Django: how to pass captured parameters in the url to extra parameters? | I remember reading somewhere that captured parameters in the url can be passed to extra parameters. For example:
url(r'^products/(?P<object_id>\d+)/$',
'someview',
{parameter: <object_id>},
name='someview'),
In this case, I want to pass object_id into the extra parameters. Can I do that? I simply can't re... | [
"Here is an example: \nurl(\n (r'^(?P<base62_id>\\w+)$', 'shortener.views.follow'),\n}\n\n... \nThe view can access it as:\ndef follow(request, base62_id):\n\n",
"Extra parameters are just that: extra. You don't have to \"pass in\" the parameter in the URL because that's done by default. Extra parameters are f... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005954819_django_python.txt |
Q:
Typical Naming Conventions for Python Directories in Packages
The Question
I would like to know if there is a standard convention for the naming of Python directories that plan to be imported as a module. Meaning the directory contains a blank __init__.py
Background
Up until recently I have given it little though... | Typical Naming Conventions for Python Directories in Packages | The Question
I would like to know if there is a standard convention for the naming of Python directories that plan to be imported as a module. Meaning the directory contains a blank __init__.py
Background
Up until recently I have given it little thought and named solely based on what made sense at the file system leve... | [
"Each module's namespace is unique, so even if you have two modules named visa as long as you avoid importing them into the same namespace with the same name you won't have any problems. I tend to prefer absolute imports:\nimport drivers.visa\nimport pyVisa.visa\n\nOr you could also use as:\nfrom drivers import vis... | [
5
] | [] | [] | [
"directory",
"naming_conventions",
"python"
] | stackoverflow_0005955473_directory_naming_conventions_python.txt |
Q:
Python Matrix, rows and columns
I have some problem matrix:
b= [[-2.5, 0.5], #b is random matrix
[-1.5, -0.5],
[-0.5, 0.5]]
How can from b get:
b=[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]]
Many thanks
A:
>>> b= [[-2.5, 0.5], #b is random matrix
[-1.5, -0.5],
[... | Python Matrix, rows and columns | I have some problem matrix:
b= [[-2.5, 0.5], #b is random matrix
[-1.5, -0.5],
[-0.5, 0.5]]
How can from b get:
b=[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]]
Many thanks
| [
">>> b= [[-2.5, 0.5], #b is random matrix\n [-1.5, -0.5],\n [-0.5, 0.5]]\n>>> [[[val] for val in row] for row in b]\n[[[-2.5], [0.5]], [[-1.5], [-0.5]], [[-0.5], [0.5]]]\n\n\nExplanation: Consider a list:\n>>> oned = [1, 2, 3]\n\nYou can re-create it with a list comprehension:\n>>> [val for val i... | [
4,
1
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0005955528_matrix_python.txt |
Q:
numpy: code to update least squares with more observations
I am looking for a numpy-based implementation of ordinary least squares that would allow the fit to be updated with more observations. Something along the lines of Applied Statistics algorithm AS 274 or R's biglm.
Failing that, a routine for updating a QR ... | numpy: code to update least squares with more observations | I am looking for a numpy-based implementation of ordinary least squares that would allow the fit to be updated with more observations. Something along the lines of Applied Statistics algorithm AS 274 or R's biglm.
Failing that, a routine for updating a QR decomposition with new rows would also be of interest.
Any point... | [
"scikits.statsmodels has an recursive OLS that updates the inverse X'X in the sandbox that could be used for this. (used only to calculate recursive OLS residuals.)\nNathaniel Smith posted his code for OLS when the data is too large to fit in memory to the scipy-user mailing list. The main code updates X'X.\nI thin... | [
4,
1,
1,
0
] | [] | [] | [
"least_squares",
"linear_regression",
"numpy",
"python",
"statistics"
] | stackoverflow_0005952815_least_squares_linear_regression_numpy_python_statistics.txt |
Q:
Cannot edit text in chart exported by Matplotlib and opened in Illustrator
I am exporting charts from matplotlib and editing them in Illustrator. It's great that I can edit the lines, but the text also comes in as lines, so I cannot change fonts, edit text, etc. I've exported as EPS, PDF, and PS with the same is... | Cannot edit text in chart exported by Matplotlib and opened in Illustrator | I am exporting charts from matplotlib and editing them in Illustrator. It's great that I can edit the lines, but the text also comes in as lines, so I cannot change fonts, edit text, etc. I've exported as EPS, PDF, and PS with the same issues.
I'm using matplotlib version 1.0.1 with python 2.7.1 on OSX Snow Leaopard... | [
"You can edit the text in Acrobat/Illustrator if you set pdf.fonttype to 42 (TrueType), and export in pdf. You can set this in your ~/matplotlib/matplotlibrc:\npdf.fonttype : 42 # Output Type 3 (Type3) or Type 42 (TrueType)\n\n..or dynamically:\n>>> import matplotlib as mpl\n>>> mpl.rcParams['pdf.fonttype'] = 42\n\... | [
28
] | [] | [] | [
"adobe_illustrator",
"eps",
"matplotlib",
"pdf",
"python"
] | stackoverflow_0005956182_adobe_illustrator_eps_matplotlib_pdf_python.txt |
Q:
Problem with form in Django
I'm trying to implement a form for let the user change their password.
Here the code:
forms.py
class ChangePasswordForm(forms.Form):
password1 = forms.CharField(widget = forms.PasswordInput(), required = True)
password2 = forms.CharField(widget = forms.PasswordInput(), required ... | Problem with form in Django | I'm trying to implement a form for let the user change their password.
Here the code:
forms.py
class ChangePasswordForm(forms.Form):
password1 = forms.CharField(widget = forms.PasswordInput(), required = True)
password2 = forms.CharField(widget = forms.PasswordInput(), required = True)
def clean_password2(... | [
"Just make it a parameter to the save method.\ndef save(self, user):\n user.set_password(self.cleaned_data['password1'])\n user.save()\n\n...\n\n\nform.save(request.user)\n\n",
"user colud be taken from request.user in general\n"
] | [
5,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0005956619_django_django_forms_python.txt |
Q:
Python: universal import
Can anyone explain which 'import' is universal, so I don't need to write for example:
from numpy import *
import numpy
import numpy as np
from numpy.linalg import *
Why not import numpy or from numpy import * to incude all from "numpy"?
A:
I'm not sure what you mean by "all from numpy",... | Python: universal import | Can anyone explain which 'import' is universal, so I don't need to write for example:
from numpy import *
import numpy
import numpy as np
from numpy.linalg import *
Why not import numpy or from numpy import * to incude all from "numpy"?
| [
"I'm not sure what you mean by \"all from numpy\", but you should never need to use more than one form of import at a time. They do different things:\nOption One: import\nimport numpy will bring the entire numpy module into the current namespace. You can then reference anything from that moudule as numpy.dot or num... | [
9
] | [] | [] | [
"numpy",
"python",
"python_import"
] | stackoverflow_0005956627_numpy_python_python_import.txt |
Q:
Extract items list from XML in python
In python, what is the best way to extract the list of items from the following xml?
<iq xmlns="jabber:client" to="__anonymous__admin@localhost/8978528613056092673206"
from="conference.localhost" id="disco" type="result">
<query xmlns="http://jabber.org/protocol/disco#i... | Extract items list from XML in python | In python, what is the best way to extract the list of items from the following xml?
<iq xmlns="jabber:client" to="__anonymous__admin@localhost/8978528613056092673206"
from="conference.localhost" id="disco" type="result">
<query xmlns="http://jabber.org/protocol/disco#items">
<item jid="pgatt@conference.... | [
"I'm not sure about lxml but you can use an expression like //*[local-name()=\"item\"] to pull out the item elements regardless of their namespace.\nYou might also want to take a look at Amara for XML processing.\n>>> import amara.bindery\n>>> doc = amara.bindery.parse(\n... '''<iq xmlns=\"jabber:client\" \n...... | [
1,
1,
0
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0005956592_lxml_python_xml.txt |
Q:
Problems loading dynamic python module using __init__.py
I'm trying to do an __init__.py that load module and instantiate dinamically internal namesake class. With a file tree like
importer/
__init__.py # The file i'm writing
asd.py # It contains class asd
bsd.py #... | Problems loading dynamic python module using __init__.py | I'm trying to do an __init__.py that load module and instantiate dinamically internal namesake class. With a file tree like
importer/
__init__.py # The file i'm writing
asd.py # It contains class asd
bsd.py # It contains class bsd
And __init__.py with
importername=__na... | [
"There is no such thing as truly global in Python. When you use globals() in importer/__init__.py, you are accessing the module's namespace. Your second non-working sample is adding 'asd' to importer, not to your test module.\nThe best you could is modify importer so you could do:\nfrom importer import *\nasd = l... | [
2
] | [] | [] | [
"init",
"instantiation",
"loading",
"module",
"python"
] | stackoverflow_0005956657_init_instantiation_loading_module_python.txt |
Q:
Pygame: How to draw in non rectangle clipping area
Hi I would like to set in pygame non rectangle clipping area (in this case as character "P"), where it would be strict limited, where to draw another objects.
Is there any option?
thanks a lot
A:
Let's see if I correctly understand your question: you want to "bl... | Pygame: How to draw in non rectangle clipping area | Hi I would like to set in pygame non rectangle clipping area (in this case as character "P"), where it would be strict limited, where to draw another objects.
Is there any option?
thanks a lot
| [
"Let's see if I correctly understand your question: you want to \"blit\" an image onto a surface, but do it through a mask which would only allow certain pixels of the source to actually end up on the surface? \nI had this precise problem and at first I thought it would only be doable through PIL. However after som... | [
7,
4
] | [] | [] | [
"clip",
"draw",
"pygame",
"python"
] | stackoverflow_0005940935_clip_draw_pygame_python.txt |
Q:
Python: Read large file in chunks
Hey there, I have a rather large file that I want to process using Python and I'm kind of stuck as to how to do it.
The format of my file is like this:
0 xxx xxxx xxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... | Python: Read large file in chunks | Hey there, I have a rather large file that I want to process using Python and I'm kind of stuck as to how to do it.
The format of my file is like this:
0 xxx xxxx xxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... | [
"If they are all within the same line, that is there are no line breaks between \"1.\" and \"2.\" then you can iterate over the lines of the file like this:\nfor line in open(\"myfile.txt\"):\n #do stuff\n\nThe line will be disposed of and overwritten at each iteration meaning you can handle large file sizes wit... | [
3,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005953949_python.txt |
Q:
iphone python or perl processor, or similar
I have an application to develop but the problem is that is must download part of behavior as a list of instructions from a server.
Ideally it will download scripting code and execute it. The question is if there are any libraries to make it? For example, I have python s... | iphone python or perl processor, or similar | I have an application to develop but the problem is that is must download part of behavior as a list of instructions from a server.
Ideally it will download scripting code and execute it. The question is if there are any libraries to make it? For example, I have python script and I want to to execute it on device...
An... | [
"Lua is very popular for games. You can embed Python, too. Apple won't enforce the \"Objective-C only\" clause unless you make it obvious that you use Python to script behavior. Do you think all the games on the store are scripted in Objective-C? No way. Just don't make your transgressions obvious and you'll be... | [
1,
0
] | [] | [] | [
"compiler_construction",
"iphone",
"python",
"scripting"
] | stackoverflow_0005957110_compiler_construction_iphone_python_scripting.txt |
Q:
how do I install httplib2 for python under windows 7 64?
Only instructions I can find refer to unix/linux?
A:
cd httplib2-0.6.0
python setup.py install
A:
If you do not want to go through compile orgy, stranger errors and terror,
Install ActivePython (32-bit)
Open Command Prompt and type pypm install httplib2... | how do I install httplib2 for python under windows 7 64? | Only instructions I can find refer to unix/linux?
| [
"cd httplib2-0.6.0\npython setup.py install\n\n",
"If you do not want to go through compile orgy, stranger errors and terror,\n\nInstall ActivePython (32-bit)\nOpen Command Prompt and type pypm install httplib2\n\n"
] | [
4,
3
] | [] | [] | [
"httplib2",
"installation",
"python",
"windows",
"windows_7"
] | stackoverflow_0005956891_httplib2_installation_python_windows_windows_7.txt |
Q:
Python, Pylons, and Sqlalchemy: Analyzing the Facebook Graph API
I would like to take data from the Facebook Graph API and analyze it to find out roughly how close one person is to another. I am attempting to use the Pylons framework with SqlAlchemy (right now it is attached to a SQLite database) to store informat... | Python, Pylons, and Sqlalchemy: Analyzing the Facebook Graph API | I would like to take data from the Facebook Graph API and analyze it to find out roughly how close one person is to another. I am attempting to use the Pylons framework with SqlAlchemy (right now it is attached to a SQLite database) to store information from the Graph API so that I can make it available to my other app... | [
"I'd store as much as possible, dump everything you can. Try to maintain the relationships between nodes so you can traverse/analyze them later. This affords you the opportunity to analyze your data set as much as you want, over and over and try different things. If you want to use SQLAlchemy you could use a simple... | [
1
] | [] | [] | [
"algorithm",
"database",
"facebook",
"python",
"sqlalchemy"
] | stackoverflow_0005957087_algorithm_database_facebook_python_sqlalchemy.txt |
Q:
Python list confusion
Let's say I have the following code:
a_list = [[0]*10]*10
This generates the following list:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
... | Python list confusion | Let's say I have the following code:
a_list = [[0]*10]*10
This generates the following list:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0,... | [
"Your hunch about copying addresses is correct. Think about it like this:\nsub_list = [0] * 10\na_list = [sub_list] * 10\n\nThis code is actually equivalent to the code you have posted above. What this means is that you are actually changing the same list sub_list whenever you change any element of a_list. You can ... | [
15,
4,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005957341_list_python.txt |
Q:
How to check if a user is admin of their Google Apps domain in App Engine?
I followed this tutorial to enable single sign on for an app that installs through the Google Apps Marketplace. Now, what is the best way to check if the user is admin of the Google Apps domain?
Edit: I'm asking this because we can define l... | How to check if a user is admin of their Google Apps domain in App Engine? | I followed this tutorial to enable single sign on for an app that installs through the Google Apps Marketplace. Now, what is the best way to check if the user is admin of the Google Apps domain?
Edit: I'm asking this because we can define links for "setup" and "manage" in the manifest. I don't think those pages in my a... | [
"You can take your admin user to your app via the optional step3 of the install process from the marketplace where you could manually request which user(s) they want to dedicate admin rights to within your app.\n",
"You probably could use the Provisioning API to do retrieve a user account. In the response you wou... | [
3,
2,
0
] | [] | [] | [
"google_app_engine",
"google_apps",
"oauth",
"openid",
"python"
] | stackoverflow_0005951946_google_app_engine_google_apps_oauth_openid_python.txt |
Q:
Using a constantly changing variable to define a list
I want to make a piece of code which pulls the title and link off an RSS feed and compiles it into a variable which can be then used in the message body. My problem is Body gets redefined every time i pull the info off the RSS. I am very new to programming and ... | Using a constantly changing variable to define a list | I want to make a piece of code which pulls the title and link off an RSS feed and compiles it into a variable which can be then used in the message body. My problem is Body gets redefined every time i pull the info off the RSS. I am very new to programming and python, and I am under the impression that using a list wou... | [
"There are a variety of design patterns you can consider using. I will demonstrate a few where you don't need to use [i] even:\nAccumulator:\nmessages = []\nfor feedItem in feed['items']:\n message = {'title':..., ...}\n message['link'] = ... # alternative\n messages += [message] # or messages.append(da... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0005957712_python.txt |
Q:
upload csv/excel file to appengine (python) for processing
I need to be able to upload an excel or csv file to appengine so that the server can process the rows and create objects. Can anyone provide or point me to an example of how this is done? Thanks for your help.
A:
Uploading to the Blobstore is probably wh... | upload csv/excel file to appengine (python) for processing | I need to be able to upload an excel or csv file to appengine so that the server can process the rows and create objects. Can anyone provide or point me to an example of how this is done? Thanks for your help.
| [
"Uploading to the Blobstore is probably what you are after. Then reading the data and processing it with the csv module.\nYou might want to look into sending your file to google docs in the case of excel (and other) formats then reading the rows back via the Spreadsheets API\n",
"If you mean a one-off (or a few) ... | [
2,
1
] | [] | [] | [
"csv",
"file",
"file_upload",
"google_app_engine",
"python"
] | stackoverflow_0005956823_csv_file_file_upload_google_app_engine_python.txt |
Q:
Preventing pool processes from importing __main__ and globals
I am using a multiprocessing pool of workers as a part of a much larger application. Since I use it for crunching a large volume of simple math, I have a shared-nothing architecture, where the only variables the workers ever need are passed on as argume... | Preventing pool processes from importing __main__ and globals | I am using a multiprocessing pool of workers as a part of a much larger application. Since I use it for crunching a large volume of simple math, I have a shared-nothing architecture, where the only variables the workers ever need are passed on as arguments. Thus, I do not need the worker subprocesses to import any glob... | [
"Looking at the multiprocessing.forking implementation, particularly get_preparation_data and prepare (win32-specific), globals aren't getting pickled. The reimport of the parent process's __main__ is a bit ugly, but it won't run any code except the one at the toplevel; not even if __name__ == '__main__' clauses. S... | [
3
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0005957727_multiprocessing_python.txt |
Q:
Need help with my shuffle card program
I'm doing a shuffle cards program.At the end i'm using for loop to print out 10 random cards, but i don't know what wrong with it.
On the end deal_card(card), why i put card because my h/w say so, but if you had other answer i'll be good to listen what you say.
This is my pro... | Need help with my shuffle card program | I'm doing a shuffle cards program.At the end i'm using for loop to print out 10 random cards, but i don't know what wrong with it.
On the end deal_card(card), why i put card because my h/w say so, but if you had other answer i'll be good to listen what you say.
This is my program:
import random
def define_cards():
... | [
"Since your define_cards already produces a list of card names, you should use that to generate the deck instead of create_deck. Then in the for loop just deal a card and print it.\ndeck = define_cards()\nshuffle_deck(deck)\nprint \"The first 10 cards are:\"\nfor i in range(10):\n card = deal_card(deck)\n pri... | [
6,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005919452_python.txt |
Q:
'The Scope Was bad or missing' error trying to use AuthSub with google health?
I'm trying to use AuthSub to request a token from google health. It says the scope was bad or missing. I've double checked, and the scope looks good to me. I've tried replacing the scope with calendar, and I don't get that error.
Here's... | 'The Scope Was bad or missing' error trying to use AuthSub with google health? | I'm trying to use AuthSub to request a token from google health. It says the scope was bad or missing. I've double checked, and the scope looks good to me. I've tried replacing the scope with calendar, and I don't get that error.
Here's a code snippet
next = 'http://localhost:8080/auth'
# h9 scope for development
#scop... | [
"I'm not familiar with Google Health, but did some Googling and you need to register your site first:\nhttps://services.google.com/fb/forms/googhealthdevelopers/\nIt takes a week for this registration to go through. Meanwhile you can test against H9 sandbox with an url like:\nhttps://h9.google.com/h9/authsub?next=h... | [
1
] | [] | [] | [
"authentication",
"authsub",
"gdata_api",
"google_app_engine",
"python"
] | stackoverflow_0005957856_authentication_authsub_gdata_api_google_app_engine_python.txt |
Q:
Try / except syntax in Python with two of the same exceptions
I am checking emails against two lists -- a list of domains and a list of individual emails.
How would I construct the following try statement --
Try: 'email in email_list'
Except DoesNotExist: 'domain in domain list' # if email not found
Except DoesN... | Try / except syntax in Python with two of the same exceptions | I am checking emails against two lists -- a list of domains and a list of individual emails.
How would I construct the following try statement --
Try: 'email in email_list'
Except DoesNotExist: 'domain in domain list' # if email not found
Except DoesNotExist: 'print error message' # if both email and domain not fou... | [
"It sounds like you're looking for something like:\nif email in email_list:\n # do something with email\nelif domain in domain_list:\n # do something with domain\nelse:\n print \"neither email nor domain found\"\n\nThere is probably no need for exceptions in this case.\n",
"Why don't define two exception... | [
7,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005958150_django_python.txt |
Q:
How to determine whether the cursor is inside a gtk.Menu?
I have a gtk.Menu (which is being used as a popup) and I need to determine whether the mouse cursor is inside the confines of the menu.
I can get the mouse's position on the screen using this method. But how do I get the dimensions and position of the menu ... | How to determine whether the cursor is inside a gtk.Menu? | I have a gtk.Menu (which is being used as a popup) and I need to determine whether the mouse cursor is inside the confines of the menu.
I can get the mouse's position on the screen using this method. But how do I get the dimensions and position of the menu after calling menu.popup(...)?
| [
"Looks like I didn't look close enough at some of the methods that gtk.Menu provides.\nIt turns out that gtk.Menu is a descendant of gtk.Widget which has a method get_window which returns the menu's underlying gtk.gdk.Window.\nFrom there, it's simply a matter of calling get_frame_extents() which returns a gtk.gdk.R... | [
0
] | [] | [] | [
"dimensions",
"menu",
"position",
"pygtk",
"python"
] | stackoverflow_0005958033_dimensions_menu_position_pygtk_python.txt |
Q:
MP3 Playing modules that will run within a thread Python
I'm trying to write a program that will play MP3's. This program will also have a GUI. In order to allow both to happen simultaneously I'm implementing threading. However, I've run into a problem. Whenever I run my program everything executes normally, excep... | MP3 Playing modules that will run within a thread Python | I'm trying to write a program that will play MP3's. This program will also have a GUI. In order to allow both to happen simultaneously I'm implementing threading. However, I've run into a problem. Whenever I run my program everything executes normally, except no sound comes out. No errors nothing. It's as if the comman... | [
"You could try pymedia or pyglet. I know pygame has mp3 support as well.\n"
] | [
1
] | [] | [] | [
"mp3",
"multithreading",
"python",
"user_interface"
] | stackoverflow_0005958616_mp3_multithreading_python_user_interface.txt |
Q:
python: lenient version of iterator.groupby that skips the records on exception
I am using a iterator.groupby to group similar entries in an iterator together based on an attribute value like this:
employment = dict(itertools.groupby(xtable_iterator), operator.attrgetter('key_to_ytable')))
key_to_ytable is a... | python: lenient version of iterator.groupby that skips the records on exception | I am using a iterator.groupby to group similar entries in an iterator together based on an attribute value like this:
employment = dict(itertools.groupby(xtable_iterator), operator.attrgetter('key_to_ytable')))
key_to_ytable is an attribute that can throw an exception. So, my whole dict constructor fails. I would... | [
"I vote for the custom attrgetter in this situation, like:\nemployment = dict(itertools.groupby(xtable_iterator),\n lambda x: getattr(x, 'key_to_ytable', None))\nemployment.pop(None)\n\nThis is simpler and probably faster than doing a filter or anything, you know there will only be one None there.\... | [
1
] | [] | [] | [
"exception_handling",
"group_by",
"iterator",
"python"
] | stackoverflow_0005958777_exception_handling_group_by_iterator_python.txt |
Q:
What does INSTALLED_APPS setting in Django actually do?
What does this actually do? I recently branched out my project from 1 app into 6 different apps and forgot to update the INSTALLED_APPS part of my settings file. Everything still works even though I didn't list the new apps in. Is that supposed to happen? Do ... | What does INSTALLED_APPS setting in Django actually do? | What does this actually do? I recently branched out my project from 1 app into 6 different apps and forgot to update the INSTALLED_APPS part of my settings file. Everything still works even though I didn't list the new apps in. Is that supposed to happen? Do I need to include all my apps in INSTALLED_APPS?
| [
"yes.\nINSTALLED_APPS helps django to sync the database, run tests, get the urls to work and more related issues.\nMaybe your installed apps still works because the main one calls the others with imports, a django app is nothing more that a simple python module that is imported when called in the settings file, tha... | [
10
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005958882_django_python.txt |
Q:
Is it safe to modify the output of globals()?
The documentation for the locals() function specifically warns not to modify its output, as interpreters may not reflect changes in the local scope. I'm assuming that means the Python spec doesn't require it, even though it works in CPython.
I'd like to know if this is... | Is it safe to modify the output of globals()? | The documentation for the locals() function specifically warns not to modify its output, as interpreters may not reflect changes in the local scope. I'm assuming that means the Python spec doesn't require it, even though it works in CPython.
I'd like to know if this is the same for globals(). There's no warning in the ... | [
"Modifying locals() doesn't work reliably, even in CPython. It happens to work in module and class scopes, but it fails inside a function (any modifications \"won't take\", since locals() provides a copy of the local namespace in that case, rather than a reference to the real thing)\nHowever, globals() is different... | [
27
] | [] | [] | [
"global",
"python"
] | stackoverflow_0005958793_global_python.txt |
Q:
Using localflavor Django form fields on Google's App Engine
Is it possible to use the form fields from
django.contrib.localflavor.us.forms
on the Google App Engine? Can I simply use those form fields, or do I need a form field under
google.appengine.ext.db.djangoforms
A:
You would need to grab the folder un... | Using localflavor Django form fields on Google's App Engine | Is it possible to use the form fields from
django.contrib.localflavor.us.forms
on the Google App Engine? Can I simply use those form fields, or do I need a form field under
google.appengine.ext.db.djangoforms
| [
"You would need to grab the folder under django.contrib.localflavour and import it into your app.\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0001235851_django_django_forms_google_app_engine_python.txt |
Q:
Convert Military Time from text file to Standard time Python
I am having problems with logic on how to convert military time from a text file to standard time and discard all the wrong values. I have only got to a point where the user is asked for the input file and the contents are displayed from the text file en... | Convert Military Time from text file to Standard time Python | I am having problems with logic on how to convert military time from a text file to standard time and discard all the wrong values. I have only got to a point where the user is asked for the input file and the contents are displayed from the text file entered. Please help me
| [
"Python's datetime.time objects use \"military\" time. You can do things like this:\n>>> t = datetime.time(hour=15, minute=12)\n>>> u = datetime.time(hour=16, minute=44)\n>>> t = datetime.datetime.combine(datetime.datetime.today(), t)\n>>> t\ndatetime.datetime(2011, 5, 11, 15, 12)\n>>> u = datetime.datetime.combine... | [
3,
1,
1
] | [] | [] | [
"python",
"standards",
"time"
] | stackoverflow_0005959130_python_standards_time.txt |
Q:
Creating Reusable Django Apps?
I am somewhat of a Django beginner and have been trying to decouple my applications as much as possible and build it in as small re-usable pieces as possible. Trying to follow James Bennett's strategy of building re-usable apps. With that in mind, I came across this problem.
Let's sa... | Creating Reusable Django Apps? | I am somewhat of a Django beginner and have been trying to decouple my applications as much as possible and build it in as small re-usable pieces as possible. Trying to follow James Bennett's strategy of building re-usable apps. With that in mind, I came across this problem.
Let's say I had an app that stores informati... | [
"In this case, personally, I'd keep it simple and just leave rating on the model. You have to balance re-usability with simplicity of implementation. It's great to make things reusable, but is your Movie model really useful enough to warrant the extra work? And is it that bad to have a dependency? I think much of t... | [
4,
1,
0
] | [] | [] | [
"django",
"python",
"reusability"
] | stackoverflow_0005958931_django_python_reusability.txt |
Q:
How can I give parameters to a function of a python script through the command-line?
Currently this is my python script (TagGen) which has one function:
def SJtag(file,len_tag):
import csv
reader = csv.reader(open(file), dialect='excel-tab' )
for row in reader:
qstarts = row[1].split(",")[1:-1... | How can I give parameters to a function of a python script through the command-line? | Currently this is my python script (TagGen) which has one function:
def SJtag(file,len_tag):
import csv
reader = csv.reader(open(file), dialect='excel-tab' )
for row in reader:
qstarts = row[1].split(",")[1:-1]
n = len_tag/2
for i in qstarts:
name = row[0]
... | [
"You could use the argparse module for that.\nFrom the docs,\nimport argparse\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('integers', metavar='N', type=int, nargs='+',\n help='an integer for the accumulator')\nparser.add_argument('--sum', dest='accumulate... | [
3,
2,
1,
0
] | [] | [] | [
"command_line",
"function",
"parameters",
"python"
] | stackoverflow_0005959172_command_line_function_parameters_python.txt |
Q:
Python: search global classes in a single module file
I have a Python 2.x module.py file that looks like this:
class A(object):
KEYWORD = 'Class A'
class B(A):
KEYWORD = 'Class B'
class C(object):
pass
def list_class_keywords():
for name in globals():
print name, hasattr(name, 'KEYWORD')... | Python: search global classes in a single module file | I have a Python 2.x module.py file that looks like this:
class A(object):
KEYWORD = 'Class A'
class B(A):
KEYWORD = 'Class B'
class C(object):
pass
def list_class_keywords():
for name in globals():
print name, hasattr(name, 'KEYWORD')
if __name__ == '__main__':
list_class_keywords()
In ... | [
"globals() is a dictionary. Index it.\nBut you should be using a decorator to enumerate the classes.\n",
"class A(object):\n KEYWORD = 'Class A'\n\nclass B(A):\n KEYWORD = 'Class B'\n\nclass C(object):\n pass\n\ndef list_class_keywords():\n for name, obj in globals().items():\n print name, hasa... | [
3,
2,
1
] | [] | [] | [
"global",
"python",
"python_module"
] | stackoverflow_0005959332_global_python_python_module.txt |
Q:
Processing information from Twitter Search API with PHP or Python
I want to be able to order a list of terms by how many results I get in a search query on twitter using each term in the list.
I know that the search API allows me do things like this -->
http://search.twitter.com/search.atom?q=
or
http://search.twi... | Processing information from Twitter Search API with PHP or Python | I want to be able to order a list of terms by how many results I get in a search query on twitter using each term in the list.
I know that the search API allows me do things like this -->
http://search.twitter.com/search.atom?q=
or
http://search.twitter.com/search.json?q=
I can type these into my browser bar and get th... | [
"Grab the data using JSON. You won't need any special parsing tools if you use JSON since you can simply call json_decode() on it. Be aware that this is available only on PHP versions 5.2 and up and that some hosts may have disabled it. You can use cURL to get the contents from the URL or if you have fopen wrappers... | [
0
] | [] | [] | [
"json",
"php",
"python",
"rest",
"twitter"
] | stackoverflow_0005945081_json_php_python_rest_twitter.txt |
Q:
Why is it bad idea to modify locals in python?
Related to this reply here. Locals' doc here.
The docs mention that the dictionary should not change, not sure what it means but would locals() be applicable in lab-reports where data won't change, for example in measurements?
A:
What documentation says is that whe... | Why is it bad idea to modify locals in python? | Related to this reply here. Locals' doc here.
The docs mention that the dictionary should not change, not sure what it means but would locals() be applicable in lab-reports where data won't change, for example in measurements?
| [
"What documentation says is that when you have a local x variable and do locals()['x'] = 42, then x may still point to the old object.\ndef foo():\n x = 0xABCD\n locals()['x'] = 42\n print(x)\n\nfoo()\n\n",
"In certain cases, the call to locals() returns values collected from multiple sources, rather tha... | [
10,
6,
4,
3,
1
] | [] | [] | [
"locals",
"python"
] | stackoverflow_0004997184_locals_python.txt |
Q:
Django not found in Eclipse IDE on Windows
I'm trying to create a Django project in Eclipse but it says I have no Django installed, Although I've run a script which imports django and print its version and everything works fine, but in Eclipse not.
See that it prints Django version correctly and every module I ha... | Django not found in Eclipse IDE on Windows | I'm trying to create a Django project in Eclipse but it says I have no Django installed, Although I've run a script which imports django and print its version and everything works fine, but in Eclipse not.
See that it prints Django version correctly and every module I have. Now see what Eclipse says:
| [
"Try to remove then re-add the python interpreter.\n"
] | [
1
] | [] | [] | [
"django",
"eclipse",
"python",
"windows"
] | stackoverflow_0005959643_django_eclipse_python_windows.txt |
Q:
Uninstalling a python module in ubuntu
I have to delete a python module named "django" (a popular one), because I installed the wrong version (1.3 - beta in py-2.6).
How to uninstall this module?
Please explain, because I've used python only in Windows and never in Ubuntu.
A:
go to the python shell
>> import dj... | Uninstalling a python module in ubuntu | I have to delete a python module named "django" (a popular one), because I installed the wrong version (1.3 - beta in py-2.6).
How to uninstall this module?
Please explain, because I've used python only in Windows and never in Ubuntu.
| [
"go to the python shell\n >> import django\n django.__path__\ncopy the path\non the shell \n sudo rm -r path \n",
"sudo aptitude install python-pip\nsudo pip install django --upgrade\n\n"
] | [
10,
1
] | [] | [] | [
"django",
"python",
"uninstallation"
] | stackoverflow_0005959647_django_python_uninstallation.txt |
Q:
print values in pdb
When I trace to a function, inside the function I would like to print the values of those variable names with underscore in the beginning, eg. p __seqLen. It keeps showing AttributeError: AttributeError("Converter instance has no attribute '__seqLen'",) I also tried to use p self.__seqLen. This... | print values in pdb | When I trace to a function, inside the function I would like to print the values of those variable names with underscore in the beginning, eg. p __seqLen. It keeps showing AttributeError: AttributeError("Converter instance has no attribute '__seqLen'",) I also tried to use p self.__seqLen. This is also not working. How... | [
"p locals()\np globals()\n\ncould help.\n",
"You might be running into Python's private name mangling. Python will mangle identifiers that begin with two or more underscores and do not end with two or more underscores. It transforms __somename into _Class__somename.\n"
] | [
11,
7
] | [] | [] | [
"debugging",
"pdb",
"python"
] | stackoverflow_0005959599_debugging_pdb_python.txt |
Q:
How do I upload an entire directory to S3?
I want my directory, and all its sub directories and files, to go straight to S3. Clone it.
Is there an easy script/program to do that?
I'm on Ubuntu linux.
A:
Install S3 (http://s3tools.org/download)
Configure it:
s3cmd --configure
Create a bucket: s3cmd mb s3://my-bu... | How do I upload an entire directory to S3? | I want my directory, and all its sub directories and files, to go straight to S3. Clone it.
Is there an easy script/program to do that?
I'm on Ubuntu linux.
| [
"\nInstall S3 (http://s3tools.org/download) \nConfigure it:\ns3cmd --configure\nCreate a bucket: s3cmd mb s3://my-bucket (alternatively, you can do this via a tool like S3Fox) \nSync your local directory with S3: s3cmd sync /path/to/local/dir/ s3://my-bucket\n\n"
] | [
10
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"file",
"python"
] | stackoverflow_0005945408_amazon_s3_amazon_web_services_file_python.txt |
Q:
Django: saving data from user input and display
I have a form with a jwysiwyg editor. Looking at it, it can use basic-formatting html tags using the formatting buttons like SO's. Upon submitting the form, I notice its saved into the database as-is, whereas if I enter stuff like <iframe> ... </iframe> into the edit... | Django: saving data from user input and display | I have a form with a jwysiwyg editor. Looking at it, it can use basic-formatting html tags using the formatting buttons like SO's. Upon submitting the form, I notice its saved into the database as-is, whereas if I enter stuff like <iframe> ... </iframe> into the editor I notice that it is html-encoded inside the table.... | [
"Use the safe filter only if you html-escape the data first. Otherwise you should use escape. If you want your users to be able to input data with html tags you could try to sanitize the input to prevent users from using <iframe>, <script>, etc, but allow other tags to be white-listed, and then mark it as safe.\n"
... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005959553_django_python.txt |
Q:
How to generate the PEM serialization for the public RSA/DSA key
Using PyCrypto I was able to generate the public and private PEM serialization for a RSA key, but in PyCrypto the DSA class has no exportKey() method.
Trying PyOpenSSL I was able to generate the private PEM serialization for RSA and DSA keys, bu ther... | How to generate the PEM serialization for the public RSA/DSA key | Using PyCrypto I was able to generate the public and private PEM serialization for a RSA key, but in PyCrypto the DSA class has no exportKey() method.
Trying PyOpenSSL I was able to generate the private PEM serialization for RSA and DSA keys, bu there is no crypto.dump_publickey method in PyOpenSSL.
I am looking for su... | [
"It is not clear what you are doing this for, but if all you want is an openssl-compatible DSA private key, you should just follow the openssl dsa(1) manual page:\n\nThe DER option with a private key uses\n an ASN1 DER encoded form of an ASN .1\n SEQUENCE consisting of the values of\n version (currently zero), p... | [
3
] | [] | [] | [
"openssl",
"pycrypto",
"pyopenssl",
"python"
] | stackoverflow_0005938664_openssl_pycrypto_pyopenssl_python.txt |
Q:
gtk.gdk.color_parse() equivalent in vala
I'm trying to find an equivalent to the pyGtk function gtk.gdk.color_parse in Vala. All I can find is Gdk.Color.parse which is sort of similar, but returns a boolean instead of a Gdk.Color structure. It seems like I should be able to find the equivalent to the Python functi... | gtk.gdk.color_parse() equivalent in vala | I'm trying to find an equivalent to the pyGtk function gtk.gdk.color_parse in Vala. All I can find is Gdk.Color.parse which is sort of similar, but returns a boolean instead of a Gdk.Color structure. It seems like I should be able to find the equivalent to the Python function, but I don't seem to be able to.
| [
"No, that's the one - it gives you the color as an \"out parameter\" instead of return value. Python doesn't have out parameters (well, Python has any feature if you try hard enough...) The boolean return value tells whether the parsing succeeded. PyGTK probably raises an exception if it doesn't.\nUse it like this:... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"vala"
] | stackoverflow_0005956930_gtk_pygtk_python_vala.txt |
Q:
Adding consecutive integers from an input (Translated from Python to C++)
I'd like to request some help on my HW. I think I'm really close to figuring this out. Our CompSci class is currently shifting from learning Python to (introductory) C++. Since the two are vaguely similar, we've been advised, since we're beg... | Adding consecutive integers from an input (Translated from Python to C++) | I'd like to request some help on my HW. I think I'm really close to figuring this out. Our CompSci class is currently shifting from learning Python to (introductory) C++. Since the two are vaguely similar, we've been advised, since we're beginners, to code the problem in Python (which we're very familiar with) and to t... | [
"Fixed code:\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n int num;\n int sum;\n int i;\n sum = 0;\n cout << \"Please enter a positive integer: \" << endl;\n cin >> num;\n // Here you had 1 <= num which was always true for positive num\n // and it did not depend on value of i... | [
1,
0,
0,
0,
0
] | [] | [] | [
"c++",
"integer",
"python"
] | stackoverflow_0005960249_c++_integer_python.txt |
Q:
Trying to manipulate images using Python
I am trying to learn Python, this is the first code that I have written:
#!/usr/bin/python
# Filename: read_image.py
f=open('1.raw','r+b')
image=f.read()
f.close()
f=open('copy.raw','w+b')
f.write(image)
f.close()
for i in range(1,256)... | Trying to manipulate images using Python | I am trying to learn Python, this is the first code that I have written:
#!/usr/bin/python
# Filename: read_image.py
f=open('1.raw','r+b')
image=f.read()
f.close()
f=open('copy.raw','w+b')
f.write(image)
f.close()
for i in range(1,256):
image[i]=0
In the first part I am... | [
"In Python bytes are immutable. You can't change them, that's why it gives you an error when you try to do item assignment. You could convert your immutable bytes object into a bytearray:\nimage = bytearray(image)\nfor i in range(1,256):\n image[i]=0\n\n",
"If you're really trying to do image processing in Pyt... | [
3,
3
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0005960234_image_processing_python.txt |
Q:
Where Should Shared Object Files Be Placed?
I am venturing into the land of creating C/C++ bindings for Python using pybindgen. I've followed the steps outlined under "Building it ( GCC instructions )" to create bindings for the sample files:
http://packages.python.org/PyBindGen/tutorial.html#a-simple-example
Run... | Where Should Shared Object Files Be Placed? | I am venturing into the land of creating C/C++ bindings for Python using pybindgen. I've followed the steps outlined under "Building it ( GCC instructions )" to create bindings for the sample files:
http://packages.python.org/PyBindGen/tutorial.html#a-simple-example
Running make produces a .so file. If I understand ho... | [
"Python looks for .so modules in the same directories where it searches python ones. So you have to install it as you would normal python module either somewhere that is on python's sys.path by default (/usr/share/python/site-lib or something like that—it'd distribution-dependent) or add the directory to PYTHONPATH... | [
3,
0
] | [] | [] | [
"binding",
"c++",
"pybindgen",
"python",
"shared_objects"
] | stackoverflow_0005960520_binding_c++_pybindgen_python_shared_objects.txt |
Q:
TemplateSyntaxError at / Caught IOError while rendering: (13, 'Permission denied')
This is the error shown on the page
TracebackFile
"/usr/local/lib64/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_k... | TemplateSyntaxError at / Caught IOError while rendering: (13, 'Permission denied') | This is the error shown on the page
TracebackFile
"/usr/local/lib64/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib64/python2.6/site-packages/django/views/generic/simple.py" in... | [
"Normally this could be the file permission problem while rendering\ndo chmod 777 -R to your template directory.\nOr Did you upgraded your django version?\n",
"The user, Apache is running under, has no permissions to write into your /tmp/ directory.\nMy suggested approach for it would be following:\n\nRun the Apa... | [
1,
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0005960132_apache_django_mod_wsgi_python.txt |
Q:
Python hashlib.md5 and ejabberd
I am using a python script as an external auth option in ejabberd 2.1.6.
I wanted to start encrypting the clear text passwords that come across in the auth verification, so that they are not being stored in plain text in the backend database. When I add the following code to my pyt... | Python hashlib.md5 and ejabberd | I am using a python script as an external auth option in ejabberd 2.1.6.
I wanted to start encrypting the clear text passwords that come across in the auth verification, so that they are not being stored in plain text in the backend database. When I add the following code to my python script and restart ejabberd, it h... | [
"I looked into the hashlib source and while it does not seem to require too much, it does import .so files as modules and one of them hits openssl. It all looks pretty safe but if ejabberd tries to fence itself against calls to 3rd party code (or if you have SELinux or something else to that effect running), stuff ... | [
1,
1,
0
] | [
"Try to use logging module, it can help you to watch input and output data, also check scripts permissions, let executing by user which is ejabberd, or for debug just set chmod 777 external.py.\n"
] | [
-1
] | [
"ejabberd",
"python"
] | stackoverflow_0005067860_ejabberd_python.txt |
Q:
Encode file path properly using python
I am trying to open files by getting the path from a dictionary. Some of the file names have commas (,) and other such characters which when used give a "no such file found error"
For instance the following file path will not open: foo,%20bar.mp3
If characters like commas exi... | Encode file path properly using python | I am trying to open files by getting the path from a dictionary. Some of the file names have commas (,) and other such characters which when used give a "no such file found error"
For instance the following file path will not open: foo,%20bar.mp3
If characters like commas exist then it should be encoded as : foo%2C%20b... | [
"You may need pathname2url\nPython 2.x (docs)\n>>> from urllib import pathname2url \n>>> pathname2url('foo, bar.mp3')\n'foo%2C%20bar.mp3'\n\nPython 3.x (docs)\n>>> from urllib.request import pathname2url\n>>> pathname2url('foo, bar.mp3')\n'foo%2C%20bar.mp3'\n\n",
"from urllib import pathname2url\npathname2url('fo... | [
18,
3,
2
] | [] | [] | [
"python",
"url_encoding"
] | stackoverflow_0005960751_python_url_encoding.txt |
Q:
C, C++ Interface with Python
I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the main( int argc, char* argv[]) function in the pa... | C, C++ Interface with Python | I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the main( int argc, char* argv[]) function in the past.
Since this method has become c... | [
"Use subprocess to execute your program from python.\nimport subprocess as sp\nimport shlex\n\ndef run(cmdline):\n process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)\n output, err = process.communicate()\n retcode = process.poll()\n return retcode, output, err\n\nrun('./a.out '+arg1+' '+ar... | [
8,
6,
3,
2,
2,
2
] | [] | [] | [
"bash",
"c",
"c++",
"python"
] | stackoverflow_0005960791_bash_c_c++_python.txt |
Q:
Reflect the QPixmap
I have an object QPixmap, how to get his reflection without QImage?
Now I do it using QImage (PyQt4):
tmp_image = QImage("./templates/{type}/{name}.png".format(type=tpl_type, name=tpl_name))
pixmap_reflect = QPixmap().fromImage(tmp_image.mirrored(horizontal=True, vertical=False))
A:
You shoul... | Reflect the QPixmap | I have an object QPixmap, how to get his reflection without QImage?
Now I do it using QImage (PyQt4):
tmp_image = QImage("./templates/{type}/{name}.png".format(type=tpl_type, name=tpl_name))
pixmap_reflect = QPixmap().fromImage(tmp_image.mirrored(horizontal=True, vertical=False))
| [
"You should be able to use QPixmap's transformed() (see this), using a scale as the transform (a scale of (1,-1) should do the trick I think). I'm assuming all functionality is available in PyQt. Don't use that myself.\n"
] | [
11
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt"
] | stackoverflow_0005960994_pyqt_pyqt4_python_qt.txt |
Q:
Using a class' __new__ method as a Factory: __init__ gets called twice
I encountered a strange bug in python where using the __new__ method of a class as a factory would lead to the __init__ method of the instantiated class to be called twice.
The idea was originally to use the __new__ method of the mother class t... | Using a class' __new__ method as a Factory: __init__ gets called twice | I encountered a strange bug in python where using the __new__ method of a class as a factory would lead to the __init__ method of the instantiated class to be called twice.
The idea was originally to use the __new__ method of the mother class to return a specific instance of one of her children depending on the paramet... | [
"When you construct an object Python calls its __new__ method to create the object then calls __init__ on the object that is returned. When you create the object from inside __new__ by calling Triangle() that will result in further calls to __new__ and __init__.\nWhat you should do is:\nclass Shape(object):\n de... | [
67,
14
] | [
"I can't actually reproduce this behavior in either of the Python interpreters I have installed, so this is something of a guess. However...\n__init__ is being called twice because you are initializing two objects: the original Shape object, and then one of its subclasess. If you change your __init__ so it also pr... | [
-1
] | [
"class_design",
"design_patterns",
"inheritance",
"python"
] | stackoverflow_0005953759_class_design_design_patterns_inheritance_python.txt |
Q:
better way to update a Tkinter listbox
Hi
so first of all i made a program that downloads music and displays the percent that has downloaded in a list box.
kind of like this
from Tkinter import *
from urllib2 import *
admin = Tk()
Admin = Tk()
listbox = Listbox(admin, bg="PURPLE")
listbox.pack()
def fores()... | better way to update a Tkinter listbox | Hi
so first of all i made a program that downloads music and displays the percent that has downloaded in a list box.
kind of like this
from Tkinter import *
from urllib2 import *
admin = Tk()
Admin = Tk()
listbox = Listbox(admin, bg="PURPLE")
listbox.pack()
def fores():
chunks = 10000
dat = ''
song =... | [
"The proper widget for displaying a string is a Label. You can change the text at runtime with the configure method:\nself.progress = Label(...)\n...\nself.progress.configure(text=\"%s%% completed\" % percent)\n\nSecond, you are creating two root windows - admin and Admin. And strangely, you are putting the listbox... | [
2
] | [
"i use a ttk.Progressbar, all you have to do is associate a variable to it and update that particular variable.\nhttp://docs.python.org/library/ttk.html#progressbar\nhttp://www.tkdocs.com/tutorial/morewidgets.html#progressbar\n"
] | [
-1
] | [
"python",
"tkinter",
"urllib2"
] | stackoverflow_0005944991_python_tkinter_urllib2.txt |
Q:
Get content from open window in Linux
I want to collect data and parse it eventually from an open window in linux.
An example- Suppose a terminal window is open. I need to retrieve all the data that appears on that window. After retrieval, I would parse it to get specific commands entered.
So is it possible to do ... | Get content from open window in Linux | I want to collect data and parse it eventually from an open window in linux.
An example- Suppose a terminal window is open. I need to retrieve all the data that appears on that window. After retrieval, I would parse it to get specific commands entered.
So is it possible to do that? If so, how? I would prefer to use pyt... | [
"You can (ab)use the assistive technologies support (for screen readers and such) that exist in the toolkit libraries. Whether it will work is toolkit specific—Gtk and Qt have this support, but others (like Tk, Fltk, etc.) may or may not.\nThe Linux Desktop Testing Project is a python toolkit for abusing these inte... | [
6,
4,
1
] | [] | [] | [
"linux",
"python",
"window_managers"
] | stackoverflow_0005960483_linux_python_window_managers.txt |
Q:
python xml.dom.minidom.parse and utf-8 xml file with cyrillic
sorry for my english :)
I have a problem with parsing xml file in utf-8 with cyrillic text in content
some rows from xml:
............
<programme start="20110405022000 +0300"
stop="20110405031000 +0300" channel="4000"> <title
lang="bul">Модерно</title>... | python xml.dom.minidom.parse and utf-8 xml file with cyrillic | sorry for my english :)
I have a problem with parsing xml file in utf-8 with cyrillic text in content
some rows from xml:
............
<programme start="20110405022000 +0300"
stop="20110405031000 +0300" channel="4000"> <title
lang="bul">Модерно</title> <sub-title
lang="bul"></sub-title> <desc
lang="bul">Тоук шоу. Моде... | [
"Your xml file has to be well formed, i.e. it must have only one root element. Try adding root tags at the beginning and the end of your input file.\n",
"You say \"\"\"If i change coding in first row to koi8-r it works. But i want to work with utf-8.\"\"\"\nI presume that you mean that it works if the XML file st... | [
1,
1,
1
] | [] | [] | [
"python",
"utf_8",
"xml"
] | stackoverflow_0005607095_python_utf_8_xml.txt |
Q:
What is the best way to get row_num in django?
What is the best way to get row_num in django ? Can we use a variable as counter in django template tags ?
{% for o in objects %}
<tr>
<td>{{ row_num }}</td>
<td>{{ o.first_name }}</td>
<td>{{ o.last_name }}</td>
</tr>
{% endfor %}
Thanks in advance.
A:
You c... | What is the best way to get row_num in django? | What is the best way to get row_num in django ? Can we use a variable as counter in django template tags ?
{% for o in objects %}
<tr>
<td>{{ row_num }}</td>
<td>{{ o.first_name }}</td>
<td>{{ o.last_name }}</td>
</tr>
{% endfor %}
Thanks in advance.
| [
"You can use the forloop template tag :\n\nforloop.counter -> The current iteration of the loop (1-indexed)\nforloop.counter0 -> The current iteration of the loop (0-indexed)\nforloop.revcounter -> The number of iterations from the end of the loop (1-indexed)\nforloop.revcounter0 -> The number of iterations from th... | [
4,
0
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0005961265_django_python_templates.txt |
Q:
What is the best pythonic way of wrapping an object?
I would like to be able to wrap any object in Python. The following does not seem to be possible, would you know why?
class Wrapper:
def wrap(self, obj):
self = obj
a = list()
b = Wrapper().wrap(a)
# can't do b.append
Thank you!
A:
Try with the g... | What is the best pythonic way of wrapping an object? | I would like to be able to wrap any object in Python. The following does not seem to be possible, would you know why?
class Wrapper:
def wrap(self, obj):
self = obj
a = list()
b = Wrapper().wrap(a)
# can't do b.append
Thank you!
| [
"Try with the getattr python magic :\nclass Wrapper:\n def wrap(self, obj):\n self.obj = obj\n def __getattr__(self, name):\n return getattr(self.obj, name)\n\na = list()\nb = Wrapper()\nb.wrap(a)\n\nb.append(10)\n\n",
"Perhaps what you are looking for, that does the job you are looking to do,... | [
5,
1,
0,
0
] | [] | [] | [
"design_patterns",
"python",
"wrapper"
] | stackoverflow_0005961313_design_patterns_python_wrapper.txt |
Q:
Python Matrix multiplication; numpy array
I have some problem with matrix multiplication:
I want to multiplicate for example a and b:
a=array([1,3]) # a is random and is array!!! (I have no impact on that)
# there is a just for example what I want to do...
... | Python Matrix multiplication; numpy array | I have some problem with matrix multiplication:
I want to multiplicate for example a and b:
a=array([1,3]) # a is random and is array!!! (I have no impact on that)
# there is a just for example what I want to do...
b=[[[1], [2]], #b is also r... | [
"Your b seem to have an unnecessary dimension. \nWith proper b you can just use dot(.), like:\nIn []: a\nOut[]: array([1, 3])\nIn []: b\nOut[]:\narray([[1, 2],\n [3, 2],\n [4, 6],\n [2, 3]])\nIn []: dot(b, a).reshape((2, -1))\nOut[]:\narray([[ 7, 9],\n [22, 11]])\n\n",
"How about this:\n... | [
7,
3
] | [
"result = \\\n[[sum(reduce(lambda x,y:x[0]*y[0]+x[1]*y[1],(a,[b1 for b1 in row]))) \\\n for row in b][i:i+2] \\\n for i in range(0, len(b),2)]\n\n"
] | [
-1
] | [
"arrays",
"matrix",
"numpy",
"python"
] | stackoverflow_0005955851_arrays_matrix_numpy_python.txt |
Q:
python: many to many groupings using iterator module
I have an iterable, items of which map to multiple groups. How do I group the items using an iterator module?
animals = (human, frog, giraffe, fish)
Here human, frog, etc are objects with attributes: is_land_dwelling and is_water_dwelling.
I want to group anim... | python: many to many groupings using iterator module | I have an iterable, items of which map to multiple groups. How do I group the items using an iterator module?
animals = (human, frog, giraffe, fish)
Here human, frog, etc are objects with attributes: is_land_dwelling and is_water_dwelling.
I want to group animals based on these attributes
groupings = dwelling_classif... | [
"def is_water_dwelling(animal):\n return animal in ('frog', 'fish')\n\n\ndef is_land_dwelling(animal):\n return animal in ('frog', 'human', 'giraffe')\n\nanimals = ('human', 'frog', 'fish', 'giraffe')\n\nland_dwelling = (x for x in animals if is_land_dwelling(x))\nwater_dwelling = (x for x in animals if is_wa... | [
3
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0005961912_iterator_python.txt |
Q:
What is a complete list of Exceptions that can be thrown by shutil.rmtree
I am using the rmtree method from shutil in Python (2.7).
What are all possible exceptions that can occur while calling this method?
A:
According to the implementation, you'll have to check OSError.
But you can use the argument ignore_erro... | What is a complete list of Exceptions that can be thrown by shutil.rmtree | I am using the rmtree method from shutil in Python (2.7).
What are all possible exceptions that can occur while calling this method?
| [
"According to the implementation, you'll have to check OSError.\nBut you can use the argument ignore_errors=True on call to...ignore errors ;) or give a callback onerror that will check the exceptions during the execution of file removal. (cf shutil.rmtree documentation)\n",
"Unless you do something very funky, o... | [
10,
3
] | [] | [] | [
"python",
"shutil"
] | stackoverflow_0005962152_python_shutil.txt |
Q:
Any flaw in the logic of using qtimer and qthread?
I have a GUI developed using pyqt4 which has a run button. on run button click, I invoke a timer and a thread. the timer keeps monitoring the thread. on the thread I invoke a command prompt to execute the test cases. I want the thread to be alive till the command ... | Any flaw in the logic of using qtimer and qthread? | I have a GUI developed using pyqt4 which has a run button. on run button click, I invoke a timer and a thread. the timer keeps monitoring the thread. on the thread I invoke a command prompt to execute the test cases. I want the thread to be alive till the command prompt is opened and want to say it as dead once I close... | [
"This code:\nif self.run_timer:\n run_monitor_object = RunMonitor()\n print 'Starting the thread...........'\n run_monitor_object.start()\n self.run_timer = False\n\nif run_monitor_object.isAlive():\n print 'Thread Alive...'\nelse:\n print 'Thread is Dead....'\n\nIs wrong. If the first branch isn'... | [
0
] | [] | [] | [
"multithreading",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0005961640_multithreading_pyqt_pyqt4_python.txt |
Q:
Calling TBB 'parallel_for' in python thread
I have a custom c++ module for python that exposes functions, some of which use TBB (tbb21_015oss) to accelerate processing.
Until now, I had no problem when calling a TBB-accelerated function from Python (2.6.2) in a Win32 environment.
But now, I have a problem when cal... | Calling TBB 'parallel_for' in python thread | I have a custom c++ module for python that exposes functions, some of which use TBB (tbb21_015oss) to accelerate processing.
Until now, I had no problem when calling a TBB-accelerated function from Python (2.6.2) in a Win32 environment.
But now, I have a problem when calling such a function from a Python thread (create... | [
"With TBB 2.1, each external thread that uses TBB should first create its own task_scheduler_init object; a single global object will not work.\nLater versions of TBB relaxed this requirement; now such a thread-specific initialization object is created implicitly if absent.\nYou might try whether mechanical replace... | [
2
] | [] | [] | [
"c++",
"python",
"tbb",
"windows"
] | stackoverflow_0005961519_c++_python_tbb_windows.txt |
Q:
numpy: boolean indexing and memory usage
Consider the following numpy code:
A[start:end] = B[mask]
Here:
A and B are 2D arrays with the same number of columns;
start and end are scalars;
mask is a 1D boolean array;
(end - start) == sum(mask).
In principle, the above operation can be carried out using O(1) tempo... | numpy: boolean indexing and memory usage | Consider the following numpy code:
A[start:end] = B[mask]
Here:
A and B are 2D arrays with the same number of columns;
start and end are scalars;
mask is a 1D boolean array;
(end - start) == sum(mask).
In principle, the above operation can be carried out using O(1) temporary storage, by copying elements of B directl... | [
"The line\nA[start:end] = B[mask]\n\nwill -- according to the Python language definition -- first evaluate the right hand side, yielding a new array containing the selected rows of B and occupying additional memory. The most efficient pure-Python way I'm aware of to avoid this is to use an explicit loop:\nfrom ite... | [
3,
2
] | [] | [] | [
"large_data",
"memory_management",
"numpy",
"python"
] | stackoverflow_0005961932_large_data_memory_management_numpy_python.txt |
Q:
Semantics of SUID (Set-User-ID)
it seems that I have some trouble understanding the semantics of the SUID bit, perhaps someone can help me clarify the situation.
My understanding of the semantic of the SUID bit are as follows:
When I set the SUID bit with a file, then the file will be executed as the owner of the ... | Semantics of SUID (Set-User-ID) | it seems that I have some trouble understanding the semantics of the SUID bit, perhaps someone can help me clarify the situation.
My understanding of the semantic of the SUID bit are as follows:
When I set the SUID bit with a file, then the file will be executed as the owner of the file and not as the caller of the fil... | [
"Setting the SUID bit on a *.py file does not help in any way here since the script is executed by the Python interpreter which must be set SUID in this case. Using 'sudo' is your better friend here.\n",
"Setting SUID does not work for scripts, because the kernel sees the #! (shebang - magic number 0x23 0x21 - ma... | [
8,
4,
0
] | [] | [] | [
"permissions",
"python",
"semantics",
"suid"
] | stackoverflow_0005523279_permissions_python_semantics_suid.txt |
Q:
Python - Graph Data Structure - How Do I Implement Breadth-First Search to Find Reachable Vertices Correctly
In Python, I have a Graph class that has a dictionary of vertex objects. Each vertex object has a dictionary of edges (which consist of a starting node, ending node, and a weight...imagine the end of arrow ... | Python - Graph Data Structure - How Do I Implement Breadth-First Search to Find Reachable Vertices Correctly | In Python, I have a Graph class that has a dictionary of vertex objects. Each vertex object has a dictionary of edges (which consist of a starting node, ending node, and a weight...imagine the end of arrow pointing to another node with a cost-to-travel number assigned to it).
With these classes, I'm graphing--well, a g... | [
"Your code is way too complicated. \nStart with a code just implementing the fundamentals and add features gradually. In order to get you started I'll post something simple but fundamental when handling graphs.\nfrom collections import deque\n\nclass fringe(object):\n def __init__(self, kind= 'stack'):\n ... | [
1
] | [] | [] | [
"breadth_first_search",
"graph",
"python"
] | stackoverflow_0005960649_breadth_first_search_graph_python.txt |
Q:
django test client trouble
I've got a problem... we're writing project using django, and i'm trying to use django.test.client with nose test-framework for tests.
Our code is like this:
from simplejson import loads
from urlparse import urljoin
from django.test.client import Client
TEST_URL = "http://smakly.localh... | django test client trouble | I've got a problem... we're writing project using django, and i'm trying to use django.test.client with nose test-framework for tests.
Our code is like this:
from simplejson import loads
from urlparse import urljoin
from django.test.client import Client
TEST_URL = "http://smakly.localhost:9090/"
def test_register():... | [
"Probably want django-nose if you want to use nose.\nhttp://github.com/jbalogh/django-nose\nI would recommend using the TestCase class\nhttp://docs.djangoproject.com/en/dev/topics/testing/\nhttp://www.djangoproject.com/documentation/models/test_client/\n",
"Shameless self-promotion: exactly for those reasons I ma... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002279917_django_python.txt |
Q:
Python - AttributeError: index
I am stuck here...
Connecting to t3://localhost:7001 with userid weblogic ...
Successfully connected to Admin Server 'examplesServer' that belongs to domain 'wl_server'.
Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
A... | Python - AttributeError: index | I am stuck here...
Connecting to t3://localhost:7001 with userid weblogic ...
Successfully connected to Admin Server 'examplesServer' that belongs to domain 'wl_server'.
Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.
[... | [
"The error tells you that this line:\nappName=dep_file[num1:num2]\n\nIs wrong. Are you sure the dep_file object can be indexed with a slice?\nMaybe you should call getName() on dep_name first?\n"
] | [
2
] | [] | [] | [
"attributeerror",
"indexing",
"python"
] | stackoverflow_0005962920_attributeerror_indexing_python.txt |
Q:
Python Option Parser: Boolean flag with optional parameters
I'm using optparse.OptionParser to manage arguments for some scripts, and something I was wondering / would like to do is have boolean flags (i.e action=store_true) that can also accept a parameter.
To put this into context, I've got a application that ca... | Python Option Parser: Boolean flag with optional parameters | I'm using optparse.OptionParser to manage arguments for some scripts, and something I was wondering / would like to do is have boolean flags (i.e action=store_true) that can also accept a parameter.
To put this into context, I've got a application that can use as many GPU/Processors as it finds on the machine. For a va... | [
"You can use the callback action to implement this quite easily. In particular, example 6 in the documentation of the callback action of OptionParser discusses a variable number of arguments. Here's a telling quote from that example:\n\nThings get hairy when you want an\n option to take a variable number of\n arg... | [
1
] | [] | [] | [
"command_line_arguments",
"optional_parameters",
"parameter_passing",
"python"
] | stackoverflow_0005962890_command_line_arguments_optional_parameters_parameter_passing_python.txt |
Q:
Expandable List using Python Tkinter
I know how to create a Listbox using Tkinter but this only allows me to display a list of single items. I need to create a expandable list that allows the user to hit something along the lines of a + next to the item which in turn opens up a new list with + buttons next to each... | Expandable List using Python Tkinter | I know how to create a Listbox using Tkinter but this only allows me to display a list of single items. I need to create a expandable list that allows the user to hit something along the lines of a + next to the item which in turn opens up a new list with + buttons next to each item until you reach the leaf of a list. ... | [
"The widget you are looking for is commonly called a \"tree\" or \"hierarchical tree\".\nIf you're using python2.7 or greater you can use ttk.Treeview widget. \nFor older versions of python you can use Tix.Tree. You can also search for \"tkinter tree\" on google and you'll find several other variations such as this... | [
2
] | [] | [] | [
"expandable",
"list",
"listbox",
"python",
"tkinter"
] | stackoverflow_0005958868_expandable_list_listbox_python_tkinter.txt |
Q:
How to open a CSV,read a particular header of column and get the highest value
I am a beginner in python and I want to know How to open a CSV,read a particular header of column and get the highest value.The value should be stored in a variab
regards,
sid
A:
You can use the CSV-module for reading the file. To get... | How to open a CSV,read a particular header of column and get the highest value | I am a beginner in python and I want to know How to open a CSV,read a particular header of column and get the highest value.The value should be stored in a variab
regards,
sid
| [
"You can use the CSV-module for reading the file. To get the highest value, you will have to read the entire file and and always remember the highest value seen so far.\n",
"Use the csv module to parse the file. Calling next(reader) for a csv.Reader object will yield the first line as a tuple. You can use the i... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005963077_python.txt |
Q:
Adding wxpython panel classes to sizers
I want to add panel classes to a sizer in a frame class that I will call in the main line of the code.
The error I get is TypeError: wx.Window, wx.Sizer, wx.Size, or (w,h) expected for item. I assume this has to do with the fact that it is a panel class and not the instance ... | Adding wxpython panel classes to sizers | I want to add panel classes to a sizer in a frame class that I will call in the main line of the code.
The error I get is TypeError: wx.Window, wx.Sizer, wx.Size, or (w,h) expected for item. I assume this has to do with the fact that it is a panel class and not the instance of the panel class..
Either way, how would I ... | [
"Like you said yourself: You're not passing instances of the step_1 and step_2 classes to the sizer, which of course you should be. Simply create instances of them:\nclass main_frame(wx.Frame):\n \"\"\"Main Frame holding the main panel.\"\"\"\n def __init__(self,*args,**kwargs):\n wx.Frame.__init__(sel... | [
4
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005958531_python_wxpython.txt |
Q:
python convert date and time into linux timestmap
i have timestamps in the following format:
2011 February 2nd 13h 27min 21s
110202 132721
I want to convert 110202 132721 into the corresponding linux timestamp: 1296682041
Is there any quick efficient way to achieve this?
A:
Something like
>>> s = ... | python convert date and time into linux timestmap | i have timestamps in the following format:
2011 February 2nd 13h 27min 21s
110202 132721
I want to convert 110202 132721 into the corresponding linux timestamp: 1296682041
Is there any quick efficient way to achieve this?
| [
"Something like\n>>> s = \"110202 132721\"\n>>> print time.mktime(time.strptime(s, \"%y%m%d %H%M%S\"))\n1296653241.0\n\nThis interprets the time as a local time (your current time zone).\n",
"To create a Unix timestamp, use the time.mktime(t) function. It takes a time.struct_time object.\nThe objects definition ... | [
3,
2,
1
] | [] | [] | [
"date",
"python",
"timestamp"
] | stackoverflow_0005963353_date_python_timestamp.txt |
Q:
Building up timetabling problem with lots of variables
I have a classic timetabling problem consisting of the variables classes(~100), rooms(20),terms(8) and weekdays(5).
To just simplfy the problem, following are the reduced constraints.
A day is 9 hours.
Some classes are mandatory for students, and mandatory cla... | Building up timetabling problem with lots of variables | I have a classic timetabling problem consisting of the variables classes(~100), rooms(20),terms(8) and weekdays(5).
To just simplfy the problem, following are the reduced constraints.
A day is 9 hours.
Some classes are mandatory for students, and mandatory classes of the terms 1,3,5,7 (and for 2,4,6,8) must not overlap... | [
"Take a look at the curriculum course example code of Drools Planner. It's basically the same thing, but the terminology is slightly different: each course (= class) has a number of lectures which need to be scheduled into a room (=room) and period (= each term on each weekday is a period).\nThe trick is to keep a ... | [
1
] | [
"I've ended up with a solution that bundles \"chosing the variables wisely\" and \"reducing the domains at selection\". Below are the snippets from the django based timetabling application i'm doing:\nclass Course(models.Model):\n name = models.CharField(max_length=255, null=False, blank=False)\n duration = m... | [
-2
] | [
"constraint_satisfaction",
"constraints",
"python",
"resource_scheduling",
"timetable"
] | stackoverflow_0005921097_constraint_satisfaction_constraints_python_resource_scheduling_timetable.txt |
Q:
Python print output while embedding Python in C\C++
Where does Python print to, if the print statement is in a python function, called from C\C++ in an embedded Python configuration?
A:
In python, the print statement writes into sys.stdout (which is the standard output) even in an embedded app, you should see yo... | Python print output while embedding Python in C\C++ | Where does Python print to, if the print statement is in a python function, called from C\C++ in an embedded Python configuration?
| [
"In python, the print statement writes into sys.stdout (which is the standard output) even in an embedded app, you should see your prints in the console that started the application.\n"
] | [
3
] | [] | [] | [
"python",
"python_embedding",
"stdout"
] | stackoverflow_0005963366_python_python_embedding_stdout.txt |
Q:
Memory never released when using Python classes and numpy
Basically I am not going to post all of the code here but I will provide a generic example. I have a class that has a function to run and create a large array of values. This array shouldn't be much bigger than 10MB from my estimates. Within the functions i... | Memory never released when using Python classes and numpy | Basically I am not going to post all of the code here but I will provide a generic example. I have a class that has a function to run and create a large array of values. This array shouldn't be much bigger than 10MB from my estimates. Within the functions it makes new and modifies arrays that should be collected up aft... | [
"What are you trying to do?\ntemp = self.largeArray = zeros((1000,1000,10,20))\nfor y in temp.size:\n for x in temp1.size:\n self.largeArray[x,y] = train()\n\ntemp.size equals 200,000,000. How can you store anything into largeArray[x,y] if the second dimension of this array is only 1000?\n"
] | [
0
] | [] | [] | [
"malloc",
"numpy",
"python",
"scipy",
"tcmalloc"
] | stackoverflow_0005963485_malloc_numpy_python_scipy_tcmalloc.txt |
Q:
Got an error while connecting to database
I am unable to connected to database in linux using psycopg2. I have postgresql installed in linux and my code is:
import psycopg2
def testEgg():
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
cur = conn.cursor()
cur.execute("CREA... | Got an error while connecting to database | I am unable to connected to database in linux using psycopg2. I have postgresql installed in linux and my code is:
import psycopg2
def testEgg():
conn = psycopg2.connect("dbname = myDatabase user = postgres port = 5432")
cur = conn.cursor()
cur.execute("CREATE TABLE egg ( num integer, data varchar);")
... | [
"It's not a problem due to your code, but due to the permission of the postgres user.\nYou should create a new user to access to your database and replace this :\nconn = psycopg2.connect(\"dbname = myDatabase user = postgres port = 5432\")\n\nby (replace <your_user> by your real user name ...)\nconn = psycopg2.conn... | [
0
] | [] | [] | [
"linux",
"psycopg2",
"python"
] | stackoverflow_0005963739_linux_psycopg2_python.txt |
Q:
calculating the next day from a "YYYYMMDD" formatted string
How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime impo... | calculating the next day from a "YYYYMMDD" formatted string | How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y... | [
"Here is an example of how to do it:\nimport time\nfrom datetime import date, timedelta\n\nt=time.strptime('20110531','%Y%m%d')\nnewdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)\nprint newdate.strftime('%Y%m%d')\n\n",
">>> from datetime import datetime\n>>> print datetime.strptime('20110531', '%Y%m%d')\n20... | [
12,
4,
3
] | [] | [] | [
"python",
"python_2.4"
] | stackoverflow_0005963854_python_python_2.4.txt |
Q:
Python: Stop the socket-receiving-process
I receive data from some device via socket-module.
But after some time the device stops sending packages.
Then I want to interupt the for-loop.
While True doesn't work, because he receives more then 100 packages.
How can I stop this process?
s stands for socket.
...
for i ... | Python: Stop the socket-receiving-process | I receive data from some device via socket-module.
But after some time the device stops sending packages.
Then I want to interupt the for-loop.
While True doesn't work, because he receives more then 100 packages.
How can I stop this process?
s stands for socket.
...
for i in range(packages100):
data = s.recv(4)
... | [
"If your peer really just stops sending data, as opposed to closing the connection, this is tricky and you'll be forced to resort to asynchronous reading from this socket.\nPut it in asynchronous mode (the docs and Google are your friends), and try to read it each time, instead of the blocking read. You can then ju... | [
3,
2
] | [] | [] | [
"break",
"interrupt",
"python",
"recv"
] | stackoverflow_0005963889_break_interrupt_python_recv.txt |
Q:
I need help choosing and printing text in PYGTK
I am trying to make a program that looks like the one below.
Image
I that file is called Tux image.png and i have another called File to use.txt that looks like this
Microsoft
Apple
HP
Dell
Linux
Blackberry
I need to make the program appear like the one above by choo... | I need help choosing and printing text in PYGTK | I am trying to make a program that looks like the one below.
Image
I that file is called Tux image.png and i have another called File to use.txt that looks like this
Microsoft
Apple
HP
Dell
Linux
Blackberry
I need to make the program appear like the one above by choosing the word Linux and printing it under the image.H... | [
"I'm not sure what you need, but you can read the use.txt file like this:\nfileobj = open(\"use.txt\")\nfile_content = fileobj.read()\n\n'file_content' should now contain:\nMicrosoft Apple HP Dell Linux Blackberry\n\nYou can split them in a list:\nchoices = file_content.split()\n\nAfter that you could use gtk.Combo... | [
0,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0005950718_pygtk_python.txt |
Q:
Does Python have a module for parsing HTTP requests and responses?
httplib (now http.client) and friends all have conn.getresponse() and an HTTPResponse class, but the server-side operations of conn.getrequest() and an HTTPRequest class seem to be lacking.
I understand that BaseHTTPServer and BaseHTTPRequestHandle... | Does Python have a module for parsing HTTP requests and responses? | httplib (now http.client) and friends all have conn.getresponse() and an HTTPResponse class, but the server-side operations of conn.getrequest() and an HTTPRequest class seem to be lacking.
I understand that BaseHTTPServer and BaseHTTPRequestHandler can perform this functionality, but they don't expose these methods fo... | [
"Jeff, to enable parsing I create a small nine-line subclass of the base HTTP request handler:\nfrom BaseHTTPServer import BaseHTTPRequestHandler\nfrom StringIO import StringIO\n\nclass HTTPRequest(BaseHTTPRequestHandler):\n def __init__(self, request_text):\n self.rfile = StringIO(request_text)\n ... | [
47,
2,
2
] | [] | [] | [
"http",
"parsing",
"python"
] | stackoverflow_0002115410_http_parsing_python.txt |
Q:
Python regex issue
I'm trying to extract ALL phone screen resolutions from the WURFL XML file with the below Python script. The problem is that I only get the first match, though. Why? How could I get all matches?
The WURFL XML file can be found at http://sourceforge.net/projects/wurfl/files/WURFL/latest/wurfl-lat... | Python regex issue | I'm trying to extract ALL phone screen resolutions from the WURFL XML file with the below Python script. The problem is that I only get the first match, though. Why? How could I get all matches?
The WURFL XML file can be found at http://sourceforge.net/projects/wurfl/files/WURFL/latest/wurfl-latest.zip/download?use_mir... | [
"First, use an XML parser instead of regular expressions. You'll be happier in the long run.\nSecond, if you insist on using regexes, use finditer() instead of findall().\nThird, your regex matches from the first entry to the last one (the .* is greedy, and you have set DOTALL mode), so either see the first paragra... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"wurfl",
"xml"
] | stackoverflow_0005963225_python_regex_wurfl_xml.txt |
Q:
How to Iterate a dictionary of references to matplotlib figures
I have a number of functions each of which creates one or more figures. As the figures are created, a reference is added to a dictionary, like so:
self.figures['figureKey'] = figure()
In another function, I would like to iterate this dictionary and ... | How to Iterate a dictionary of references to matplotlib figures | I have a number of functions each of which creates one or more figures. As the figures are created, a reference is added to a dictionary, like so:
self.figures['figureKey'] = figure()
In another function, I would like to iterate this dictionary and save each of the figures; it would be nice to use the dictionary key ... | [
"Maybe I'm confused as to what you're doing... If you just want to save the figure, why not use the fig object's savefig method? \npyplot.savefig saves the active figure, but using a particular figure instance's fig.savefig method saves that particular figure, regardless of which one is active.\nimport matplotlib.p... | [
3,
2,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005957815_matplotlib_python.txt |
Q:
Python: Cannot Assign Function Call
I am having a problem such as:
def function (number):
for number in list:
number = number + 1
For example function(1):
for number in range(1,5):
number = number + 1
Error come back as "can't assign function call"
I would like to use that variable... | Python: Cannot Assign Function Call | I am having a problem such as:
def function (number):
for number in list:
number = number + 1
For example function(1):
for number in range(1,5):
number = number + 1
Error come back as "can't assign function call"
I would like to use that variable as a value for further calculations.
Hel... | [
"I think you have two problems. First, you are not naming your function or declaring it properly; you should do this:\ndef f(number):\n ...\n\nSecond, you are naming the function parameter number but on the next line you seem to be treating list as though it were the parameter. I think you mean to do this instead... | [
2,
0
] | [
"you have to use def to define a function\n"
] | [
-1
] | [
"python"
] | stackoverflow_0005964645_python.txt |
Q:
implement COM interface type library in python
I have a plugin that I'm trying to create as a sample for an application from the company I work for. I'm trying to write this plugin in Python.
The way the plugin architecture works is that the plugin needs to implement an interface defined in a provided COM type ... | implement COM interface type library in python | I have a plugin that I'm trying to create as a sample for an application from the company I work for. I'm trying to write this plugin in Python.
The way the plugin architecture works is that the plugin needs to implement an interface defined in a provided COM type library. So it is a COM client to that type library... | [
"You can simply use win32com.client.Dispatch():\nobject = win32com.client.Dispatch(\"Class.Name\")\nThis is the example from ActiveState quick start guide:\n>>> import win32com.client\n>>> w=win32com.client.Dispatch(\"Word.Application\")\n>>> w.Visible=1\n>>> w\n<win32com.gen_py.Microsoft Word 8.0 Object Library._A... | [
5
] | [] | [] | [
"com",
"python"
] | stackoverflow_0005964805_com_python.txt |
Q:
How to count number of lines after a certain line
I am trying to write a code that will count number of lines after certain line. I would like to compute all the lines that appear in my file after {A B} appearing in my file
{A B}
1 1
0.072 108.815
0.217 108.815
0.362 108.814
My code is as follows:
from __... | How to count number of lines after a certain line | I am trying to write a code that will count number of lines after certain line. I would like to compute all the lines that appear in my file after {A B} appearing in my file
{A B}
1 1
0.072 108.815
0.217 108.815
0.362 108.814
My code is as follows:
from __future__ import with_statement
def file_len(fname):
... | [
"Skip the lines up to and including the line you are looking for, and count the remaining ones:\ndef file_len(fname):\n with open(fname) as f:\n for line in f:\n if line.strip() == \"{A B}\":\n break\n return sum(1 for line in f)\n\n",
"Count total number of lines in f... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0005965040_python.txt |
Q:
getting recarray into postgres using psycopg2
Just would like to get a quick idea on the best, meaning least coding, way to get lots of data in recarray into postgres using psycopg2. I have seen some stuff using cast but really I thought it would be strait forward and I could find something good on the web.
Examp... | getting recarray into postgres using psycopg2 | Just would like to get a quick idea on the best, meaning least coding, way to get lots of data in recarray into postgres using psycopg2. I have seen some stuff using cast but really I thought it would be strait forward and I could find something good on the web.
Example have census data with 200 variables read in reca... | [
"Psycopg can be extended using a new adapter (when you want to pass a Python object to Postgres) or a new typecaster (when you want to read from Postgres and get Python objects).\nIt looks like you have to register some of the existing adapters for the numpy types, for instance:\n>>> psycopg2.extensions.register_ad... | [
2
] | [] | [] | [
"numpy",
"postgresql",
"psycopg2",
"python",
"recarray"
] | stackoverflow_0005946034_numpy_postgresql_psycopg2_python_recarray.txt |
Q:
custom views within Djangocms?
I haven't found a satisfactory way of doing this: I have a djangocms setup that is working fine. But I need to add content from a table outside the CMS to my homepage and render that content on the template. I can do this, but editing the urls.py within CMS to use my views like so...... | custom views within Djangocms? | I haven't found a satisfactory way of doing this: I have a djangocms setup that is working fine. But I need to add content from a table outside the CMS to my homepage and render that content on the template. I can do this, but editing the urls.py within CMS to use my views like so...
url(r'^', 'myapp.views.slideshow_in... | [
"You can hook a custom app instance to any Django-CMS page. Here's the documentation on how to do so: http://docs.django-cms.org/en/2.1.3/extending_cms/app_integration.html#app-hooks You shouldn't need to alter the base url patterns to specifically re-route / to your view.\nBefore custom app-hooks were available, I... | [
6
] | [] | [] | [
"django",
"django_cms",
"python"
] | stackoverflow_0005964973_django_django_cms_python.txt |
Q:
Memory error in np.hstack()
I am trying to execute this code:
for i in Fil:
for k in DatArr:
a = np.zeros(0)
for j in Bui:
a = np.hstack([a,DatDifCor[k][i,j]])
DatDifPlt[k].update({i:a})
But it gives me this error:
Traceback (most recent call last):
File "<i... | Memory error in np.hstack() | I am trying to execute this code:
for i in Fil:
for k in DatArr:
a = np.zeros(0)
for j in Bui:
a = np.hstack([a,DatDifCor[k][i,j]])
DatDifPlt[k].update({i:a})
But it gives me this error:
Traceback (most recent call last):
File "<ipython console>", line 5, in <mod... | [
"A MemoryError always means that an attempt to allocate memory failed. Trying to create an array bigger than the maximum array size results in a ValueError:\n>>> a = numpy.arange(500000000)\n>>> numpy.hstack((a, a))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/pym... | [
2
] | [] | [] | [
"memory_management",
"numpy",
"out_of_memory",
"python"
] | stackoverflow_0005965667_memory_management_numpy_out_of_memory_python.txt |
Q:
Python's profile module: :1(?)
I am using Python's (v2.4) profile module to profile a numpy script, and the following entry appears to account for the bulk of the execution time:
ncalls tottime percall cumtime percall filename:lineno(function)
256/1 0.000 0.000 7.710 7.710 <string>:1(?)
Unfortuna... | Python's profile module: :1(?) | I am using Python's (v2.4) profile module to profile a numpy script, and the following entry appears to account for the bulk of the execution time:
ncalls tottime percall cumtime percall filename:lineno(function)
256/1 0.000 0.000 7.710 7.710 <string>:1(?)
Unfortunately, its appearance makes it hard t... | [
"Ignore this line. It is an artifact of how the profiler is implemented. It is not telling you anything useful. Look at the \"tottime\" value for it: 0.000. \"tottime\" is the amount of time spent executing \"<string>:1(?)\" excluding time spent executing children of it. So, no time is spent here. \"cumtime\"... | [
26
] | [] | [] | [
"profile",
"profiler",
"profiling",
"python"
] | stackoverflow_0005964126_profile_profiler_profiling_python.txt |
Q:
Django; How can i serve templates/images/css/js from inside custom 'skin' directory?
I'm trying to make a skinnable Django project.
What i'm having problems with is figuring out how i can serve file(s) from within the skin directory, and not from the media dir, so that all the skin's images/css/js files can reside... | Django; How can i serve templates/images/css/js from inside custom 'skin' directory? | I'm trying to make a skinnable Django project.
What i'm having problems with is figuring out how i can serve file(s) from within the skin directory, and not from the media dir, so that all the skin's images/css/js files can reside in the skin's folder(s).
A user should be able to choose a skin name , preferably by only... | [
"First thing, you should rather keep your static files in a static folder and only use media for uploaded content.\nThen within your static folder you could have a folder for each of your skin containing all the CSS, images and JS needed.\nFrom your skin template just import the files prefixed by both {{ STATIC_URL... | [
2,
1
] | [] | [] | [
"django",
"frameworks",
"python",
"web_applications"
] | stackoverflow_0005966021_django_frameworks_python_web_applications.txt |
Q:
Making Eclipse follow the PEP 8 formatting standards?
Is there any way to make Eclipse follow PEP 8 code formatting standards by default, and show warnings if such standards are broken?
A:
As ulidtko said in his comment, you can set the Eclipse Python editor to generate code in a certain way. If the Eclipse Pyt... | Making Eclipse follow the PEP 8 formatting standards? | Is there any way to make Eclipse follow PEP 8 code formatting standards by default, and show warnings if such standards are broken?
| [
"As ulidtko said in his comment, you can set the Eclipse Python editor to generate code in a certain way. If the Eclipse Python Editor has a Format option, you can format the Python code based on the Eclipse Python editor settings.\nHowever, you can't force anyone to use the Format option.\n"
] | [
0
] | [] | [] | [
"eclipse",
"pep8",
"python"
] | stackoverflow_0005965915_eclipse_pep8_python.txt |
Q:
Start creating websites by using Python
I am basically a PHP guy. now moving towards python. I am starting to learn python.
How do I install it and start working it, and develop websites .
I got totally confused with the alternative implementations in the download section of the Python site. Can you tell me what... | Start creating websites by using Python | I am basically a PHP guy. now moving towards python. I am starting to learn python.
How do I install it and start working it, and develop websites .
I got totally confused with the alternative implementations in the download section of the Python site. Can you tell me what "alternative implementations" means?.
I me... | [
"Just as a disclaimer, I interpret you saying \"run Python in a browser\" as \"making a website with Python.\"\nIf you want to start writing web applications in Python, you can either use CGI or use one of its many web app frameworks. Python is not like PHP in the sense that you can't just embed it in HTML. Many of... | [
18,
5,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005966059_python.txt |
Q:
When using setResultsName with listAllMatches true, some matched items are nested
Based on this grammar:
from pyparsing import *
g = quotedString.setParseAction( removeQuotes )
eg = Suppress('-') + quotedString.setParseAction( removeQuotes )
choice = Or( [ g.setResultsName("out",listAllMatches=True),
... | When using setResultsName with listAllMatches true, some matched items are nested | Based on this grammar:
from pyparsing import *
g = quotedString.setParseAction( removeQuotes )
eg = Suppress('-') + quotedString.setParseAction( removeQuotes )
choice = Or( [ g.setResultsName("out",listAllMatches=True),
eg.setResultsName("in",listAllMatches=True) ] )
grammar = ZeroOrMore( choice ) +... | [
"It's been a while since I've looked at this issue - the problem is that And's always return their tokens as lists, even if the contain only a single value.\nHere is an ungrouper that can clear this up for you, I'll include this in the next pyparsing release:\nungroup = lambda expr : TokenConverter(expr).setParseAc... | [
1
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0005962494_pyparsing_python.txt |
Q:
Python module for wiki markup
Is there a Python module for converting wiki markup to other languages (e.g. HTML)?
A similar question was asked here, What's the easiest way to convert wiki markup to html, but no Python modules are mentioned.
Just curious. :) Cheers.
A:
mwlib provides ways of converting MediaWiki ... | Python module for wiki markup | Is there a Python module for converting wiki markup to other languages (e.g. HTML)?
A similar question was asked here, What's the easiest way to convert wiki markup to html, but no Python modules are mentioned.
Just curious. :) Cheers.
| [
"mwlib provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats.\n",
"Django uses the following libraries for markup:\n\nMarkdown\nTextile\nreStructuredText\n\nYou can see how they're used in Django.\n",
"You should look at a good parser for Creole syntax: creole.py. I... | [
21,
9,
7,
2
] | [] | [] | [
"markup",
"python",
"wiki"
] | stackoverflow_0000154592_markup_python_wiki.txt |
Q:
Python object wrapper for lxml etree?
Given lxml.etree is it possible to somehow construct an object representation of the tree, so that sub-elements can be accessed in object-like fashion (with '.' operator)?
I know lxml has a library called objectify but it looks like it can be only constructed given raw XML and... | Python object wrapper for lxml etree? | Given lxml.etree is it possible to somehow construct an object representation of the tree, so that sub-elements can be accessed in object-like fashion (with '.' operator)?
I know lxml has a library called objectify but it looks like it can be only constructed given raw XML and adding new elements to the tree still requ... | [
"I guess you have to override the __setattribute__ respectively the __getattribute__ operators. I guess you have to subclass the etree.Element class to achieve this.\nBut, on the other hand this API would also be quite impractical, since there might be multiple child-nodes with the same tag name.\nTo find elements ... | [
1
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0005966748_lxml_python_xml.txt |
Q:
How to write lists "one by one" to a binary file in python?
I have a piece of code which generates quite large lists in each iteration. To save memory I want to write each list to a binary file in each iteration after the list has been generated.
I have tried this with text files(even setting the parameter to "wb"... | How to write lists "one by one" to a binary file in python? | I have a piece of code which generates quite large lists in each iteration. To save memory I want to write each list to a binary file in each iteration after the list has been generated.
I have tried this with text files(even setting the parameter to "wb" in linux). "wb" seems not to have any effect for the file to be ... | [
"Since you mentioned the need for compressibility, I'd suggest using pickle with the gzip module to compress your output. You can write and read back your lists one at a time, here's an example of how:\nimport gzip, pickle\n\noutput = gzip.open('pickled.gz', 'wb', compresslevel=9)\n\nfor x in range(10):\n outpu... | [
4,
1,
1
] | [] | [] | [
"binary",
"file",
"list",
"python"
] | stackoverflow_0005966416_binary_file_list_python.txt |
Q:
Can't communicate via socket on Mac OS X
I'm working on some software that consists of a server and clients on one machine that communicate via local sockets.
The server (written in Java) opens a java.net.ServerSocket on port 9000, and the clients (in either Java or Python) have to connect to localhost:9000 to com... | Can't communicate via socket on Mac OS X | I'm working on some software that consists of a server and clients on one machine that communicate via local sockets.
The server (written in Java) opens a java.net.ServerSocket on port 9000, and the clients (in either Java or Python) have to connect to localhost:9000 to communicate.
In Windows and Linux, this works fin... | [
"Maybe this will be helpful for someone as I had very similar issue on Mac OS with Java client not being able to open socket for a Web server (lighttpd serving static file): no firewall running; works in Web browser and with CLI tools (curl and wget); same for different, non-standard, free ports. Disabling IPv6 sup... | [
0
] | [] | [] | [
"java",
"macos",
"networking",
"python",
"sockets"
] | stackoverflow_0003268111_java_macos_networking_python_sockets.txt |
Q:
Why I can't convert a list of str to a list of floats?
I'm starting to write a code, but it fails at the beginning.
This is my code:
import csv
reader = csv.reader(open("QstartRefseqhg19.head"), dialect='excel-tab' )
for row in reader:
C = row[1].split(",")[1:]
C1 = [float(i) for i in C]
print C1
a... | Why I can't convert a list of str to a list of floats? | I'm starting to write a code, but it fails at the beginning.
This is my code:
import csv
reader = csv.reader(open("QstartRefseqhg19.head"), dialect='excel-tab' )
for row in reader:
C = row[1].split(",")[1:]
C1 = [float(i) for i in C]
print C1
and the error log says:
Traceback (most recent call last):
... | [
"Your input line is ended with a comma, e.g.:\n0,182,283,388,470,579,757,\n\nSo naturally, this will be split into:\n['0', '182', '283', '388', '470', '579', '757', '']\n\nThe last element will always be an empty string, ''. You'd need to account for this. One way is simply by ignoring it:\nC1 = [float(i) for i in ... | [
7,
0
] | [] | [] | [
"csv",
"floating_point",
"list",
"python",
"string"
] | stackoverflow_0005958136_csv_floating_point_list_python_string.txt |
Q:
QuerySet caching: executing get after filter was fired
How many database queries will be executed for the following code:
q = SomeModel.objects.filter(pk__in=ids)
print q # The actual query is executed and the result
# set evaluated
m = q.get(pk=ids[0])
print m # Does it reuse the evaluated resul... | QuerySet caching: executing get after filter was fired | How many database queries will be executed for the following code:
q = SomeModel.objects.filter(pk__in=ids)
print q # The actual query is executed and the result
# set evaluated
m = q.get(pk=ids[0])
print m # Does it reuse the evaluated result set
# or does it hit the database the second t... | [
"Since querysets are evaluated lazily if you do:\nq = SomeModel.objects.filter(pk__in=ids)\n\n...immediately folllowed by (i.e., without using print):\nm = q.get(pk=ids[0])\n\nYou'll end up with one SQL query. It'll AND together the first query with the second. It's safe to continue adding to querysets this way. In... | [
1
] | [] | [] | [
"caching",
"database",
"django",
"django_queryset",
"python"
] | stackoverflow_0005967006_caching_database_django_django_queryset_python.txt |
Q:
displaylist of children in parent model one-to-many
I am learning django admin, i have to models with a one-to-many relation between them.
I got something like Manufacturer model where i can add different car manufacturers, and Car model for adding cars. In my django admin page i want to be able to display_list of... | displaylist of children in parent model one-to-many | I am learning django admin, i have to models with a one-to-many relation between them.
I got something like Manufacturer model where i can add different car manufacturers, and Car model for adding cars. In my django admin page i want to be able to display_list of all cars manfuctred by say manufacturer1 when i click on... | [
"Answer for your updated question:\nthe way to do it could be by using ProxyModels and overriding ModelAdmin.queryset\nYou extend the Car model via FordCar, GMCar and use proxy=True in the Meta class, for both those.\nThen you can register seperate admins for each of FordCar and GMCar and override the queryset meth... | [
2,
1,
1
] | [] | [] | [
"displaylist",
"django",
"foreign_key_relationship",
"python"
] | stackoverflow_0005965096_displaylist_django_foreign_key_relationship_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.