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:
Making a PythonCard File Dialog single select?
I'm working on a python application and have chosen to build the gui with PythonCard. I have need to have the user select a file to open, and in the context, selecting more than 1 file doesn't make sense. I can successfully create a file dioalog with
dialog.fileDial... | Making a PythonCard File Dialog single select? | I'm working on a python application and have chosen to build the gui with PythonCard. I have need to have the user select a file to open, and in the context, selecting more than 1 file doesn't make sense. I can successfully create a file dioalog with
dialog.fileDialog(self, 'Open Input File', '', '')
And I would ima... | [
"Try setting the last line to wx.OPEN - that should be it. It seems that PythonCard specifies a dialog's main style as wx.OPEN | wx.MULTIPLE, so overriding it to just open should do the trick.\n",
"Here's a reference for PythonCard dialogs:\npythoncard.sourceforge.net/dialogs\nIt provides an explanation of the ar... | [
1,
0
] | [] | [] | [
"python",
"pythoncard"
] | stackoverflow_0002065934_python_pythoncard.txt |
Q:
ctypes behaving strangely in Python interpreter
I am having a funny issue with ctypes; while it seems to work in regular python scripts, when I use it in the interpreter with printf() it prints the length of the string after the string itself. A demo:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] o... | ctypes behaving strangely in Python interpreter | I am having a funny issue with ctypes; while it seems to work in regular python scripts, when I use it in the interpreter with printf() it prints the length of the string after the string itself. A demo:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "lice... | [
"From the printf(3) man page:\n\nUpon successful return, these functions return the number of characters printed (not including the trailing ’\\0’ used to end output to strings).\n\nThe python interpreter is displaying the return code of printf() after you call it. Since you don't have a newline \\n at the e... | [
8
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003568867_ctypes_python.txt |
Q:
How to I determine the default value for a given function parameter at runtime?
Using python 2.4, I'm attempting to identify, at runtime, which of an arbitrary function's arguments have default values. Unfortunately, although I can find what the default values are, I can't seem to get a handle on which parameters ... | How to I determine the default value for a given function parameter at runtime? | Using python 2.4, I'm attempting to identify, at runtime, which of an arbitrary function's arguments have default values. Unfortunately, although I can find what the default values are, I can't seem to get a handle on which parameters they correspond to. For example:
def foo(a, b, c=5):
return a + b + c
import ins... | [
"Arguments with default values must follow arguments without default values.\nSo if there are any defaults, they must correspond to the arguments at the tail end of args.\nIn your case, args=['a','b','c'], and defaults=(5,). So the default must correspond to c.\nimport inspect\n\ndef foo(a, b, c=5):\n return a +... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0003568844_python.txt |
Q:
Calculating e (base of the natural log) to high precision in Python?
Is it possible to calculate the value of the mathematical constant, e with high precision (2000+ decimal places) using Python?
I am particularly interested in a solution either in or that integrates with NumPy or SciPy.
A:
You can set the preci... | Calculating e (base of the natural log) to high precision in Python? | Is it possible to calculate the value of the mathematical constant, e with high precision (2000+ decimal places) using Python?
I am particularly interested in a solution either in or that integrates with NumPy or SciPy.
| [
"You can set the precision you want with the decimal built-in module:\nfrom decimal import *\ngetcontext().prec = 40\nDecimal(1).exp()\n\nThis returns:\nDecimal('2.718281828459045235360287471352662497757')\n\n",
"This can also be done with sympy using numerical evaluation:\nimport sympy\n\nprint sympy.N(sympy.E, ... | [
22,
9,
7,
5,
3,
1
] | [] | [] | [
"floating_point",
"math",
"numpy",
"python",
"scipy"
] | stackoverflow_0003559548_floating_point_math_numpy_python_scipy.txt |
Q:
A better way to do this?
I am writing a python function with the following:
class myObj(object):
def __init__(self, args):
# there is code here
def newO(self, name, description):
if type(name)==str:
self.oname.append(name)
self.o.append(description)
elif type... | A better way to do this? | I am writing a python function with the following:
class myObj(object):
def __init__(self, args):
# there is code here
def newO(self, name, description):
if type(name)==str:
self.oname.append(name)
self.o.append(description)
elif type(name)==list:
for... | [
"\nNever check type(x) == foo, use isinstance(x, foo) — the former will break if there is a subclass, for instance.\nYou appear to be maintaining parallel lists. If the order matters, it might make more sense to use a list of tuples instead, so self.values.append((name, description)). If the order does not matter, ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003569093_python.txt |
Q:
Problem with Django/Dajaxice and international characters
I am having a problem using Djajaxice with international characters...
I have a django template...in that template is the following select:
<select name="region" id="id" onchange="Dajaxice.crc.regions('my_callback',{'data':this.value});">
<option ... | Problem with Django/Dajaxice and international characters | I am having a problem using Djajaxice with international characters...
I have a django template...in that template is the following select:
<select name="region" id="id" onchange="Dajaxice.crc.regions('my_callback',{'data':this.value});">
<option value="" selected="selected" ></option>
{% for region ... | [
"Ok, fixed this...\nSo for anyone else using Dajaxice, and using international characters you should change line 10 in the Dajaxice.core.js file from the following:\nsend_data.push('argv='+escape(JSON.stringify(argv)));\nto this:\nsend_data.push('argv='+encodeURIComponent(JSON.stringify(argv)));\nand all works well... | [
1
] | [] | [] | [
"django",
"python",
"unicode",
"unicode_string"
] | stackoverflow_0003567388_django_python_unicode_unicode_string.txt |
Q:
Querying for not None
I have a model with a reference property, eg:
class Data(db.Model):
x = db.IntegerProperty()
class Details(db.Model):
data = db.ReferenceProperty(reference_class = Data)
The data reference can be None.
I want to fetch all Details entities which have valid data, ie for which the refe... | Querying for not None | I have a model with a reference property, eg:
class Data(db.Model):
x = db.IntegerProperty()
class Details(db.Model):
data = db.ReferenceProperty(reference_class = Data)
The data reference can be None.
I want to fetch all Details entities which have valid data, ie for which the reference property is not None.... | [
"I would advise you to use the extra model field. This is more flexible, since it also allows you to query for Details that have no Data references. In addition, queries can only have one inequality filter, so you're better off saving this inequality filter for another property where inequality makes more sense, su... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003568553_google_app_engine_python.txt |
Q:
Parsing HTML with Lxml
I need help parsing out some text from a page with lxml. I tried beautifulsoup and the html of the page I am parsing is so broken, it wouldn't work. So I have moved on to lxml, but the docs are a little confusing and I was hoping someone here could help me.
Here is the page I am trying t... | Parsing HTML with Lxml | I need help parsing out some text from a page with lxml. I tried beautifulsoup and the html of the page I am parsing is so broken, it wouldn't work. So I have moved on to lxml, but the docs are a little confusing and I was hoping someone here could help me.
Here is the page I am trying to parse, I need to get the t... | [
"import lxml.html as lh\nimport urllib2\n\ndef text_tail(node):\n yield node.text\n yield node.tail\n\nurl='http://bit.ly/bf1T12'\ndoc=lh.parse(urllib2.urlopen(url))\nfor elt in doc.iter('td'):\n text=elt.text_content()\n if text.startswith('Additional Info'):\n blurb=[text for node in elt.iters... | [
16
] | [] | [] | [
"html",
"lxml",
"parsing",
"python"
] | stackoverflow_0003569152_html_lxml_parsing_python.txt |
Q:
Indentation Error python
I'm using twisted API and was going through this example.
I inserted one print statement print "in getdummydata" with correct indentation. code is as below:
from twisted.internet import reactor, defer
def getDummyData(x):
"""
This function is a dummy which simulates a delayed resu... | Indentation Error python | I'm using twisted API and was going through this example.
I inserted one print statement print "in getdummydata" with correct indentation. code is as below:
from twisted.internet import reactor, defer
def getDummyData(x):
"""
This function is a dummy which simulates a delayed result and
returns a Deferred ... | [
"It looks like the \"def\" for all your functions have one blank space in front of them. By my eye, \"def\" falls under the \"r\" in the \"from\" above rather than the \"f\".\nPerhaps if you remove those spaces the problem will go away. Whitespace is important to Python.\n",
"Check that you aren't mixing spaces... | [
1,
0,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003569490_python_twisted.txt |
Q:
Command Line Arguments in Imported Python Modules
This is more a question of coding style, but I have a script that processes a particular file (or set of files). It would be nice to allow the user to provide those files as command-line arguments. Of course, it's possible that the user forgets to provide these or ... | Command Line Arguments in Imported Python Modules | This is more a question of coding style, but I have a script that processes a particular file (or set of files). It would be nice to allow the user to provide those files as command-line arguments. Of course, it's possible that the user forgets to provide these or the filenames are invalid, so I have to introduce a try... | [
"The usual procedure:\nimport sys\n\ndef main(*files):\n # your program's logic goes here\n\nif __name__ == \"__main__\": #i.e. run directly\n try:\n main(*sys.argv[1:])\n except IOError:\n handle_error()\n\nIf imported, __name__ will be != \"__main__\", thus nothing actually happens and the ... | [
5,
2
] | [] | [] | [
"command_line",
"python"
] | stackoverflow_0003569523_command_line_python.txt |
Q:
how to replicate parts of code in python into C to execution faster?
i have prepared a project in python language ie a TEXT TO SPEECH synthesizer. Which took a total on 1500 lines of code.
But there few parts of code due to which it is taking so much time to run the code, i want to replace that parts of code in C/... | how to replicate parts of code in python into C to execution faster? | i have prepared a project in python language ie a TEXT TO SPEECH synthesizer. Which took a total on 1500 lines of code.
But there few parts of code due to which it is taking so much time to run the code, i want to replace that parts of code in C/c++ lang so that it runs faster.
So i want to know how can i run these par... | [
"You could write them in Cython, it's pretty easy.\nAlternatively, you can try using numpy, which is already written in C and may have most of the operations you need.\n",
"You have a few options:\nAs Radomir mentioned, Cython might be a good choice: it's essentially a restricted Python with type declarations, au... | [
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003568371_python.txt |
Q:
FTP Detect if active or passive modes are enabled
Specifically for Twisted, I would like to be able to determine whether the server I am connected to supports active or passive mode. See API.
If somebody could explain or give example in FTP protocol how you can determine whether the server supports active or passi... | FTP Detect if active or passive modes are enabled | Specifically for Twisted, I would like to be able to determine whether the server I am connected to supports active or passive mode. See API.
If somebody could explain or give example in FTP protocol how you can determine whether the server supports active or passive modes.
| [
"Passive mode is enabled by issuing the PASV command to the server. If it responds with an error code (should be 500 Unknown command) upon issuing that command, then you know that it is not supported. If it responds with a 227 Entering Passive Mode, then you know that passive is supported.\nExample using command l... | [
5
] | [] | [] | [
"ftp",
"python",
"twisted"
] | stackoverflow_0003569604_ftp_python_twisted.txt |
Q:
Overloading List Comprehension Behavior?
I'm tasked with creating a model of a cage of hardware. Each cage contains N slots, each slot may or may not contain a card.
I would like to model the cage using a list. Each list index would correspond to the slot number. cards[0].name="Card 0", etc.
This would allow my ... | Overloading List Comprehension Behavior? | I'm tasked with creating a model of a cage of hardware. Each cage contains N slots, each slot may or may not contain a card.
I would like to model the cage using a list. Each list index would correspond to the slot number. cards[0].name="Card 0", etc.
This would allow my users to query the model via simple list compr... | [
">>> class MyList(list):\n... def __iter__(self):\n... return (x for x in list.__iter__(self) if x is not None)\n... \n>>> \n>>> ml = MyList([\"cat\", \"dog\", None, \"fox\"])\n>>> for item in ml:\n... print item\n... \ncat\ndog\nfox\n\n>>> [x for x in ml]\n['cat', 'dog', 'fox']\n>>> list(ml)\n['cat... | [
8,
2,
1,
0
] | [] | [] | [
"list",
"list_comprehension",
"overloading",
"python"
] | stackoverflow_0003569945_list_list_comprehension_overloading_python.txt |
Q:
Crash in development server clears datastore?
I'm testing my app with the development server.
When I manually interrupt a request, it sometimes clears the datastore.
This clears even models that are not modified by my request, like users, etc.
Any idea why is this?
Thanks
A:
I would recommend using the SQLite st... | Crash in development server clears datastore? | I'm testing my app with the development server.
When I manually interrupt a request, it sometimes clears the datastore.
This clears even models that are not modified by my request, like users, etc.
Any idea why is this?
Thanks
| [
"I would recommend using the SQLite stub, instead of the default file-based stub, in your SDK; read all about it in this blog entry by Nick Johnson, who made it. Just pass flag --use_sqlite=true to dev_appserver.py to gain all of SQLite goodness (including, at least in design intent, no datastore wiping on crashes... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003570111_google_app_engine_python.txt |
Q:
How do I set the transaction isolation level in SQLAlchemy for PostgreSQL?
We're using SQLAlchemy declarative base and I have a method that I want isolate the transaction level for. To explain, there are two processes concurrently writing to the database and I must have them execute their logic in a transaction. T... | How do I set the transaction isolation level in SQLAlchemy for PostgreSQL? | We're using SQLAlchemy declarative base and I have a method that I want isolate the transaction level for. To explain, there are two processes concurrently writing to the database and I must have them execute their logic in a transaction. The default transaction isolation level is READ COMMITTED, but I need to be able ... | [
"From Michael Bayer, the maintainer of SQLAlchemy:\n\nPlease use the \"isolation_level\"\n argument to create_engine()\n and use the latest tip of SQLAlchemy\n until 0.6.4 is released, as there was\n a psycopg2-specific bug fixed recently\n regarding isolation level. \nThe approach you have below does not\n... | [
15
] | [
"The isolation level is set within a transaction, e.g.\ntry:\n Session.begin()\n Session.execute('set transaction isolation level serializable')\n self.find_or_create(kwarg1=value1)\nexcept:\n ...\n\nFrom PostgreSQL doc:\n\nIf SET TRANSACTION is executed without a prior START TRANSACTION or BEGIN, it wi... | [
-4
] | [
"isolation_level",
"postgresql",
"python",
"sqlalchemy",
"transactions"
] | stackoverflow_0003518863_isolation_level_postgresql_python_sqlalchemy_transactions.txt |
Q:
Updating a For Each Loop in Python
The below python code takes a list of files and zips them up. The only File Geodatabase (File based database) that I need to have is called "Data" so how can I modify the loop to only include the File based database called Data? To be more specific a File Geodatabase is stored ... | Updating a For Each Loop in Python | The below python code takes a list of files and zips them up. The only File Geodatabase (File based database) that I need to have is called "Data" so how can I modify the loop to only include the File based database called Data? To be more specific a File Geodatabase is stored as a system folder that contains binary ... | [
"The best way to walk over a directory tree is os.walk -- does the file/dir separation for you, and also does the recursion down to subdirectories for you.\nSo:\ndef zipws(path, zip, filename='Data.gdb'):\n for root, dirs, files in os.walk(path):\n if filename in files:\n zip.write(os.path.join(root, filen... | [
1,
0
] | [] | [] | [
"arcgis",
"gis",
"python"
] | stackoverflow_0003569516_arcgis_gis_python.txt |
Q:
Eclipse PyDev bug when trying to comment out 300+ lines with """docstring"""
I don't know if you guys are having the same problem, but when I'm trying to use """ and """ for multi-lines comments in eclipse pydev, it sometimes does not work. Anybody can suggest me some better IDE?
Sorry. I will try to make this cle... | Eclipse PyDev bug when trying to comment out 300+ lines with """docstring""" | I don't know if you guys are having the same problem, but when I'm trying to use """ and """ for multi-lines comments in eclipse pydev, it sometimes does not work. Anybody can suggest me some better IDE?
Sorry. I will try to make this clearer. It happens every time when I try to comment off looong multi lines like 300 ... | [
"I prefer pyDev plugin with Eclipse. \nBut if you feel its problem checkout following:\n\nNetBeans python ide check\nfeatures from their wiki page\nPyCharm from JetBrains\n\n",
"I have this problem as well. It has been around for so long, I have become used to it. It tends to happen to me most when I am writing e... | [
1,
0
] | [] | [] | [
"eclipse",
"eclipse_plugin",
"multiline",
"python",
"wxpython"
] | stackoverflow_0003512788_eclipse_eclipse_plugin_multiline_python_wxpython.txt |
Q:
In wxPython how do you bind a EVT_KEY_DOWN event to the whole window?
I can bind an event to a textctrl box np. The problem is I have to be clicked inside of the textctrl box to "catch" this event. I am hoping to be able to catch anytime someone presses the Arrow keys while the main window has focus.
NOT WORKI... | In wxPython how do you bind a EVT_KEY_DOWN event to the whole window? | I can bind an event to a textctrl box np. The problem is I have to be clicked inside of the textctrl box to "catch" this event. I am hoping to be able to catch anytime someone presses the Arrow keys while the main window has focus.
NOT WORKING:
wx.EVT_KEY_DOWN(self, self.OnKeyDown)
WORKING:
self.NudgeTxt = wx.Tex... | [
"Instead try binding to wx.EVT_CHAR_HOOK\ne.g..\nself.Bind(wx.EVT_CHAR_HOOK, self.onKey)\n\n ...\n\ndef onKey(self, evt):\n if evt.GetKeyCode() == wx.WXK_DOWN:\n print \"Down key pressed\"\n else:\n evt.Skip()\n\n",
"You could use EVT_CHAR_HOOK,\n self.Bind(wx.EVT_CHAR_HOOK, self.hotkey)\n... | [
21,
4
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003570254_python_user_interface_wxpython.txt |
Q:
Python definitions relying on other undefined definitions?
I didn't know what to title this, so if anyone wants to edit it: Go ahead.
def Function_A()
print "We're going to function B!"
Function_B()
def Function_B()
print "We made it!'
This is a beginner question, but the solution hasn't occurred to me as I'v... | Python definitions relying on other undefined definitions? | I didn't know what to title this, so if anyone wants to edit it: Go ahead.
def Function_A()
print "We're going to function B!"
Function_B()
def Function_B()
print "We made it!'
This is a beginner question, but the solution hasn't occurred to me as I've been spoiled by compiled languages. You can see here, Function... | [
"In Python, functions do not need to be defined in order of use. As long as it's defined somewhere before the function is called at runtime it should work. This is because Function_A() is not actually evaluated until it's called, which in this is case is at the bottom of the this test.py file at which point Functio... | [
5,
2,
2,
2,
1
] | [] | [] | [
"definition",
"function",
"python"
] | stackoverflow_0003570532_definition_function_python.txt |
Q:
Something quite tricky in a python exercise
I wrote a python script test1.py in which I import a module called test2, then in test2, I did import test1; when I run test1, it works correctly; to my very big suprise, when I try to run test2, it outputs exactlly the same result as I run test1, despite these two files... | Something quite tricky in a python exercise | I wrote a python script test1.py in which I import a module called test2, then in test2, I did import test1; when I run test1, it works correctly; to my very big suprise, when I try to run test2, it outputs exactlly the same result as I run test1, despite these two files have very very different contents. but when I re... | [
"This is why.\n"
] | [
2
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003570726_import_module_python.txt |
Q:
Rotate an image about a specific pixel in python
How can I rotate an image about a specific pixel in Python? I am trying to de-rotate a set of images of the night sky. Since the stars rotate around Polaris, I could define Polaris as the center of rotation and rotate each image to line up the stars.
A:
In phadej'... | Rotate an image about a specific pixel in python | How can I rotate an image about a specific pixel in Python? I am trying to de-rotate a set of images of the night sky. Since the stars rotate around Polaris, I could define Polaris as the center of rotation and rotate each image to line up the stars.
| [
"In phadej's answer the transformation between the old and new coordinates of a point on the image is an affine transformation.\nPIL (Python Imaging Library) has an image method called transform which can perform an affine transformation of an image.\nThe documentation for transform is near the bottom of this page.... | [
2,
0
] | [] | [] | [
"astronomy",
"image",
"image_rotation",
"python"
] | stackoverflow_0003570782_astronomy_image_image_rotation_python.txt |
Q:
Need some help with PyQt and QGridLayout
I'm having an annoyingly stubborn problem here, and I would appreciate it if anyone could give me some insight into what I'm doing wrong.
I have a PyQt app that is supposed to display a table of numbers. So, naturally, I am using QTableWidget. Right now, it's extremely simp... | Need some help with PyQt and QGridLayout | I'm having an annoyingly stubborn problem here, and I would appreciate it if anyone could give me some insight into what I'm doing wrong.
I have a PyQt app that is supposed to display a table of numbers. So, naturally, I am using QTableWidget. Right now, it's extremely simple: all I do is create a window with a Table W... | [
"What you have works perfectly, so it must be in your setup. The following should work for you:\nfrom PyQt4 import QtCore, QtGui\nfrom Ui_TableWindow import Ui_TableWindow # adjust accordingly\n\nclass TableWindow(QtGui.QWidget, Ui_TableWindow):\n def __init__(self, parent):\n QtGui.QWidget.__init__(self... | [
1,
1
] | [] | [] | [
"designer",
"pyqt",
"python",
"qt_designer"
] | stackoverflow_0002676369_designer_pyqt_python_qt_designer.txt |
Q:
show linux process [Python]
Guy how i can read all process work in my computer and print it
i want process read then print ?
A:
one of the possible ways is to parse the output of some specialized system process "viewer" application
like:
import commands
cmd = 'ps ax'
for line in commands.getoutput(cmd).splitline... | show linux process [Python] | Guy how i can read all process work in my computer and print it
i want process read then print ?
| [
"one of the possible ways is to parse the output of some specialized system process \"viewer\" application\nlike:\nimport commands\ncmd = 'ps ax'\nfor line in commands.getoutput(cmd).splitlines():\n # process the line\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003571194_python.txt |
Q:
UnicodeDecodeError when passing GET data in Python/AppEngine
This feels like a really basic question, but I haven't been able to find an answer.
I would like to read data from an url, for example GET data from a querystring. I am using the webapp framework in Python. I tried the following code, but since I've a to... | UnicodeDecodeError when passing GET data in Python/AppEngine | This feels like a really basic question, but I haven't been able to find an answer.
I would like to read data from an url, for example GET data from a querystring. I am using the webapp framework in Python. I tried the following code, but since I've a total beginner at Python/appengine, I've certainly done something wr... | [
"You try to e.g. print an ASCII coded string actually containing data of a different charset. This can happen e.g. with Latin-1 encoded data. Try converting your input to unicode using\nunicoded = unicode(non_unicode_string, source_encoding)\n\nwhere source_encoding is something like 'cp1252', 'iso-8859-1' etc., an... | [
2,
2
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0003570434_google_app_engine_python_web_applications.txt |
Q:
Customizing matplotlib image display to add copy/paste
I would like to customize matplotlib image display so that i can type control-c and it will copy the image to the clipboard so then i can copy it to openoffice spreadsheet to organize all of my raw data and image results. Is there any way to do this? Thanks!
... | Customizing matplotlib image display to add copy/paste | I would like to customize matplotlib image display so that i can type control-c and it will copy the image to the clipboard so then i can copy it to openoffice spreadsheet to organize all of my raw data and image results. Is there any way to do this? Thanks!
| [
"If you're using the wx backend, FigureCanvasWxAgg has a Copy_to_Clipboard method you can use. You could bind the CTRL+C key event to call this method. For an example, see this sample code.\n",
"import matplotlib\nimport matplotlib.pyplot as plt\nif not globals().has_key('__figure'):\n __figure = matplotlib... | [
5,
2
] | [] | [] | [
"copy",
"excel",
"matplotlib",
"paste",
"python"
] | stackoverflow_0003571117_copy_excel_matplotlib_paste_python.txt |
Q:
Psycopg2 under osx works on commandline but fails in Aptana studio
I have been developing under Python/Snowleopard happily for the part 6 months. I just upgraded Python to 2.6.5 and a whole bunch of libraries, including psycopg2 and Turbogears. I can start up tg-admin and run some queries with no problems. Similar... | Psycopg2 under osx works on commandline but fails in Aptana studio | I have been developing under Python/Snowleopard happily for the part 6 months. I just upgraded Python to 2.6.5 and a whole bunch of libraries, including psycopg2 and Turbogears. I can start up tg-admin and run some queries with no problems. Similarly, I can run my web site from the command line with no problems.
Howev... | [
"Problem solved (to a point). I was running 64 bit python from Aptana Studio and 32 bit python on the command line. By forcing Aptana to use 32 bit python, the libraries work again and all is happy.\n"
] | [
0
] | [] | [] | [
"psycopg",
"python",
"turbogears"
] | stackoverflow_0003571495_psycopg_python_turbogears.txt |
Q:
Django and dynamically generated images
I have a view in my Django application that automatically creates an image using the PIL, stores it in the Nginx media server, and returns a html template with a img tag pointing to it's url.
This works fine, but I notice an issue. For every 5 times I access this view, in 1 ... | Django and dynamically generated images | I have a view in my Django application that automatically creates an image using the PIL, stores it in the Nginx media server, and returns a html template with a img tag pointing to it's url.
This works fine, but I notice an issue. For every 5 times I access this view, in 1 of them the image doesn't render.
I did some ... | [
"We had this problem a while back when writing HTML pages out to disk. The solution for us was to write to a temporary file and then atomically rename the file. You might also want to consider using fsync.\nThe full source is available here: staticgenerator/__init__.py, but here are the useful bits:\nimport os\nimp... | [
5
] | [] | [] | [
"django",
"http_headers",
"nginx",
"python",
"python_imaging_library"
] | stackoverflow_0003514569_django_http_headers_nginx_python_python_imaging_library.txt |
Q:
Getting Django to work with Eclipse
I'm new to python and django but wanted to start following some tutorials. I installed python, then django, and then the pydev plugin for eclipse. I created a new django project and tried running it. In eclipse I set up a run configuration for manage.py with argument runserve... | Getting Django to work with Eclipse | I'm new to python and django but wanted to start following some tutorials. I installed python, then django, and then the pydev plugin for eclipse. I created a new django project and tried running it. In eclipse I set up a run configuration for manage.py with argument runserver and it said "Validating Models" but nev... | [
"I'm just starting myself. Apparently there's a MySQLdb plugin (sorry if that's not the right term) that you need to use in addition to a standard MySQL install. This is so Python can communicate with MySQL.\n",
"It sounds like that you need to include the module in Eclipse System PYTHONPATH.\nGo to Windows -> ... | [
1,
1,
0
] | [] | [] | [
"django",
"eclipse",
"pydev",
"python"
] | stackoverflow_0003398631_django_eclipse_pydev_python.txt |
Q:
Does Windows 7 Automatically Use Multiple Processors for Python 3 Code?
I have windows 7 and I wrote a python program that loops ("for loops", i.e., "for key in dict") over multiple databases, checks for various conditions (e.g., if x in dict, y += 1) and then tallies the results. I didn't do anything to parralel... | Does Windows 7 Automatically Use Multiple Processors for Python 3 Code? | I have windows 7 and I wrote a python program that loops ("for loops", i.e., "for key in dict") over multiple databases, checks for various conditions (e.g., if x in dict, y += 1) and then tallies the results. I didn't do anything to parralelize the proceesing. I have 8 CPU cores on my computer. When I start Windows... | [
"No. The C implementation of Python only allows one thread to interpret one bytecode at a time. The only way to take advantage of multiple cores is with multiple threads or multiple processes. \nIt is completely possible that you will see multiple core activity related to your script however. Let's say you open sev... | [
4,
2
] | [] | [] | [
"parallel_processing",
"python",
"windows_7"
] | stackoverflow_0003571906_parallel_processing_python_windows_7.txt |
Q:
Python code flow does not work as expected?
I am trying to process various texts by regex and NLTK of python -which is at http://www.nltk.org/book-. I am trying to create a random text generator and I am having a slight problem. Firstly, here is my code flow:
Enter a sentence as input -this is called trigger stri... | Python code flow does not work as expected? | I am trying to process various texts by regex and NLTK of python -which is at http://www.nltk.org/book-. I am trying to create a random text generator and I am having a slight problem. Firstly, here is my code flow:
Enter a sentence as input -this is called trigger string, is assigned to a variable-
Get longest word i... | [
"How about this?\n\nYou find longest word in trigger\nYou find longest word in the longest sentence containing word found in 1.\nThe word of 1. is the longest word of the sentence of 2.\n\nWhat happens? Hint: answer starts with \"Infinite\". To correct the problem you could find set of words in lower case to be use... | [
1,
1,
0,
0
] | [] | [] | [
"nltk",
"parsing",
"python",
"text"
] | stackoverflow_0003571887_nltk_parsing_python_text.txt |
Q:
Django can't find my non-python files!
I can't, for the life of me, get Django to find my JavaScript files! I am trying to plug in a custom widget to the admin page, like so:
class MarkItUpWidget(forms.Textarea):
class Media:
js = (
'js/jquery.js',
'js/markitup/jquery.markitup.js',
'js/... | Django can't find my non-python files! | I can't, for the life of me, get Django to find my JavaScript files! I am trying to plug in a custom widget to the admin page, like so:
class MarkItUpWidget(forms.Textarea):
class Media:
js = (
'js/jquery.js',
'js/markitup/jquery.markitup.js',
'js/markitup/sets/markdown/set.js',
'js/... | [
"I guess you're using django-admin runserver to test your website. In that case, have a look at \"How to serve static files\" (but don't ignore the big fat disclaimer).\nOnce you're ready to deploy, this chapter contains all the information (provided you go the standard route of Apache/mod_wsgi)\n",
"I don't know... | [
3,
0
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0003572032_django_django_admin_django_forms_python.txt |
Q:
An optional dict in the structure with MongoKit
I've got MongoKit structure like this:
structure = {
...
'plugin': {
'id': unicode,
'title': unicode,
'description': unicode,
...
}
However, not all documents will have the plugin key. If they do, I'd like it to be validated against the structure... | An optional dict in the structure with MongoKit | I've got MongoKit structure like this:
structure = {
...
'plugin': {
'id': unicode,
'title': unicode,
'description': unicode,
...
}
However, not all documents will have the plugin key. If they do, I'd like it to be validated against the structure.
required_fields does not include plugin. (plugin is... | [
"Looks like a bug in 0.5:\n\nhttp://bitbucket.org/namlook/mongokit/issue/78/not-required-fields-wrongly-validates#comment-234872\n\nDiscussion and temporary workaround here:\n\nhttp://groups.google.com/group/mongokit/browse_thread/thread/18fe4081a306e93e\n\n"
] | [
0
] | [] | [] | [
"mongodb",
"mongokit",
"python"
] | stackoverflow_0003429527_mongodb_mongokit_python.txt |
Q:
Static method vs module function in python
So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead ... | Static method vs module function in python | So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the... | [
"Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a from module import *.\nAnother technique is to specify an __all__ list in the module - this can just be done in the module itself (you don't need an __init__.... | [
8,
3,
3
] | [] | [] | [
"global",
"python",
"static_methods"
] | stackoverflow_0003570823_global_python_static_methods.txt |
Q:
Python: Why should 'from import *' be prohibited?
If you happen to have
from <module> import *
in the middle of your program (or module), you would get the warning:
/tmp/foo:100: SyntaxWarning: import * only allowed at module level
I understand why import * is discouraged in general (namespace invisibility),
bu... | Python: Why should 'from import *' be prohibited? | If you happen to have
from <module> import *
in the middle of your program (or module), you would get the warning:
/tmp/foo:100: SyntaxWarning: import * only allowed at module level
I understand why import * is discouraged in general (namespace invisibility),
but there are many situations where it would prove conveni... | [
"I believe by \"in the middle of your program\" you are talking about an import inside a function definition:\ndef f():\n from module import * # not allowed\n\nThis is not allowed because it would make optimizing the body of the function too hard. The Python implementation wants to know all of the names of f... | [
30,
17,
14,
4,
1,
0
] | [] | [] | [
"module",
"namespaces",
"python",
"python_import"
] | stackoverflow_0003571514_module_namespaces_python_python_import.txt |
Q:
Why doesn't this Boost ASIO code work with this python client?
This code is identical to the original udp async echo server, but with a different socket.
The response is transmitted and showing in wireshark, but then an ICMP Port Unreachable error is sent back to the server. I'm trying to understand why because e... | Why doesn't this Boost ASIO code work with this python client? | This code is identical to the original udp async echo server, but with a different socket.
The response is transmitted and showing in wireshark, but then an ICMP Port Unreachable error is sent back to the server. I'm trying to understand why because everything looks correct.
You can copy this code directly into a sour... | [
"You shouldn't pend an asynchronous send and then close the socket. The destructor for socket runs at the end of the block, closing the socket, which prevents the send from ever occurring.\n",
"Ok, a completely different possibility.\nAre you running netfilter? Do you have a conntrack rule?\nA reply from the sa... | [
3,
0,
0
] | [
"Edit\nYour python client code looks suspicious, I don't think you should be doing a connect or a send using a UDP socket. Try this:\n#!/usr/bin/python\n\nimport socket, sys, time, struct\n\nport = 10000\nhost = \"localhost\"\naddr = (host,port)\n\nif len(sys.argv) > 1:\n host = sys.argv[1]\n\nprint \"Sending D... | [
-1
] | [
"boost_asio",
"c++",
"python"
] | stackoverflow_0003571156_boost_asio_c++_python.txt |
Q:
Python: How to be notified when the subprocess is ended opened by Popen
I am using Popen to run a command but I don't know how I can write a callback that gets called once the command is finished. Any idea?
Thanks.
Bin
A:
You can call communicate():
p = subprocess.Popen('find . -name "*.txt"', stdout=subprocess... | Python: How to be notified when the subprocess is ended opened by Popen | I am using Popen to run a command but I don't know how I can write a callback that gets called once the command is finished. Any idea?
Thanks.
Bin
| [
"You can call communicate():\n p = subprocess.Popen('find . -name \"*.txt\"', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n\nYou can also call wait(), but this might cause problems if the child process fills its output buffer.\n",
"You could use p.poll() method of the Popen ... | [
2,
2
] | [] | [] | [
"popen",
"python"
] | stackoverflow_0003571784_popen_python.txt |
Q:
Pasting image to clipboard in python in linux
Ive tried the gtk method, but it is very slow and doesn't work for a 'large' image (120 kb)
import pygtk
pygtk.require('2.0')
import gtk
import os
def copy_image(f):
assert os.path.exists(f), "file does not exist"
clipboard = gtk.clipboard_get()
img = gtk.I... | Pasting image to clipboard in python in linux | Ive tried the gtk method, but it is very slow and doesn't work for a 'large' image (120 kb)
import pygtk
pygtk.require('2.0')
import gtk
import os
def copy_image(f):
assert os.path.exists(f), "file does not exist"
clipboard = gtk.clipboard_get()
img = gtk.Image()
img.set_from_file(f)
clipboard.set_i... | [
"One way of getting text from/to the clipboard is using XSel. It's not pretty and requires you to communicate with an external program. But it works and is quite fast.\nNot sure if it's the best solution but I know it works :)\n[edit]You're right, it seems that xsel does not support images.\nIn that case, how about... | [
3,
1
] | [] | [] | [
"copy",
"image",
"python"
] | stackoverflow_0003571855_copy_image_python.txt |
Q:
Is there any way to get ps output programmatically?
I've got a webserver that I'm presently benchmarking for CPU usage. What I'm doing is essentially running one process to slam the server with requests, then running the following bash script to determine the CPU usage:
#! /bin/bash
for (( ;; ))
do
echo "`p... | Is there any way to get ps output programmatically? | I've got a webserver that I'm presently benchmarking for CPU usage. What I'm doing is essentially running one process to slam the server with requests, then running the following bash script to determine the CPU usage:
#! /bin/bash
for (( ;; ))
do
echo "`python -c 'import time; print time.time()'`, `ps -p $1 -o ... | [
"You could check out this question about parsing ps output using Python.\nOne of the answers suggests using the PSI python module. It's an extension though, so I don't really know how suitable that is for you.\nIt also shows in the question how you can call a ps subprocess using python :)\n",
"My preference is to... | [
3,
3,
1,
1
] | [] | [] | [
"linux",
"macos",
"ps",
"python",
"unix"
] | stackoverflow_0003559157_linux_macos_ps_python_unix.txt |
Q:
Finding out how many lines can be displayed in wx.richtext.RichTextCtrl without scrolling
I'm writing an e-book reader in Python + wxPython, and I'd like to find out how many lines of text can be displayed in a given RichTextCtrl with the current formatting without scrolling.
I thought of using and dividing the c... | Finding out how many lines can be displayed in wx.richtext.RichTextCtrl without scrolling | I'm writing an e-book reader in Python + wxPython, and I'd like to find out how many lines of text can be displayed in a given RichTextCtrl with the current formatting without scrolling.
I thought of using and dividing the control's height by RichTextCtrl.GetFont().GetPixelSize(), but it appears that the pixel size pa... | [
"Source code of PageDown method suggest that there is not a sane way to do this...\nHere is my insane proposition (which breaks widget content, caret, displayed position...) which scroll one page and measure how long this scroll is...\ndef GetLineHeight(rtc):\n tallString = \"\\n\".join([str(i) for i in xrange(2... | [
2,
0
] | [] | [] | [
"python",
"resolution_independence",
"wxpython"
] | stackoverflow_0003504383_python_resolution_independence_wxpython.txt |
Q:
Debug a python script used with nmake
I have a Visual Studio project which uses nmake to call a Python file for clean, build, or rebuild. For ex. in VS project properties->Configuration Properties->NMake, for the Build Command Line I would have
....\blah\tools\myBuildFile.py build -arg1 -arg2
There are several py... | Debug a python script used with nmake | I have a Visual Studio project which uses nmake to call a Python file for clean, build, or rebuild. For ex. in VS project properties->Configuration Properties->NMake, for the Build Command Line I would have
....\blah\tools\myBuildFile.py build -arg1 -arg2
There are several python files used with lots of variables and ... | [
"\nInstall winpdb\nChange your command to: ...\\blah\\winpdb.py ...\\blah\\tools\\myBuildFile.py build -arg1 -arg2\n\n"
] | [
0
] | [] | [] | [
"makefile",
"python",
"visual_studio"
] | stackoverflow_0003574911_makefile_python_visual_studio.txt |
Q:
Function Names for sending and receiving RPCs?
I'm using twisted. I have my protocols set up so that, to send an RPC, I do protocol.send("update_status", data). To document which RPCs I've implemented, I make a separate function call for each one, so in this case I'd call REQUEST_UPDATE_STATUS(data) to send that R... | Function Names for sending and receiving RPCs? | I'm using twisted. I have my protocols set up so that, to send an RPC, I do protocol.send("update_status", data). To document which RPCs I've implemented, I make a separate function call for each one, so in this case I'd call REQUEST_UPDATE_STATUS(data) to send that RPC. When a protocol receives an RPC, a function gets... | [
"First tip: Use PB... it's well designed and does exactly that\nSecond Tip: If the first tip isn't going to work for you, just do what PB does. On the client end a \"callRemote(\"foo_func\")\" asks the server ot invoke the \"foo_func\" function on the server object. The server will then use \"getattr(server_obj, \"... | [
1
] | [] | [] | [
"naming_conventions",
"python",
"rpc",
"twisted"
] | stackoverflow_0003575119_naming_conventions_python_rpc_twisted.txt |
Q:
python+twisted+gtk: KeyboardInterrupt causes free variable?
I'm using twisted with GTK, and the following code runs when a connection could not be established:
def connectionFailed(self, reason):
#show a "connect failed" dialog
dlg = gtk.MessageDialog(
type=gtk.MESSAGE_ERROR,
buttons=gtk.BU... | python+twisted+gtk: KeyboardInterrupt causes free variable? | I'm using twisted with GTK, and the following code runs when a connection could not be established:
def connectionFailed(self, reason):
#show a "connect failed" dialog
dlg = gtk.MessageDialog(
type=gtk.MESSAGE_ERROR,
buttons=gtk.BUTTONS_CLOSE,
message_format="Could not connect to server:... | [
"Shouldn't that be:\ndef response(dialog, rid):\n dialog.hide_all()\n responseDF.callback(rid)\n\nor really, for clarity,\ndef response(self, rid):\n self.hide_all()\n responseDF.callback(rid)\n\n(I might be wrong about this, I've done barely any GTK.) If so, the problem is that you are referencing dlg ... | [
1
] | [] | [] | [
"gtk",
"python",
"scope",
"twisted",
"variables"
] | stackoverflow_0003575200_gtk_python_scope_twisted_variables.txt |
Q:
Parse html with ajax json inside
I have such files to parse (from scrapping) with Python:
some HTML and JS here...
SomeValue =
{
'calendar': [
{ 's0Date': new Date(2010, 9, 12),
'values': [
{ 's1Date': new Date(2010, 9, 17), 'price': 9900 },
{... | Parse html with ajax json inside | I have such files to parse (from scrapping) with Python:
some HTML and JS here...
SomeValue =
{
'calendar': [
{ 's0Date': new Date(2010, 9, 12),
'values': [
{ 's1Date': new Date(2010, 9, 17), 'price': 9900 },
{ 's1Date': new Date(2010, 9, 18), 'pri... | [
"aarrghhh no regex dont use regex no regex no no nooooooo\n\nUse the json module to handle JSON data:\nimport json\njson.loads( <string> )\n\nUse BeautifulSoup or lxml to handle parsing the html page:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup( <string> )\n\nIf you want specific help, you'll nee... | [
5
] | [] | [] | [
"html_parsing",
"json",
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0003575515_html_parsing_json_python_screen_scraping_web_scraping.txt |
Q:
Get object created in child thread back in main thread
Assume i want to create 500 wxWidget like (some panels , color buttons and text ctrl etc), I have to create all this at single time but this will freeze my main thread, so i put this creation part in child thread and show some gif anim in main thread. But i wa... | Get object created in child thread back in main thread | Assume i want to create 500 wxWidget like (some panels , color buttons and text ctrl etc), I have to create all this at single time but this will freeze my main thread, so i put this creation part in child thread and show some gif anim in main thread. But i was not able to get all these wxWidget object those created on... | [
"You could use pubsub which is included with wxpython -- wx.lib.pubsub.\nSee my answer here for a basic example of usage for inter-thread comms.\n\nFor an alternative: An example of how you could use wx.Yield to keep your window updated.\nimport wx\n\nclass GUI(wx.Frame):\n def __init__(self, parent, title=\"\")... | [
2,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003574714_python_wxpython.txt |
Q:
Preserving subelement namespace serialization with lxml
I have a few different XML documents that I'm trying to combine into one using lxml. The problem is that I need the result to preserve the namespaces on each of the sub-documents' root nodes. Lxml seems to want to push any namespace declarations used more t... | Preserving subelement namespace serialization with lxml | I have a few different XML documents that I'm trying to combine into one using lxml. The problem is that I need the result to preserve the namespaces on each of the sub-documents' root nodes. Lxml seems to want to push any namespace declarations used more than once to the root of the new document, which breaks in my ... | [
"You could try inserting XInclude elements first, and then resolving them with the .xinclude() method (see docs). That seems to preserve the namespace declarations (lxml keeps them when they originate from the parser, but not when you create elements yourself, or move elements from one document to another)\nNote th... | [
0
] | [] | [] | [
"lxml",
"namespaces",
"python",
"serialization",
"xml_namespaces"
] | stackoverflow_0003569712_lxml_namespaces_python_serialization_xml_namespaces.txt |
Q:
Pseudo-dicts as properties
I have a Python class C which should have two pseudo-dicts a and b. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed.
In pseudocode this would look like this:
class C:
def a.__getitem__(self, key):
... | Pseudo-dicts as properties | I have a Python class C which should have two pseudo-dicts a and b. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed.
In pseudocode this would look like this:
class C:
def a.__getitem__(self, key):
return 'a'
def b.__getite... | [
"Why not just define your own class?\nclass PseudoDict(object):\n def __init__(self, c):\n self.c = c\n\n def __getitem__(self, key):\n return self.c.somethingmagical()\n\nclass C(object):\n def __init__(self):\n self.a = PseudoDict(self)\n self.b = PseudoDict(self)\n\nc = C()\n... | [
1,
1
] | [] | [] | [
"methods",
"nested",
"nested_attributes",
"nested_class",
"python"
] | stackoverflow_0003572526_methods_nested_nested_attributes_nested_class_python.txt |
Q:
python pythonpath modules
Ok a short question:
Is there any SIMPLE software with a GUI, that lets me manage my pythonpath, path python version in mac?
So I could set my Python, pythonpath and python version i want to use.
Thanks!
@ katrielalex and S.Lott :
I had a very nightmare with installing modules in python a... | python pythonpath modules | Ok a short question:
Is there any SIMPLE software with a GUI, that lets me manage my pythonpath, path python version in mac?
So I could set my Python, pythonpath and python version i want to use.
Thanks!
@ katrielalex and S.Lott :
I had a very nightmare with installing modules in python and as pointed out correctly in ... | [
"This is a bit of a niche market! If you're technically competent enough to know what a PYTHONPATH is, you should probably be able to Google how to set environment variables on OSX. It requires editing a text file.\nhttp://adammechtley.com/2009/10/setting-up-your-pythonpath-environment-variable-globally-on-osx/\n"
... | [
1
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0003575840_python_pythonpath.txt |
Q:
Is this a known DES cipher? What DES cipher is it? DES-CTR?
import Crypto.Cipher.DES
import struct
def rol32(x, y):
ret = ((x<<y)&0xFFFFFFFF)|((x>>(32-y))&0xFFFFFFFF)
#print 'rol32', hex(x), hex(y), hex(ret)
return ret
def sub32(x, y):
ret = (x & 0xFFFFFFFF) - (y & 0xFFFFFFFF)
if ret < 0: ret ... | Is this a known DES cipher? What DES cipher is it? DES-CTR? | import Crypto.Cipher.DES
import struct
def rol32(x, y):
ret = ((x<<y)&0xFFFFFFFF)|((x>>(32-y))&0xFFFFFFFF)
#print 'rol32', hex(x), hex(y), hex(ret)
return ret
def sub32(x, y):
ret = (x & 0xFFFFFFFF) - (y & 0xFFFFFFFF)
if ret < 0: ret += 0x100000000
#print 'sub32', hex(x), hex(y), hex(ret)
r... | [
"No. It is certainly not CTR-mode.\nIt looks like a disc encryption mode. In particular the encryption mode has some slight resemblance with LRW. The main idea is to tweak the input depending on the block number, so that encrypting the same block multiple times does not result in the same ciphertext.\nIt allows to ... | [
0
] | [] | [] | [
"algorithm",
"cryptography",
"encryption",
"python"
] | stackoverflow_0003557803_algorithm_cryptography_encryption_python.txt |
Q:
How can I get pointer type behaviour in python
I want to write a test case which will test a list of functions.
Here is an example of what I want to do:
from mock import Mock
def method1 ():
pass
def method2 ():
pass
## The testcase will then contain:
for func in method_list:
func = Mock()
# cont... | How can I get pointer type behaviour in python | I want to write a test case which will test a list of functions.
Here is an example of what I want to do:
from mock import Mock
def method1 ():
pass
def method2 ():
pass
## The testcase will then contain:
for func in method_list:
func = Mock()
# continue to setup the mock and do some testing
What I w... | [
"Um, how about simply modifiying method_list?\nfor i in range(len(method_list)): # xrange in Python 2\n method_list[i] = Mock()\n\nWhat you describe is closer to C++ references than to pointers. Few languages have such semantics (a few provide a special keyword for pass-by-reference), including Python.\n",
"If... | [
1,
1,
1
] | [] | [] | [
"monkeypatching",
"python"
] | stackoverflow_0003575639_monkeypatching_python.txt |
Q:
Mercurial http interface under Ubuntu Hardy. Doesn't work
I am trying to deploy mercurial under Ubuntu 8.04.
Mercurial packages were installed correctly, but when I've configured http interface I always get 500 error.
I enabled outputting debug info to error.log and got:
mod_wsgi (pid=21159): Exception occurred wi... | Mercurial http interface under Ubuntu Hardy. Doesn't work | I am trying to deploy mercurial under Ubuntu 8.04.
Mercurial packages were installed correctly, but when I've configured http interface I always get 500 error.
I enabled outputting debug info to error.log and got:
mod_wsgi (pid=21159): Exception occurred within WSGI script
'/home/hg/rep/hgwebdir.wsgi'.
Traceback (most ... | [
"Which version of mercurial are you using? If you're still using the 1.0.x that ubuntu ships update to the PPAs from launchpad: https://launchpad.net/~mercurial-ppa/+archive/stable-snapshots\nIn 1.6 hgwebdir has been renamed to just 'hgweb' which will alter your config slightly.\nAlso what are you using the launch... | [
1
] | [] | [] | [
"mercurial",
"python",
"ubuntu"
] | stackoverflow_0003575783_mercurial_python_ubuntu.txt |
Q:
Extracting Text from Parsed HTML with Python
I'm new to Python and I have been trying to search through html with regular expressions that has been parsed with BeautifulSoup. I haven't had any success and I think the reason is that I don't completely understand how to set up the regular expressions properly. I've ... | Extracting Text from Parsed HTML with Python | I'm new to Python and I have been trying to search through html with regular expressions that has been parsed with BeautifulSoup. I haven't had any success and I think the reason is that I don't completely understand how to set up the regular expressions properly. I've looked at older questions about similar problems b... | [
"BeautifulSoup could also extract node values from your html.\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = ('<html><head><title>Page title</title></head>'\n '<body>'\n '<table><tr>'\n '<td class=\"name\"><a href=\"/torrent/32726/0/\">Slackware Linux 13.0 [x86 DVD ISO]</a></td>'\n '<td ... | [
3,
2
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0003575359_html_python_regex.txt |
Q:
Urllib2 authentication with API key
I am trying to connect to radian6 api, which requires the auth_appkey, auth_user and auth_pass as md5 encryption.
When I am trying to connect using telnet I can get the response xml successfully
telnet sandboxapi.radian6.com 80
Trying 142.166.170.31...
Connected to sandboxapi.... | Urllib2 authentication with API key | I am trying to connect to radian6 api, which requires the auth_appkey, auth_user and auth_pass as md5 encryption.
When I am trying to connect using telnet I can get the response xml successfully
telnet sandboxapi.radian6.com 80
Trying 142.166.170.31...
Connected to sandboxapi.radian6.com.
Escape character is '^]'.
GE... | [
"In your telnet session, you're not setting the Authorization: header, but that's what HTTPBasicAuthHandler uses. (You could listen in on this using wireshark or similar.) Presumably the API doesn't use HTTP Basic Authentication but its home-brew variant. You probably want to drop that line and set the HTTP headers... | [
1
] | [] | [] | [
"api_key",
"authentication",
"python",
"urllib2"
] | stackoverflow_0003576201_api_key_authentication_python_urllib2.txt |
Q:
Problem with 2D interpolation in SciPy, non-rectangular grid
I've been trying to use scipy.interpolate.bisplrep() and scipy.interpolate.interp2d() to find interpolants for data on my (218x135) 2D spherical-polar grid. To these I pass 2D arrays, X and Y, of the Cartesian positions of my grid nodes. I keep getting e... | Problem with 2D interpolation in SciPy, non-rectangular grid | I've been trying to use scipy.interpolate.bisplrep() and scipy.interpolate.interp2d() to find interpolants for data on my (218x135) 2D spherical-polar grid. To these I pass 2D arrays, X and Y, of the Cartesian positions of my grid nodes. I keep getting errors like the following (for linear interp. with interp2d):
"Warn... | [
"Added 27Aug: Kyle followed this up on a\nscipy-user thread.\n30Aug: @Kyle, it looks as though there's a mixup between Cartesion X,Y and polar Xnew,Ynew.\nSee \"polar\" in the too-long notes below.\n\n# griddata vs SmoothBivariateSpline\n# http://stackoverflow.com/questions/3526514/\n# problem-with-2d-interpolati... | [
19
] | [] | [] | [
"interpolation",
"python",
"scipy"
] | stackoverflow_0003526514_interpolation_python_scipy.txt |
Q:
Trying to parse an XML file with Python - what am I doing wrong?
I'm working with XML and Python for the first time. The ultimate goal is to send a request to a REST service, receive a response in XML, and parse the values and send emails depending on what was returned. However, the REST service is not yet in plac... | Trying to parse an XML file with Python - what am I doing wrong? | I'm working with XML and Python for the first time. The ultimate goal is to send a request to a REST service, receive a response in XML, and parse the values and send emails depending on what was returned. However, the REST service is not yet in place, so for now I'm experimenting with an XML file saved on my C drive.
... | [
"Does this help?\ndoc = '''<Response>\n <exitCode>1</exitCode>\n <fileName>C:/Something/</fileName>\n <errors>\n <error>Error generating report</error>\n </errors>\n</Response>'''\n\nfrom xml.dom import minidom\n\nsomething = minidom.parseString( doc )\n\nnodeList = [ ]\nfor node in something.get... | [
3,
3,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0003576190_python_xml.txt |
Q:
Blob object for python (ctypes), C++
Hallo!
I want a blob object which I can pass around in python and from time to time give it to a C++ function to write to.
ctypes seems the way to go but I have problem with the python standard functions.
For example:
>>> import ctypes
>>> T=ctypes.c_byte * 1000
>>> blob = T()
... | Blob object for python (ctypes), C++ | Hallo!
I want a blob object which I can pass around in python and from time to time give it to a C++ function to write to.
ctypes seems the way to go but I have problem with the python standard functions.
For example:
>>> import ctypes
>>> T=ctypes.c_byte * 1000
>>> blob = T()
>>> ctypes.pointer(blob)
<__main__.LP_c_by... | [
"You'll probably have better luck with using string buffers and accessing the content through the raw attribute value\npstr = ctypes.create_string_buffer( 1000 )\nf.write( pstr.raw )\n\n"
] | [
0
] | [] | [] | [
"blob",
"ctypes",
"python"
] | stackoverflow_0003575564_blob_ctypes_python.txt |
Q:
make python os.chdir follow vim autochdir?
I use the autochdir option in VIM and I also utilize VIM's built-in Python interface. Is it possible to have the current directory for the built-in Python interpreter follow VIM's autochdir. For example, when I am editing a Python file, VIM's autochdir option puts me in ... | make python os.chdir follow vim autochdir? | I use the autochdir option in VIM and I also utilize VIM's built-in Python interface. Is it possible to have the current directory for the built-in Python interpreter follow VIM's autochdir. For example, when I am editing a Python file, VIM's autochdir option puts me in the same directory as the edited file as far as ... | [
"You could try putting in vimrc\nautocmd Filetype python py os.chdir(directory)\n\nwhich means that whenever a python file is read or written, it executes this command.\n"
] | [
2
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0003566228_python_vim.txt |
Q:
Custom sort of directory contents
I have a number of directories containing the files similar to the below example:
test
setup
adder
hello
_CONFIG
TEST2
The file(s) in these directories with the prefix _ represent configuration files of significance. The aim was to have these files appear first when I listed the ... | Custom sort of directory contents | I have a number of directories containing the files similar to the below example:
test
setup
adder
hello
_CONFIG
TEST2
The file(s) in these directories with the prefix _ represent configuration files of significance. The aim was to have these files appear first when I listed the directory i.e. I would like to be provi... | [
"sorted( ..., key = lambda s: ( not s.startswith( \"_\" ), s ) )\n\n",
"for element in sorted(os.listdir(path), key=lambda x:x.replace('_', ' ')):\n print(element)\n\n"
] | [
2,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003576678_python_sorting.txt |
Q:
How can I get Eclipse / PyDev to ignore alternatives to cls?
I have inherited some code that uses klass instead of PyDev's preferred cls:
def func(klass):
# do something that doesn't reference klass
return True
PyDev issues a warning that there is an unused parameter klass, which it wouldn't do if we used... | How can I get Eclipse / PyDev to ignore alternatives to cls? | I have inherited some code that uses klass instead of PyDev's preferred cls:
def func(klass):
# do something that doesn't reference klass
return True
PyDev issues a warning that there is an unused parameter klass, which it wouldn't do if we used the parameter cls.
Is there an easy way to let PyDev know that kl... | [
"The only unused name Pydev doesn't warn about is _.\ncls is the name used for the first argument in classmethods, but that doesnt seem to be the case here.\n",
"If you're using PyDev's built-in code analysis, go to Preferences > Pydev > Editor > Code Analysis, and switch to the 'Unused' tab. At the bottom is a ... | [
0,
0
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003575828_eclipse_pydev_python.txt |
Q:
copy objects between different Virtual-Machines efficiently
I have a feeling that I am going to ask a "stupid" question, yet I must ask ...
I have 2 virtual machines.
I would like to copy an instance of an object from one to another,
Is it possible to copy the bits that represents this object in the VM's heap, sen... | copy objects between different Virtual-Machines efficiently | I have a feeling that I am going to ask a "stupid" question, yet I must ask ...
I have 2 virtual machines.
I would like to copy an instance of an object from one to another,
Is it possible to copy the bits that represents this object in the VM's heap, send it to the other VM, like that the other VM just need to allocat... | [
"Lets ignore for a second the naive assumption that you can generalize this question over multiple VMs easily. Any attempt to build a mechanism like this would be heavily dependent on the implementation details of the VM you were building the mechanism for.\nHere are several reasons why this isn't done:\n\nIn-core ... | [
7,
2,
0
] | [] | [] | [
"c#",
"java",
"javascript",
"python",
"vm_implementation"
] | stackoverflow_0003575218_c#_java_javascript_python_vm_implementation.txt |
Q:
_really_ disable GtkTreeView searching
How do I really disable gtk treeview interactive search? The docs say to set_enable_search(False), but if I do this, CTRL+F still causes an annoying search pop-up to appear. Connecting to start-interactive-search and returning True doesn't work either.
A:
The pygtk docs don... | _really_ disable GtkTreeView searching | How do I really disable gtk treeview interactive search? The docs say to set_enable_search(False), but if I do this, CTRL+F still causes an annoying search pop-up to appear. Connecting to start-interactive-search and returning True doesn't work either.
| [
"The pygtk docs don't state this, but the C docs do:\ngtk_tree_view_set_search_column (GtkTreeView *tree_view, gint column)\n\ncolumn :\n the column of the model to search in, or -1 to disable searching \n\nPassing -1 for the column really disables searching.\n"
] | [
9
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003577224_gtk_gtktreeview_pygtk_python.txt |
Q:
How can I change windows codepage in python?
>>> a = os.popen('chcp 65001')
>>> a.read()
'Active code page: 65001\n'
>>> a.close()
>>> a = os.popen('chcp')
>>> a.read()
'Active code page: 437\n'
>>> a.close()
After I set the codepage to 65001, the next time i call chcp it should say the active codepage is 65001, ... | How can I change windows codepage in python? | >>> a = os.popen('chcp 65001')
>>> a.read()
'Active code page: 65001\n'
>>> a.close()
>>> a = os.popen('chcp')
>>> a.read()
'Active code page: 437\n'
>>> a.close()
After I set the codepage to 65001, the next time i call chcp it should say the active codepage is 65001, not 437. I tried this in windows command prompt a... | [
"The reason is that every time you call os.popen you are spawning a new process. Try opening up two cmd.exe sessions and running chcp 65001 in one and chcp in the other -- that's what you are doing here in your Python code.\nOne thing to note: all of the [popen*()][1] calls are depreciated as of Python 2.6. The ... | [
3
] | [] | [] | [
"codepages",
"python"
] | stackoverflow_0003577249_codepages_python.txt |
Q:
Do Django Fixtures load in incorrect order when testing?
I am testing my application and I am running into an issue and I'm not sure why. I'm loading fixtures for my tests and the fixtures have foreign keys that rely on each other. They must be loaded in a certain order or it won't work.
The fixtures I'm loading a... | Do Django Fixtures load in incorrect order when testing? | I am testing my application and I am running into an issue and I'm not sure why. I'm loading fixtures for my tests and the fixtures have foreign keys that rely on each other. They must be loaded in a certain order or it won't work.
The fixtures I'm loading are:
["test_company_data", "test_rate_index", 'test_rate_descri... | [
"\nDjango's documentation states that the fixtures load in the order they are declared, but this doesn't seem to be the case.\n\nThis is certainly strange. Fixtures are getting loaded in the proper order when I tested one of my projects (Django 1.2.1, Python 2.6.2, Postgresql 8.3.11).\nHere is what I'd do to troubl... | [
1
] | [] | [] | [
"django",
"django_fixtures",
"python"
] | stackoverflow_0003575867_django_django_fixtures_python.txt |
Q:
Set comprehensions don't work on Pydev (Python)
{x for x in range(10)}
works perfectly on IDLE, but when I try this in eclipse (with Pydev plugin) I get a syntax error:
Undefined variable: x
Is it because Pydev doesn't support set comprehensions or something? What can I do to make this work?
(This was just one ... | Set comprehensions don't work on Pydev (Python) | {x for x in range(10)}
works perfectly on IDLE, but when I try this in eclipse (with Pydev plugin) I get a syntax error:
Undefined variable: x
Is it because Pydev doesn't support set comprehensions or something? What can I do to make this work?
(This was just one example that doesn't work. All set comprehensions don... | [
"This is a bug in PyDev; in this case ignore the editor's warning and execute the code: it will work.\nI get this a lot, PyDev isn't perfect but it's good enough!\n",
"Make sure that Pydev is configured to use Python 3.\n",
"You can find out which version of Python you are using with\nimport sys\nsys.stdout.wri... | [
3,
2,
0
] | [] | [] | [
"eclipse_plugin",
"list_comprehension",
"pydev",
"python",
"set"
] | stackoverflow_0003576927_eclipse_plugin_list_comprehension_pydev_python_set.txt |
Q:
Sending multiple POST data items with the same name, using AppEngine
I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values.
form_fields = {
"data": "foo",
"data": "bar"
}
form_data = urllib.urlencode(form_fields)
result = ... | Sending multiple POST data items with the same name, using AppEngine | I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values.
form_fields = {
"data": "foo",
"data": "bar"
}
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url="http://www.foo.com/", payload=form_data, method=urlfet... | [
"Modify your form_fields dictionary so that fields with the same name are turned into lists, and use the doseq argument to urllib.urlencode:\nform_fields = {\n \"data\": [\"foo\",\"bar\"]\n}\n\nform_data = urllib.urlencode(form_fields, doseq=True)\n\nAt this point, form_data is 'data=foo&data=bar', which is what ... | [
14,
1
] | [] | [] | [
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0003577064_google_app_engine_python_urlfetch.txt |
Q:
in gql, how do i sort by a field in another class linked by referenceproperty?
for example, 2 classes in a 1-to-many relationship:
class owner(db.model):
name = db.StringProperty()
class cat(db.model):
name = db.StringProperty()
owner = db.ReferenceProperty(owner)
so how do i produce a list of cats o... | in gql, how do i sort by a field in another class linked by referenceproperty? | for example, 2 classes in a 1-to-many relationship:
class owner(db.model):
name = db.StringProperty()
class cat(db.model):
name = db.StringProperty()
owner = db.ReferenceProperty(owner)
so how do i produce a list of cats ordered by owner.name (then optionally by cat.name)?
i tried
"SELECT * FROM cat O... | [
"You can't; this would require a join, which the datastore doesn't support. If you need to sort like this, denormalize your data and include the owner name in the cat model.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0003573122_google_app_engine_gql_python.txt |
Q:
SSH Tunnel for Python MySQLdb connection
I tried creating a SSH tunnel using
ssh -L 3306:localhost:22 <hostip>
Then running my python script to connect via localhost
conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test')
However, I receive the following error
(2002, "Can't connect... | SSH Tunnel for Python MySQLdb connection | I tried creating a SSH tunnel using
ssh -L 3306:localhost:22 <hostip>
Then running my python script to connect via localhost
conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test')
However, I receive the following error
(2002, "Can't connect to local MySQL server through socket '/var/li... | [
"Try changing \"localhost\" to \"127.0.0.1\", it should work as you expect. This behavior is detailed in the manual:\n\nUNIX sockets and named pipes don't\n work over a network, so if you specify\n a host other than localhost, TCP will\n be used, and you can specify an odd\n port if you need to (the default por... | [
18,
13,
3
] | [] | [] | [
"mysql",
"python",
"ssh"
] | stackoverflow_0003577555_mysql_python_ssh.txt |
Q:
Python: How do I convert an int to its string representation with a set number of digits?
Pretty much what it says up there.
Basically, how do I get the string produced by
print "%05d" % 100
A:
Maybe I'm misinterpreting the question, but this should work:
my_string = "%05d" % 100
A:
Use str.zfill(width)
A:
... | Python: How do I convert an int to its string representation with a set number of digits? | Pretty much what it says up there.
Basically, how do I get the string produced by
print "%05d" % 100
| [
"Maybe I'm misinterpreting the question, but this should work:\nmy_string = \"%05d\" % 100\n\n",
"Use str.zfill(width)\n",
"This should work too:\n`100`.zfill(5)\n\n",
"print('{0:0=5d}'.format(100))\n# 00100\n\n\n use the 0th positional argument to format\n / fill character is '0'\n / / desired width ... | [
11,
1,
1,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003577582_python_string.txt |
Q:
Substitute for u'string'
I saved my script in UTF-8 encoding.
I changed my codepage on windows to 65001.
I'm on python 2.6
Script #1
# -*- coding: utf-8 -*-
print u'Español'
x = raw_input()
Script #2
# -*- coding: utf-8 -*-
a = 'Español'
a.encode('utf8')
print a
x = raw_input()
Script #1, prints the word fine wi... | Substitute for u'string' | I saved my script in UTF-8 encoding.
I changed my codepage on windows to 65001.
I'm on python 2.6
Script #1
# -*- coding: utf-8 -*-
print u'Español'
x = raw_input()
Script #2
# -*- coding: utf-8 -*-
a = 'Español'
a.encode('utf8')
print a
x = raw_input()
Script #1, prints the word fine with no errors, Script #2 does e... | [
"Change your code to the following:\n# -*- coding: utf-8 -*-\na = 'Español'\na = a.decode('utf8')\nprint a\nx = raw_input()\n\nDecode specifies how the string should be read, and returns the value. Making the changes above should fix your problem.\nThe problem is that python stores a string as a list of bytes, rega... | [
8,
5
] | [] | [] | [
"python",
"utf_8"
] | stackoverflow_0003577561_python_utf_8.txt |
Q:
In Python, how to add distinct items to a list of dicts from another dict?
In Python, the original dict list is as follows:
orig = [{'team': 'team1', 'other': 'blah', 'abbrev': 't1'},
{'team': 'team2', 'other': 'blah', 'abbrev': 't2'},
{'team': 'team3', 'other': 'blah', 'abbrev': 't3'},
{'t... | In Python, how to add distinct items to a list of dicts from another dict? | In Python, the original dict list is as follows:
orig = [{'team': 'team1', 'other': 'blah', 'abbrev': 't1'},
{'team': 'team2', 'other': 'blah', 'abbrev': 't2'},
{'team': 'team3', 'other': 'blah', 'abbrev': 't3'},
{'team': 'team1', 'other': 'blah', 'abbrev': 't1'},
{'team': 'team3', 'othe... | [
"dict keys are unique, which you can exploit:\nteamdict = dict([(data['team'], data) for data in t])\nnew = [{'team': team, 'abbrev': data['abbrev']} for (team, data) in teamdict.items()]\n\nCan't help to suggest that a dict might be your data structure of choice to begin with.\nOh, I don't know how dict() reacts t... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003577833_python.txt |
Q:
cPickle.UnpicklingError: invalid load key
My program work fine on windows, with cpickle, and I am using binary mode, like 'wb', or 'rb'. When I ran my program on Linux, it still works fine.
But when I tried to unpickle the files obtained from the Linux platform on my windows platform, I got this wired message says... | cPickle.UnpicklingError: invalid load key | My program work fine on windows, with cpickle, and I am using binary mode, like 'wb', or 'rb'. When I ran my program on Linux, it still works fine.
But when I tried to unpickle the files obtained from the Linux platform on my windows platform, I got this wired message says: cPickle.UnpicklingError: invalid load key'
'... | [
"Looking at the code (http://svn.python.org/view/python/trunk/Modules/cPickle.c?revision=81029&view=markup), it looks like it was a parsing error (load key is a pickle format key). It sounds like the file has been altered.\nHow were the files transferred from Linux to Windows? If it was FTP, did you transfer in b... | [
4
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0003577382_pickle_python.txt |
Q:
How to print japanese utf-8 on console in windows?
#coding=<utf8>
import os
os.popen('chcp 65001')
a = 'こんにちは世界'
print a.decode('utf8')
x = raw_input()
PYTHON 2.6 on Windows 7
It will run in IDLE with no errors.
However when run from the console, it errors and flashes very quickly and I can't read the error mes... | How to print japanese utf-8 on console in windows? | #coding=<utf8>
import os
os.popen('chcp 65001')
a = 'こんにちは世界'
print a.decode('utf8')
x = raw_input()
PYTHON 2.6 on Windows 7
It will run in IDLE with no errors.
However when run from the console, it errors and flashes very quickly and I can't read the error message.
How can it be done in windows console?
By the way,... | [
"Update\nNever mind. The OP is using Windows. \nInterestingly changing the encoding declaration to #encoding=<utf8> did not work in Ubuntu.\nOriginal Answer\nThis worked for me (Ubuntu Jaunty, Python 2.6.2). The only change I made was to the first line declaring the encoding.\n# encoding: utf-8 \nimport os\nos.pop... | [
0
] | [] | [] | [
"python",
"utf_8"
] | stackoverflow_0003578104_python_utf_8.txt |
Q:
Selenium, with Python, how to simplify scripts so that I can run them from other python scripts?
I'm having some trouble figuring out how to take out what is not necessary in a selenium strip and package it in such a way that I can call it from another script.. I am having trouble understanding what is going on wi... | Selenium, with Python, how to simplify scripts so that I can run them from other python scripts? | I'm having some trouble figuring out how to take out what is not necessary in a selenium strip and package it in such a way that I can call it from another script.. I am having trouble understanding what is going on with this, as I don't get where the unit testint parts are coming from... ideally if I could just separa... | [
"What I would recommend is to make functions in your other script that have as an argument a reference to the test case. That way, your functions could fail the test case if something does not go right. Like so (to search google for a string and check the title):\ndef search_s(utest, in_str):\n s = utest.selenium\... | [
1
] | [] | [] | [
"python",
"selenium",
"unit_testing"
] | stackoverflow_0003577986_python_selenium_unit_testing.txt |
Q:
mplot3d broken ubuntu 10.04
I'm trying to use mplot3d. I installed matibplot using the Ubuntu (lucid) repositories and it seems broken out-of-the-box. Any help would be appreciated.
This is the code I'm running:
from __future__ import division
from mpl_toolkits.mplot3d import Axes3D
from random import *
from scipy... | mplot3d broken ubuntu 10.04 | I'm trying to use mplot3d. I installed matibplot using the Ubuntu (lucid) repositories and it seems broken out-of-the-box. Any help would be appreciated.
This is the code I'm running:
from __future__ import division
from mpl_toolkits.mplot3d import Axes3D
from random import *
from scipy import *
import matplotlib.pyplo... | [
"First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib. \nWhich version are you using? (Try running: python -c 'import matplotlib; print matplotlib.__version__')\nI'm guessing you're running version 0.99, in which case you'll need to eithe... | [
1
] | [] | [] | [
"matplotlib",
"python",
"ubuntu_10.04"
] | stackoverflow_0003576875_matplotlib_python_ubuntu_10.04.txt |
Q:
Does this web app require a task queue?
Background
I have a web app that will create an image from user input.
The image creation could take up to a couple seconds.
Problem
If I let the server thread, that is handling the request/response also generate the image, that is going to tie up a thread for a couple secon... | Does this web app require a task queue? | Background
I have a web app that will create an image from user input.
The image creation could take up to a couple seconds.
Problem
If I let the server thread, that is handling the request/response also generate the image, that is going to tie up a thread for a couple seconds, and possibly bog down my server, affect p... | [
"I'm going to say No - for now.\n\nA couple of second is not that long.\nYou'll anyway have to implement some sort of polling (or comet processing) to feed the image back to the user.\nIt will make your system more complex.\nDesign the system so adding on a task queue later on is feasible and easy.\n\nSo, keep it s... | [
6,
0,
0
] | [] | [] | [
"architecture",
"celery",
"python"
] | stackoverflow_0003578218_architecture_celery_python.txt |
Q:
Django: Update Field Value Based on Other Fields
I am not sure this is even possible without modifying the Admin interface.
I have a model called "Quote" that can contain multiple "Product" models. I connect the two using an intermediate model "QuoteIncludes". Here are the three models as they currently stand:
cla... | Django: Update Field Value Based on Other Fields | I am not sure this is even possible without modifying the Admin interface.
I have a model called "Quote" that can contain multiple "Product" models. I connect the two using an intermediate model "QuoteIncludes". Here are the three models as they currently stand:
class Product(models.Model):
name = models.CharField(... | [
"Info on how to include js in your model admin:\nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions\nFor example:\nclass Media:\n js = (\n 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js',\n '/media/js/calculate.js',\n )\n\nAnd your script could l... | [
3,
0
] | [] | [] | [
"admin",
"django",
"django_admin",
"methods",
"python"
] | stackoverflow_0003570898_admin_django_django_admin_methods_python.txt |
Q:
I can`t decide what to select: ASP.NET MVC 2 (C#) or Django (Python)?
I`m learning programming languages. And I decide that I need to lear a new web framework. I have 2 candidates: Django or ASP.NET MVC 2.
Can you say me the difference between them and what is so interesting?
A:
Try both, then decide.
A:
Wel... | I can`t decide what to select: ASP.NET MVC 2 (C#) or Django (Python)? | I`m learning programming languages. And I decide that I need to lear a new web framework. I have 2 candidates: Django or ASP.NET MVC 2.
Can you say me the difference between them and what is so interesting?
| [
"Try both, then decide.\n",
"Well, I'm using both and found both to be state of the art, easy to learn, fast and easy to install. \nMaybe don't look at it from a technical standpoint but from the context. ASP.NET needs a Windows Server, ASP.NET and an IIS installed. You have the license for that? Django on the ot... | [
4,
2,
1,
1
] | [] | [] | [
"asp.net_mvc_2",
"c#",
"django",
"python"
] | stackoverflow_0003578822_asp.net_mvc_2_c#_django_python.txt |
Q:
Invalid syntax problem with Python (running pygame)
I've been using The New Boston tutorial (http://www.youtube.com/watch?v=x9M3R6igH2E) on how to program with pygame and I keep getting an "invalid syntax" error on the print self.diff command. Only the self is highlighted. Here is the code (i've bolded the problem... | Invalid syntax problem with Python (running pygame) | I've been using The New Boston tutorial (http://www.youtube.com/watch?v=x9M3R6igH2E) on how to program with pygame and I keep getting an "invalid syntax" error on the print self.diff command. Only the self is highlighted. Here is the code (i've bolded the problem):
class vector(object):
def __init__(self, list1, list2)... | [
"Python 3? If so, arguments to print must be enclosed in parentheses: print(self.diff).\nIf your learning materials and tutorials are based on the Python 2.x branch, you won't be too lucky with Python 3. Otherwise it's a great choice because it cleans up with many of the issues of the older Python versions.\n"
] | [
2
] | [] | [] | [
"python",
"syntax",
"vector"
] | stackoverflow_0003579144_python_syntax_vector.txt |
Q:
What is the best solution to bind objects in wx.DC?
So, for example I draw some objects on wx.PaintDC, such as lines and rectangles.
Now I want next: on mouse click I wont know which object was clicked.
Of course, I can see what object is the closest, but what about more exact answer?
Maybe even not standart wx.DC... | What is the best solution to bind objects in wx.DC? | So, for example I draw some objects on wx.PaintDC, such as lines and rectangles.
Now I want next: on mouse click I wont know which object was clicked.
Of course, I can see what object is the closest, but what about more exact answer?
Maybe even not standart wx.DC, but such things as FloatCanvas or something like this.
... | [
"You can use a PseudoDC and its FindObjects method\nIn my drawing program, Whyteboard I employ a whole bunch of maths, polymorphic classes and such to allow users to \"hit test\" drawn items with the Select drawing tool.\nYou can also do this with FloatCanvas, it provides HitTest(x, y) (off the top of my head) meth... | [
1,
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0003576071_python_user_interface_wxpython.txt |
Q:
SQLAlchemy override types.DateTime on raw sql expressions
is it possible to override the default type.DateTime behaviour when using sqlalchemy with raw sql expressions?
for example when using
myconnection.execute(text("select * from mytable where mydate > :mydate), {'mydate': mypythondatetimeobject)}
, i would li... | SQLAlchemy override types.DateTime on raw sql expressions | is it possible to override the default type.DateTime behaviour when using sqlalchemy with raw sql expressions?
for example when using
myconnection.execute(text("select * from mytable where mydate > :mydate), {'mydate': mypythondatetimeobject)}
, i would like to have type.DateTime to automatically strip the TimeZone fr... | [
"If you used SQL expressions based on Table metadata, then you'd just set your MyType on the appropriate columns. The plain text approach loses some convenience. You could stick your MyType into the sqlalchemy.types.type_map keyed to the datetime class, though this is currently not public API.\nIf it were me I'... | [
1
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0003567131_postgresql_python_sqlalchemy.txt |
Q:
Using PIL on web hosting machine
I want to be able to use the PIL library on a web hosting machine. The machine has Python 2.4.3 installed, but not the PIL library. I tried downloading the PIL source and putting the PIL folder into my directory. It kind of works, except when I need to do some actual image processi... | Using PIL on web hosting machine | I want to be able to use the PIL library on a web hosting machine. The machine has Python 2.4.3 installed, but not the PIL library. I tried downloading the PIL source and putting the PIL folder into my directory. It kind of works, except when I need to do some actual image processing, which brings up an ImportError, sa... | [
"You need to compile that module. Running the setup.py install command should do it for you, provided the host has a working compiler and the required libraries. You can use virtualenv to have it installed somewhere where you have rights to put files (by default it would try to install it system-wide).\nIf it doesn... | [
1,
0
] | [] | [] | [
"python",
"python_imaging_library",
"web_hosting"
] | stackoverflow_0003560246_python_python_imaging_library_web_hosting.txt |
Q:
Could someone help me here? Python object maintaining between separate functions
I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem.
import copy
class Obj(object):
def __init__(self, name):
self.name = name
def one(o):
print("1: o.name... | Could someone help me here? Python object maintaining between separate functions | I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem.
import copy
class Obj(object):
def __init__(self, name):
self.name = name
def one(o):
print("1: o.name:", o.name) # "foo"
obackup = copy.deepcopy(o)
o.name = "bar"
print("2: o... | [
"Forget that the copy module exists, it almost never is needed and often produces surprising results.\nAs soon as you say o = obackup in one() you have created a new binding for the formal argument which then goes out of scope after print('4...\n",
"o is a local variable to the one() so this problem cannot be fix... | [
2,
0
] | [] | [] | [
"oop",
"python",
"scope"
] | stackoverflow_0003579447_oop_python_scope.txt |
Q:
How to parse broken XML in Python?
A sever I can't influence sends very broken XML.
Specifically, a Unicode WHITE STAR would get encoded as UTF-8 (E2 98 86) and then translated using a Latin-1 to HTML entity table. What I get is â 98 86 (9 bytes) in a file that's declared as utf-8 with no DTD.
I couldn't con... | How to parse broken XML in Python? | A sever I can't influence sends very broken XML.
Specifically, a Unicode WHITE STAR would get encoded as UTF-8 (E2 98 86) and then translated using a Latin-1 to HTML entity table. What I get is â 98 86 (9 bytes) in a file that's declared as utf-8 with no DTD.
I couldn't configure W3C tidy in a way that doesn't ga... | [
"BeautifulSoup is your best bet in this case. I suggest profiling before ruling out BeautifulSoup altogether. \n",
"Maybe something like:\nimport htmlentitydefs as ents\nfrom lxml import etree # or maybe 'html' , if the input is still more broken\ndef repl_ent(m): \n return ents.entitydefs[m.group()[1:-1]]\n... | [
2,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0003577652_python_xml.txt |
Q:
python: complex string algorithm
i have a list
listcdtitles =
[""" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphonic Poem. (NW German Phil./ Kulka) """,
""" Puccini, Verdi, Gounod, Bizet: Arias & Duets from Butterfly, Tosca, Boheme, Turandot, I Ve... | python: complex string algorithm | i have a list
listcdtitles =
[""" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphonic Poem. (NW German Phil./ Kulka) """,
""" Puccini, Verdi, Gounod, Bizet: Arias & Duets from Butterfly, Tosca, Boheme, Turandot, I Vespri, Faust, Carmen. (Fiamma Izzo d'Am... | [
"I'm a newbie to python language but I've written a sample code that calculates similarity scores between entries in that list.\nThe code is as follows. \nimport re\nimport array\n\nlistcdtitles = [\"\"\" Liszt, Hungarian Rhapsody #6 {'Pesther Carneval'}; 2 Episodes from Lenau's 'Faust'; 'Hunnenschlacht' Symphon... | [
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003570959_python_string.txt |
Q:
SQL to handle table updates in a "dynamically typed" fashion
I'm playing around with Python 3's sqlite3 module, and acquainting myself with SQL in the process.
I've written a toy program to hash a salted password and store it, the associated username, and the salt into a database. I thought it would be intuitive t... | SQL to handle table updates in a "dynamically typed" fashion | I'm playing around with Python 3's sqlite3 module, and acquainting myself with SQL in the process.
I've written a toy program to hash a salted password and store it, the associated username, and the salt into a database. I thought it would be intuitive to create a function of the signature:
def store(table, data, datab... | [
"\nSQLite3 is dynamically typed, so no problem there.\nCREATE TABLE IF NOT EXISTS <name> ... See here.\nYou can see if the columns you need already exist in the table by using sqlite_master documented in this FAQ. You'll need to parse the sql column, but since it's exactly what your program provided to create the t... | [
1
] | [] | [] | [
"python",
"python_3.x",
"sql",
"sqlite"
] | stackoverflow_0003577324_python_python_3.x_sql_sqlite.txt |
Q:
Display GAE list by most recent entry
n00b problem- I am trying to have a list show the most recent entry first. This works without the reverse(), but retrieves nothing with it in. I have heard I should try and use order_by(), but I can't seem to get that to work either. Thanks for the help!
class MainHandler(weba... | Display GAE list by most recent entry | n00b problem- I am trying to have a list show the most recent entry first. This works without the reverse(), but retrieves nothing with it in. I have heard I should try and use order_by(), but I can't seem to get that to work either. Thanks for the help!
class MainHandler(webapp.RequestHandler):
def get(self):
que... | [
"In django, you use order_by(), but for GAE it is order().\nSo the answer was not in using reverse but:\nclass MainHandler(webapp.RequestHandler):\ndef get(self):\n\n que = db.Query(models.URL).order('-created')\n url_list = que.fetch(limit=100)\n\n path = self.request.path \n if doRender(self,pa... | [
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003577910_google_app_engine_python.txt |
Q:
How do I restore default settings of an application in Gtk (set all the widgets to the state as if the application was restarted)?
I would like to implement a button "New" that would work the same as File>New in most applications - that is: resets all the labels, treeviews, etc. to the original state.
Thank you, T... | How do I restore default settings of an application in Gtk (set all the widgets to the state as if the application was restarted)? | I would like to implement a button "New" that would work the same as File>New in most applications - that is: resets all the labels, treeviews, etc. to the original state.
Thank you, Tomas
| [
"The widgets don't remember their original state; you have to set them all back one by one. Give labels their original text, clear the tree views by setting their model to None.\nPerhaps it is better to destroy your window and rebuild it from your Glade file if you have one?\n"
] | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003577335_gtk_pygtk_python.txt |
Q:
Web gateway interfaces in Python 3
I've finally concluded that I can no longer afford to just hope the ongoing Py3k/WSGI disasterissues will be resolved anytime soon, so I need to get ready to move on.
Unfortunately, my available options don't seem a whole lot better:
While I find a few different Python modules f... | Web gateway interfaces in Python 3 | I've finally concluded that I can no longer afford to just hope the ongoing Py3k/WSGI disasterissues will be resolved anytime soon, so I need to get ready to move on.
Unfortunately, my available options don't seem a whole lot better:
While I find a few different Python modules for FastCGI scattered around the web, non... | [
"CherryPy 3.2 release candidates support Python 3.X. Because it only supports WSGI at the web server interface layer and not through the whole stack, then you are isolated from issues as to whether WSGI will change. CherryPy has its own internal WSGI server, but also can run under Apache/mod_wsgi with Python 3.1+. ... | [
2,
1
] | [] | [] | [
"fastcgi",
"python",
"python_3.x",
"wsgi"
] | stackoverflow_0003476481_fastcgi_python_python_3.x_wsgi.txt |
Q:
Behavior of Python exec() differs depending on the where it is called from
I have a Python script 'runme.py' that I am trying to execute from 'callerX.py' below. I am using exec(open(filename).read()) to accomplish this task. The script being executed contains a simple class that attempts to call the 'time()' func... | Behavior of Python exec() differs depending on the where it is called from | I have a Python script 'runme.py' that I am trying to execute from 'callerX.py' below. I am using exec(open(filename).read()) to accomplish this task. The script being executed contains a simple class that attempts to call the 'time()' function both from the global namespace & inside a function.
In all of the examples ... | [
"This has probably to do with how 'from x import *' works. If you call this from 'top-level', it gets imported into globals() for the whole module.\nHowever, if you call this inside a function, it gets imported only into locals() - in the function. The exec() gets evaluated inside a function in caller2; therefore t... | [
0
] | [
"Here's an idea: don't use exec. Basically every time I've seen someone use exec or eval it's because they don't know that a better way to accomplish the same thing already exists; it's a crutch that hinders writing dynamic code, not a way to write code that's somehow more dynamic.\n"
] | [
-1
] | [
"exec",
"python",
"scope"
] | stackoverflow_0003578573_exec_python_scope.txt |
Q:
mod_wsgi not working with pinax of django
I tried hard to configure mod_wsgi for an pinax project. I followed the exact instructions from the site (pinaxproject.org), unfortunately, I always got the following error:
[Thu Aug 26 17:32:46 2010] [error] [client 173.48.119.55] (13)Permission denied: mod_wsgi (pid=267... | mod_wsgi not working with pinax of django | I tried hard to configure mod_wsgi for an pinax project. I followed the exact instructions from the site (pinaxproject.org), unfortunately, I always got the following error:
[Thu Aug 26 17:32:46 2010] [error] [client 173.48.119.55] (13)Permission denied: mod_wsgi (pid=26749): Unable to connect to WSGI daemon process '... | [
"Read:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets\nSetup WSGISocketPrefix directive as indicated.\n"
] | [
0
] | [] | [] | [
"django",
"mod_wsgi",
"pinax",
"python",
"web_deployment_project"
] | stackoverflow_0003579850_django_mod_wsgi_pinax_python_web_deployment_project.txt |
Q:
Issues w/ Widget.hide()
Problem: Widget 'A' is a toplevel window that is displayed after a button click in MainWindow 'B'. How do I assign a handler to handle the signal sent back after the 'X' along the window border of Widget 'A' is clicked (see below for current implementation)?
def on_mainWindow_B_button_click... | Issues w/ Widget.hide() | Problem: Widget 'A' is a toplevel window that is displayed after a button click in MainWindow 'B'. How do I assign a handler to handle the signal sent back after the 'X' along the window border of Widget 'A' is clicked (see below for current implementation)?
def on_mainWindow_B_button_clicked(self, widget):
self.w... | [
"The handler for the delete_event signal must return True in order to stop the Window being permanently destroyed on closing.\n self.widget_a.connect('delete_event', self.on_widget_a_delete)\n\ndef on_widget_a_delete(self, widget, event):\n widget.hide()\n # do something\n return True\n\nIf you only wan... | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003580469_gtk_pygtk_python.txt |
Q:
Do Python regexes support something like Perl's \G?
I have a Perl regular expression (shown here, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I ... | Do Python regexes support something like Perl's \G? | I have a Perl regular expression (shown here, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?
| [
"Try these:\nimport re\nre.sub()\nre.findall()\nre.finditer()\n\nfor example:\n# Finds all words of length 3 or 4\ns = \"the quick brown fox jumped over the lazy dogs.\"\nprint re.findall(r'\\b\\w{3,4}\\b', s)\n\n# prints ['the','fox','over','the','lazy','dogs']\n\n",
"Python does not have the /g modifier for the... | [
4,
4,
2,
2,
0
] | [] | [] | [
"perl",
"python",
"regex"
] | stackoverflow_0000529830_perl_python_regex.txt |
Q:
PyGTK: Parent window wait until child window is showed
I'm learning PyGTK and I have a parent window and a child window. Inside of a parent window's method, i create the child window and then I refresh a treeview... something like that:
def add_user(self, widget, data = None):
save_user.SaveUser(self.window)
... | PyGTK: Parent window wait until child window is showed | I'm learning PyGTK and I have a parent window and a child window. Inside of a parent window's method, i create the child window and then I refresh a treeview... something like that:
def add_user(self, widget, data = None):
save_user.SaveUser(self.window)
self.load_tree_view()
But, when it's running, the child ... | [
"gtk.Dialog solves my problem but i don't know if is right use that ... When should I use a dialog?\n#! /usr/bin/python\n\nimport pygtk\nimport gtk\n\nclass Window:\n def __init__(self):\n self.window = gtk.Window()\n self.window.connect('delete-event', self.close_window)\n self.window.show(... | [
0
] | [] | [] | [
"methods",
"oop",
"pygtk",
"python",
"windows"
] | stackoverflow_0003579641_methods_oop_pygtk_python_windows.txt |
Q:
Sorting list of dictionaries according to specific order
I am using Python 2.6 and I have two data stores. Querying the first one returns a list of document IDs in a specific order. I look up all the documents at once in the second data store using these IDs, which returns a list of dictionaries (one for each doc)... | Sorting list of dictionaries according to specific order | I am using Python 2.6 and I have two data stores. Querying the first one returns a list of document IDs in a specific order. I look up all the documents at once in the second data store using these IDs, which returns a list of dictionaries (one for each doc), but not in the same order as the original list. I now need t... | [
"Don't.\nMove your \"list of dictionaries (one for each doc), but not in the same order as the original list\" into a dictionary.\nThis new dictionary-of-dictionaries has the matching key.\nThen go through your first list in it's order and find items in the dictionary-of-dictionaries that match.\nsome_list= query_d... | [
4,
1,
0
] | [] | [] | [
"dictionary",
"mapping",
"python",
"sorting"
] | stackoverflow_0003559960_dictionary_mapping_python_sorting.txt |
Q:
Python permanent assignment variables
I have just started python and came across something kind of strange.
The following code assigns a co-ordinate of x=1 and y=2 to the variable test. The test2 variable assigns itself the same value as test and then the [x] value for test2 is changed to the old [x] value minus 1... | Python permanent assignment variables | I have just started python and came across something kind of strange.
The following code assigns a co-ordinate of x=1 and y=2 to the variable test. The test2 variable assigns itself the same value as test and then the [x] value for test2 is changed to the old [x] value minus 1. This works fine, however, when the last p... | [
"In Python, like in Java, assignment per se never makes a copy -- rahter, assignment adds another reference to the same object as the right-hand side of the =. (Argument passing works the same way). Strange that you've never heard of the concept, when Python is quite popular and Java even much more so (and many o... | [
4,
3,
0,
0
] | [] | [] | [
"list",
"python",
"reference"
] | stackoverflow_0003580913_list_python_reference.txt |
Q:
tcp port 80 redirector in python for windows 7
I want to redirect the port 80 traffic to port 3128 for windows 7 , i want to write it in python.
I am relatively new to this....could you guys help ..by giving me some pointers regarding from where to start.
Thanks.
A:
http://code.activestate.com/recipes/483730/ or... | tcp port 80 redirector in python for windows 7 | I want to redirect the port 80 traffic to port 3128 for windows 7 , i want to write it in python.
I am relatively new to this....could you guys help ..by giving me some pointers regarding from where to start.
Thanks.
| [
"http://code.activestate.com/recipes/483730/ or http://code.activestate.com/recipes/114642/ might be good places to start\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003581154_python.txt |
Q:
about the return expression
level: beginner
the following code will print 'False'
def function(x):
if len(x) == 5: return True
else: return x[0] == x[-1]
print function('annb')
why does the line "else: return x[0] == x[-1]" print False?
i do understand what's happening but i'm having difficulties to put ... | about the return expression | level: beginner
the following code will print 'False'
def function(x):
if len(x) == 5: return True
else: return x[0] == x[-1]
print function('annb')
why does the line "else: return x[0] == x[-1]" print False?
i do understand what's happening but i'm having difficulties to put this into plain english...how can... | [
"Sorry, I'm not entirely sure what you mean, but here think of it this way:\nreturn (x[0] == x[-1])\n\nIf you only consider what is within the parenthesis, you realize that, that 'statement' equates to a boolean, right? That's why you can also do:\nif x[0] == x[-1]\n\nSo basically, what is being returned here is a ... | [
6,
1,
0
] | [] | [] | [
"python",
"return",
"semantics"
] | stackoverflow_0003580228_python_return_semantics.txt |
Q:
Django 1.2 Equivalent of QuerySet.query.as_sql()
In Django 1.1 I was able to produce the SQL used by a QuerySet with this notation:
QuerySet.query.as_sql()
In Django 1.2, this raises as AttributeError.
Anyone know the Django 1.2 equivalent of that method?
Thanks
A:
In Django 1.1, QuerySet.query returned a Base... | Django 1.2 Equivalent of QuerySet.query.as_sql() | In Django 1.1 I was able to produce the SQL used by a QuerySet with this notation:
QuerySet.query.as_sql()
In Django 1.2, this raises as AttributeError.
Anyone know the Django 1.2 equivalent of that method?
Thanks
| [
"In Django 1.1, QuerySet.query returned a BaseQuery object, now it returns a Query objects. The query object has a __str__ method defined that returns the SQL.\n",
"as answered in In django 1.2.1 how can I get something like the old .as_sql?\nit's just:\nprint QuerySet.query\n\n"
] | [
12,
4
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0002900057_django_django_queryset_python.txt |
Q:
py2exe error on MSVCR80.dll
from distutils.core import setup
import py2exe,sys,os
sys.argv.append('py2exe')
try:
setup(
options = {'py2exe': {'bundle_files': 1}},
console=['my_console_script.py'],
zipfile = None,
)
except Exception, e:
print e
outputs:
> running py2exe
> *** searching for... | py2exe error on MSVCR80.dll | from distutils.core import setup
import py2exe,sys,os
sys.argv.append('py2exe')
try:
setup(
options = {'py2exe': {'bundle_files': 1}},
console=['my_console_script.py'],
zipfile = None,
)
except Exception, e:
print e
outputs:
> running py2exe
> *** searching for required modules ***
> *** parsi... | [
"Append to your call to setup:\n{ 'py2exe': { ...,\n 'dll_excludes': [ 'msvcr80.dll', 'msvcp80.dll',\n 'msvcr80d.dll', 'msvcp80d.dll',\n 'powrprof.dll', 'mswsock.dll' ] }, ...\n\nIf you want to include the visual C runtime DLLs in your appli... | [
2
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0003581814_py2exe_python.txt |
Q:
Get angles in the range -180 to +180
Before I start thanking everybody.
Through my application s/w I will read syncro values which will be in angles.
When I run Python script, the values are collected in particular variables.
Suppose the range is -180 to 180.
And I got angle as -180. According to the requirement i... | Get angles in the range -180 to +180 | Before I start thanking everybody.
Through my application s/w I will read syncro values which will be in angles.
When I run Python script, the values are collected in particular variables.
Suppose the range is -180 to 180.
And I got angle as -180. According to the requirement it should be +/-1 deg window;ie; between 17... | [
"if -180 < x < 180:\n #do something\n\nThis includes -179 and 179 in the range, but not -180 and 180. \n",
"If I understand you correctly, you have some angles that you want to make sure that they are close to a target angle, given a specific tolerance defining the closeness. I think this is what you need:\nde... | [
1,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0003351254_math_python.txt |
Q:
Python client for MSSQL, with encrypted connections?
I am looking for a Python client for MSSQL, but one that supports encrypted connections to a remote MSSQL server.
Can someone recommend a technique for using Python to read from MSSQL, over an encrypted connection?
A:
Encryption is usually a feature of the MSS... | Python client for MSSQL, with encrypted connections? | I am looking for a Python client for MSSQL, but one that supports encrypted connections to a remote MSSQL server.
Can someone recommend a technique for using Python to read from MSSQL, over an encrypted connection?
| [
"Encryption is usually a feature of the MSSQL client library and/or the OS, not Python. So first work out what encrpytion mechanism you want to use, then see how you can use it from Python.\nMSSQL can be configured to support and even require encrypted connections from clients: \nhttp://msdn.microsoft.com/en-us/lib... | [
0
] | [] | [] | [
"encryption",
"python",
"sql",
"sql_server",
"tunnel"
] | stackoverflow_0003580591_encryption_python_sql_sql_server_tunnel.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.