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:
why does printing a returned tuple differ from printing members of the tuple by index?
I've got this function (see below) that accepts a few values and returns a tuple. If I print the values of the tuple using indexes into it (e.g. tuple[0], tuple[1], etc.) then the value printed is correct. But if I just print ... | why does printing a returned tuple differ from printing members of the tuple by index? | I've got this function (see below) that accepts a few values and returns a tuple. If I print the values of the tuple using indexes into it (e.g. tuple[0], tuple[1], etc.) then the value printed is correct. But if I just print the tuple or print the function, then I get some crazy values (sometimes).
Here's the code:
... | [
"So here's what's happening:\nWhen printing the values individually, you're printing them using a format string (%f), which prints numbers in floating point format (ie, up to about 7 significant digits). This part is correct.\nWhen printing the values as part of a tuple, the tuple itself is responsible for producin... | [
3,
2
] | [] | [] | [
"printing",
"python",
"tuples"
] | stackoverflow_0004989069_printing_python_tuples.txt |
Q:
Python: How do I install packages within my package or repository?
My program requires specific versions of several python packages. I don't want to have to require the user to specifically install the specific version, so I feel that the best solution is to simply install the package within the source repository,... | Python: How do I install packages within my package or repository? | My program requires specific versions of several python packages. I don't want to have to require the user to specifically install the specific version, so I feel that the best solution is to simply install the package within the source repository, and to distribute it along with my package.
What is the simplest way to... | [
"Go for virtualenv. Life will be much easier. MUCH easier. Basically, it allows you to create specific python environments as needed.\n",
"There are indeed two ways to get this done. \nI usually use buildout (see a post by Jacob from Django: http://jacobian.org/writing/django-apps-with-buildout/) - and have ev... | [
1,
0
] | [] | [] | [
"package",
"python",
"version_control"
] | stackoverflow_0004988625_package_python_version_control.txt |
Q:
Python polymorphism trouble
In python, I defined a class 'number'. Now I wish to define a function named 'number' too. (Just like 'int' or 'str' are classes as well as you can use them as functions ('int()' , 'str()') for type conversion). How can I do the same with (my class and function) 'number'?
[Would it be ... | Python polymorphism trouble | In python, I defined a class 'number'. Now I wish to define a function named 'number' too. (Just like 'int' or 'str' are classes as well as you can use them as functions ('int()' , 'str()') for type conversion). How can I do the same with (my class and function) 'number'?
[Would it be correct to call this as polymorph... | [
"class number(object):\n def __init__(self, value)\n self.val = value # or something like that\n\nn = number(2.3)\n\nint() and str() are not functions, they are type constructors. So you need to make your own constructor initializer.\n",
"what you want are callables. Look at this for more.\n"
] | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004989409_python.txt |
Q:
Django: strange IntegrityError upon saving a ModelFormset form
I am trying to save a couple ModelFormset forms, but am running into an IntegrityError. Here is the code:
billing_formset = BillingFormSet(request.POST,prefix='billing')
cc_formset = CCFormSet(request.POST,prefix='cc')
if billing_formset.... | Django: strange IntegrityError upon saving a ModelFormset form | I am trying to save a couple ModelFormset forms, but am running into an IntegrityError. Here is the code:
billing_formset = BillingFormSet(request.POST,prefix='billing')
cc_formset = CCFormSet(request.POST,prefix='cc')
if billing_formset.is_valid() and cc_formset.is_valid():
bp = UserBillingProfil... | [
"This means you are trying to save a model instance with user_billing_profile set to None, looks like you are calling \"billing_profile\" instead of \"user_billing_profile\".\nThe \"save\" method returns None every time commit=False isn't specified. you should instead call something like this:\nbilling_profile.save... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004989548_django_python.txt |
Q:
Parsing files (ics/ Vcalendar) using Python
I have a .ics file in the following format. What is the best way to parse it. I need to retrieve the Summary, Description, and Time for each of the entries. Thanks in advance for your help.
**January 31th 8pm : ,
2011 Cricket
match at chennai
A:
Look at icalendar or v... | Parsing files (ics/ Vcalendar) using Python | I have a .ics file in the following format. What is the best way to parse it. I need to retrieve the Summary, Description, and Time for each of the entries. Thanks in advance for your help.
**January 31th 8pm : ,
2011 Cricket
match at chennai
| [
"Look at icalendar or vobject.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004989397_python.txt |
Q:
Convert Point Database to Body Shape
I have a database containing body scan results in point format.
For example :
point1=(x,y,z)
point2=(x2,y2,z2)
...
I want to convert these points to body shape.
And I want to do some processing on this points for example calculate neck diameter and some related calculation.
... | Convert Point Database to Body Shape | I have a database containing body scan results in point format.
For example :
point1=(x,y,z)
point2=(x2,y2,z2)
...
I want to convert these points to body shape.
And I want to do some processing on this points for example calculate neck diameter and some related calculation.
Any suggestion ? (module , tutorial etc...... | [
"You need some basic textbook on computational geometry. See this question, for example: https://stackoverflow.com/questions/3308266/computational-geometry\n"
] | [
1
] | [] | [] | [
"3d",
"python"
] | stackoverflow_0004990035_3d_python.txt |
Q:
dictionary input of function in python
i have see some code like bellow:
params = {
'username': username,
'password': password,
'attended': attended,
'openid_identifier': openid_identifier,
'multistage': (stage and True) or None
}
ret = authmethod.login(request, userobj, **params)
login is imp... | dictionary input of function in python | i have see some code like bellow:
params = {
'username': username,
'password': password,
'attended': attended,
'openid_identifier': openid_identifier,
'multistage': (stage and True) or None
}
ret = authmethod.login(request, userobj, **params)
login is implemented like this
def login(self,request,... | [
"Basically this is what it means:\nWithout using **kw, you would need to list all the input parameters for login in it's signature. \nNow, you are calling login function and you know what variable names login's parameters are. So if you have a lot of parameters, it's difficult to always remember the order of the pa... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0004989850_python.txt |
Q:
virtualenv --no-site-packages is not working for me
virtualenv --no-site-packages v1
cd v1\Scripts
activate.bat
python -c "import django" # - no problem here
Why does it see the Django package??? It should give me an import error, right?
A:
Just unset PYTHONPATH environment variable. The idea of virtualenv i... | virtualenv --no-site-packages is not working for me | virtualenv --no-site-packages v1
cd v1\Scripts
activate.bat
python -c "import django" # - no problem here
Why does it see the Django package??? It should give me an import error, right?
| [
"Just unset PYTHONPATH environment variable. The idea of virtualenv is that you can create your own environment (fully isolated or extending the default one) so you don't have to mess with that.\nAs someone noticed there's already been a similar question on SO.\nRead it if you need a better explanation.\n",
"It s... | [
9,
2
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0004987230_python_virtualenv.txt |
Q:
Programming using pyclutter
I am new to clutter (and pyclutter).
I have been trying to use pyclutter. I haven't found any good tutorial for it so far. I mean nothing that really explains properly. I saw a couple of example programs but when I tried to use pyclutter I didn't get any good results.
The commands are... | Programming using pyclutter | I am new to clutter (and pyclutter).
I have been trying to use pyclutter. I haven't found any good tutorial for it so far. I mean nothing that really explains properly. I saw a couple of example programs but when I tried to use pyclutter I didn't get any good results.
The commands are available but their proper use i... | [
"What about this one: http://www.tuxradar.com/content/clutter-beginners-tutorial. It looks pretty decent.\n"
] | [
2
] | [] | [] | [
"cogl",
"opengl",
"python"
] | stackoverflow_0004989639_cogl_opengl_python.txt |
Q:
Python Beginner. Is this Python code as efficient as it could be?
This question/solution led me to another related question asked here - Help would be appreciated!
Updated current code below based on initial feedback
I am brand new to Python (this is my second program). I am currently using the Open Courseware fro... | Python Beginner. Is this Python code as efficient as it could be? | This question/solution led me to another related question asked here - Help would be appreciated!
Updated current code below based on initial feedback
I am brand new to Python (this is my second program). I am currently using the Open Courseware from MIT to get an intro to CS using Python Academic Earth videos and I am... | [
"This is unrelated to any possible efficiency problems*, but you should look into the decimal module if you're doing financial arithmetic. Otherwise, you'll end up with strange rounding and representation errors.\n\n*more precisely: It will reduce the efficiency but increase the correctness of your code.\n",
"pri... | [
4,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004990159_python.txt |
Q:
What encoding does the ScraperWiki datastore expect?
While writing a scraper on ScraperWiki, I was repeatedly getting this message when trying to save a UTF8-encoded string:
UnicodeDecodeError('utf8', ' the \xe2...', 49, 52, 'invalid data')
I eventually worked out, by trial and UnicodeDecodeError, that the Scrape... | What encoding does the ScraperWiki datastore expect? | While writing a scraper on ScraperWiki, I was repeatedly getting this message when trying to save a UTF8-encoded string:
UnicodeDecodeError('utf8', ' the \xe2...', 49, 52, 'invalid data')
I eventually worked out, by trial and UnicodeDecodeError, that the ScraperWiki datastore seems to expect Unicode.
So I'm now decod... | [
"The datastore requires either UTF-8 byte strings or Unicode strings.\nThis example show both ways of saving a pounds sterling currency sign in Python:\nhttp://scraperwiki.com/scrapers/unicode_test/\nThe same applies in other languages.\nYou can, for debugging purposes, print non-UTF-8/Unicode strings to the consol... | [
1
] | [] | [] | [
"python",
"scraperwiki",
"screen_scraping"
] | stackoverflow_0004984712_python_scraperwiki_screen_scraping.txt |
Q:
Django on Dreamhost: Display or log console output?
I have a Django install on Dreamhost, and I'm trying to figure out if there is anyway I can see the console output from my Django scripts. When I run it on the devserver (./manage.py runserver), the output from any print statements goes right to the console it wa... | Django on Dreamhost: Display or log console output? | I have a Django install on Dreamhost, and I'm trying to figure out if there is anyway I can see the console output from my Django scripts. When I run it on the devserver (./manage.py runserver), the output from any print statements goes right to the console it was run from. Is there a logfile or any way to see this inf... | [
"If you have the ADMIN mail configured you can receive the error logs by mail: \nhttp://docs.djangoproject.com/en/dev/howto/error-reporting/\nAlso take a look to django-sentry, it's a very good exception logging app: \nhttps://github.com/dcramer/django-sentry\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"dreamhost",
"passenger",
"python"
] | stackoverflow_0004778526_apache_django_dreamhost_passenger_python.txt |
Q:
Python argument interpreter
Is there a correct way to read the arguments to a python application?
Example:
python game.py -server 127.0.0.1 -nick TheKiller1337
Is there a correct way of interpreting these argument?
As it is now I have a while-loop with some ifs. But it is getting rather large. Should I do a gener... | Python argument interpreter | Is there a correct way to read the arguments to a python application?
Example:
python game.py -server 127.0.0.1 -nick TheKiller1337
Is there a correct way of interpreting these argument?
As it is now I have a while-loop with some ifs. But it is getting rather large. Should I do a general class for argument reading, or... | [
"Use argparse, optparse or getopt.\nAll three are in the standard library. \nI recommend argparse. It is the newest of the three, and is IMO the easiest to use. It was introduced in version 2.7. \nIf using an older Python version, I would recommend optparse (or get argparse for version 2.5 and 2.6 from pypi)\n",
... | [
8,
2,
1,
0
] | [] | [] | [
"arguments",
"input",
"python"
] | stackoverflow_0004990183_arguments_input_python.txt |
Q:
Django/Flask Implementation: Listen permanently to connection via HTTP or Socket. (in Background)
I'm currently planning a web-app that requires listening permanently to a open socket-connection and writing specifig things to a database.
To get known to flask (framework of my choice) and python in general I want t... | Django/Flask Implementation: Listen permanently to connection via HTTP or Socket. (in Background) | I'm currently planning a web-app that requires listening permanently to a open socket-connection and writing specifig things to a database.
To get known to flask (framework of my choice) and python in general I want to play around with twitter-streaming-api.
The essential problem is the same. How to implement a permane... | [
"If you want the system to be non-blocking then neither Flask or Django are going to natively provide the support you are looking for. You should probably check out Twisted since its the most mature python project for non-blocking IO: http://twistedmatrix.com/trac/ \nIt provides a solid set of API's for socket-base... | [
5,
2
] | [] | [] | [
"background",
"flask",
"observer_pattern",
"python",
"twitter"
] | stackoverflow_0004990899_background_flask_observer_pattern_python_twitter.txt |
Q:
Aggregate data using the ORM
Django/Python noob here!
Here are my models:
class Match(models.Model):
date = models.DateTimeField()
court = models.ForeignKey(Court)
players = models.ManyToManyField(User, through='Participant')
class Participant(models.Model):
match = models.ForeignKey(Match)
us... | Aggregate data using the ORM | Django/Python noob here!
Here are my models:
class Match(models.Model):
date = models.DateTimeField()
court = models.ForeignKey(Court)
players = models.ManyToManyField(User, through='Participant')
class Participant(models.Model):
match = models.ForeignKey(Match)
userid = models.ForeignKey(User)
... | [
"Your table showing 'data in the database' doesn't match your models, so I'm a bit confused.\nBut going by your models, there's no aggregation needed here at all, since you have a matches_won field directly on the Participant model (I assume that's the data you need to display). You can do it simply by iterating th... | [
1,
0
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0004982346_django_django_orm_python.txt |
Q:
Python / Django - Organizing Stylesheets and Scripts
I am looking for a simple way to organize stylesheets and scripts in Django. I am relatively new to the framework and language of python. I'm coming from a PHP background.
In the world of PHP / Zend there are functions that are implemented with the view/layout... | Python / Django - Organizing Stylesheets and Scripts | I am looking for a simple way to organize stylesheets and scripts in Django. I am relatively new to the framework and language of python. I'm coming from a PHP background.
In the world of PHP / Zend there are functions that are implemented with the view/layout object. By including a single line inside your head tag ... | [
"Look at the django.contrib.admin application. \nParallel the way the admin site works.\n\nCreate a media directory.\nCreate media/img, media/jss, media/css, media/whatever directories\nIn each of these, you'll have your app's specific stuff. media/img/app1, media/jss/app1 so that each of your Django apps can have... | [
5,
2,
0,
0
] | [] | [] | [
"django",
"django_templates",
"python",
"stylesheet"
] | stackoverflow_0004974544_django_django_templates_python_stylesheet.txt |
Q:
Modules between multiple versions of Python Linux
I have Python2.6.5 and Python2.4.4 on my linux machine.
At the moment, all the modules I have (wx, ply, pyserial, twisted, to name a few) are installed for the 2.6 version of python. If I try to import wx on Python2.4, I get the expected no module error.
The probl... | Modules between multiple versions of Python Linux | I have Python2.6.5 and Python2.4.4 on my linux machine.
At the moment, all the modules I have (wx, ply, pyserial, twisted, to name a few) are installed for the 2.6 version of python. If I try to import wx on Python2.4, I get the expected no module error.
The problem here, is that I have a lot of devices (Let's say ove... | [
"You can't share modules between different versions of Python. If you want to use wxPython from Python 2.4, you need to install it for Python 2.4. \nYou said you tried to install it with Python 2.4 as your \"primary\". I'm not sure what that means. You would install wxPython for Python 2.4 by running the installer ... | [
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0004991366_python.txt |
Q:
MySQLdb for Python - incompatible library version error?
I am, like many others, trying to get MySQLdb for Python to run on Mac Snow Leopard (10.6.x) and I've been able to install the 64-bit MySQL DMG as recommended by various blogs/forum posts, and I've been able to install the setuptools and MySQLDB itself by us... | MySQLdb for Python - incompatible library version error? | I am, like many others, trying to get MySQLdb for Python to run on Mac Snow Leopard (10.6.x) and I've been able to install the 64-bit MySQL DMG as recommended by various blogs/forum posts, and I've been able to install the setuptools and MySQLDB itself by using the
ARCHFLAGS='-arch 86_64' python2.7 setup.py clean
ARCHF... | [
"You built the module against MySQL 5.5.x, but only the client libraries for 5.1.x are available on the system. Either install updated libraries, or build against an older version.\n",
"Definitely make sure that Python and MySQL are for the same architecture. You have to consistently use either 32bit or 64bit ver... | [
0,
0
] | [] | [] | [
"django",
"installation",
"mysql",
"python"
] | stackoverflow_0004989786_django_installation_mysql_python.txt |
Q:
Where can I find free Ruby and Python logos for a commercial site?
I need a Ruby and Python logo, usable free of charge for a commercial site.
On Google Images, I have not been able to find such logos; All of them have no clearly specified license.
Where can I find such "free" logos?
A:
Python logos
Ruby logos
... | Where can I find free Ruby and Python logos for a commercial site? | I need a Ruby and Python logo, usable free of charge for a commercial site.
On Google Images, I have not been able to find such logos; All of them have no clearly specified license.
Where can I find such "free" logos?
| [
"Python logos\nRuby logos\nAs long as you follow the (fairly liberal) usage guidelines/license, there is no issue with you using them.\n",
"The rules regarding the Python trademark are described here: http://www.python.org/psf/trademarks/ .\nEspecially:\n\nUses that Never Require Approval\nAll trademarks are subj... | [
6,
3
] | [] | [] | [
"graphical_logo",
"open_source",
"python",
"ruby"
] | stackoverflow_0004991497_graphical_logo_open_source_python_ruby.txt |
Q:
timezone handling in python
I have an application in python wherein I've to convert between different time zones. I intend to use tz database from http://www.twinsun.com/tz/tz-link.htm as it is periodically updated.
Is there a compiler which reads tz database files directly so that updated files can be downloaded ... | timezone handling in python | I have an application in python wherein I've to convert between different time zones. I intend to use tz database from http://www.twinsun.com/tz/tz-link.htm as it is periodically updated.
Is there a compiler which reads tz database files directly so that updated files can be downloaded periodically and used without muc... | [
"If you want to use pytz anyway, then why not periodically update that package as it already contains the most recent timezone definitions. You could accomplish this with regular calls to pip install --upgrade pytz, for example.\nOf course this will only update the timezones once a new pytz release is out.\n",
"p... | [
3,
3
] | [] | [] | [
"python",
"timezone"
] | stackoverflow_0004990373_python_timezone.txt |
Q:
Python and Tkinter: Function madness
I'm trying to write myself a program that calculates a function taken from a Tk.Entry().
The problem is, when I try to run my display() function
(it runs Tkinter, sets up the window, and calls root.Mainloop()),
I get parse errors coming from eval() from a function that is suppo... | Python and Tkinter: Function madness |
I'm trying to write myself a program that calculates a function taken from a Tk.Entry().
The problem is, when I try to run my display() function
(it runs Tkinter, sets up the window, and calls root.Mainloop()),
I get parse errors coming from eval() from a function that is supposed to be called only if the user inputs ... | [
"You haven't shown us the code that causes the error (the value of _n) so we can only guess. A couple words of advice:\n\nthe error message is telling you the problem: unexpected eof. That means there's a missing closing quote or brace or something like that. The parser got to the end of the \"file\" (the string be... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004984285_python_tkinter.txt |
Q:
Lexing and Parsing Utilities
I'm looking for lexical analysis and parser-generating utilities that are not Flex or Bison. Requirements:
Parser is specified using a context-free LL(*) or GLR grammar. I would also consider PEGs.
Integrates tightly with a programming language that could be used for both scripting an... | Lexing and Parsing Utilities | I'm looking for lexical analysis and parser-generating utilities that are not Flex or Bison. Requirements:
Parser is specified using a context-free LL(*) or GLR grammar. I would also consider PEGs.
Integrates tightly with a programming language that could be used for both scripting and application development. Languag... | [
"There is a list of modern Packrat parsers here. \n",
"NL text tends have to lots of ambiguity. If you want to parse natural langauge, I don't think any of the classic compiler-type parser generators (LALR, LL [including ANTLR]) will help you much, and compiler type parser generators typically don't handle this ... | [
2,
1,
0
] | [] | [] | [
"guile",
"lexical_analysis",
"parsing",
"python",
"ruby"
] | stackoverflow_0004982455_guile_lexical_analysis_parsing_python_ruby.txt |
Q:
Why does refs increase 2 for every new object in Python?
It is a little weird to me that the refs number in the interactive environment increases 2 after a new object is defined. I created only one object, isn't it?
>>> v
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'v' ... | Why does refs increase 2 for every new object in Python? | It is a little weird to me that the refs number in the interactive environment increases 2 after a new object is defined. I created only one object, isn't it?
>>> v
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'v' is not defined
[41830 refs]
>>> v = "v"
[41832 refs]
| [
"Your assignment worked by creating an entry in the globals() dictionary that has v as a key and \"v\" as a value. That's two references (one for the key and one for the value) although in this case they probably both refer to the same string \"v\".\n"
] | [
8
] | [] | [] | [
"cpython",
"python",
"python_internals"
] | stackoverflow_0004991744_cpython_python_python_internals.txt |
Q:
python, numpy boolean array: negation in where statement
with:
import numpy as np
array = get_array()
I need to do the following thing:
for i in range(len(array)):
if random.uniform(0, 1) < prob:
array[i] = not array[i]
with array being a numpy.array.
I wish I could do something similar to:
array = n... | python, numpy boolean array: negation in where statement | with:
import numpy as np
array = get_array()
I need to do the following thing:
for i in range(len(array)):
if random.uniform(0, 1) < prob:
array[i] = not array[i]
with array being a numpy.array.
I wish I could do something similar to:
array = np.where(np.random.rand(len(array)) < prob, not array, array)
... | [
"I suggest using\narray ^= numpy.random.rand(len(array)) < prob\n\nThis is probably the most efficient way of getting the desired result. It will modify the array in place, using \"xor\" to invert the entries which the random condition evaluates to True for.\n\nWhy can I take the value of array but not its negatio... | [
33,
4
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004992040_numpy_python.txt |
Q:
How to change the label of a MenuItem in a PyGTK application?
I'm writing a small Application Indicator for Ubuntu in Python. I need to change the text of an insensitive (disabled) gtk.MenuItem. I know a living example for this function, the topmost item in the built-in Bluetooth Indicator.
A:
The gtk.MenuItem i... | How to change the label of a MenuItem in a PyGTK application? | I'm writing a small Application Indicator for Ubuntu in Python. I need to change the text of an insensitive (disabled) gtk.MenuItem. I know a living example for this function, the topmost item in the built-in Bluetooth Indicator.
| [
"The gtk.MenuItem is a container that usually has the actual label as its child widget, unless there is something more complicated like an image involved; if the child is just a simple label, you should be able to do\nmenuitem.get_child().set_text('New text')\n\n"
] | [
7
] | [] | [] | [
"gtk",
"indicator",
"pygtk",
"python",
"ubuntu"
] | stackoverflow_0004981004_gtk_indicator_pygtk_python_ubuntu.txt |
Q:
How to read the date/time field from the csv file and plot a graph accordingly in python
Im importing records from a CSV file using python csv module .
The date/Time field expects the date to be in a specific format, but
different spreadsheet programs default to different types of formats
and I dont want the user ... | How to read the date/time field from the csv file and plot a graph accordingly in python | Im importing records from a CSV file using python csv module .
The date/Time field expects the date to be in a specific format, but
different spreadsheet programs default to different types of formats
and I dont want the user to have to change their down format.I want to
find a way to either detect the format the strin... | [
"dateutil can parse date strings in a variety of formats, without you having to specify in advance what format the date string is in:\nIn [8]: import dateutil.parser as parser\n\nIn [9]: parser.parse('Jan 1')\nOut[9]: datetime.datetime(2011, 1, 1, 0, 0)\n\nIn [10]: parser.parse('1 Jan')\nOut[10]: datetime.datetime(... | [
8
] | [] | [] | [
"csv",
"matplotlib",
"python"
] | stackoverflow_0004992697_csv_matplotlib_python.txt |
Q:
PyQt --> connect() --> TypeError: arguments did not match any overloaded call
I have problems with connect() from PyQt4. For example here is .UI converted via pyuic4.
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(ob... | PyQt --> connect() --> TypeError: arguments did not match any overloaded call | I have problems with connect() from PyQt4. For example here is .UI converted via pyuic4.
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialo... | [
"The error is on the double-commented line:\n## self.connect(self.btnClearText, QtCore.SIGNAL('clicked()'), self.label.setText('ABC'))\n\nIt looks like you want the text of the label set to ABC whenever the button is clicked. However, the above line of code will not achieve this. The problem is that the th... | [
10
] | [] | [] | [
"connect",
"pyqt",
"python"
] | stackoverflow_0004992968_connect_pyqt_python.txt |
Q:
Passing custom Python objects to nosetests
I am attempting to re-organize our test libraries for automation and nose seems really promising. My question is, what is the best strategy for passing Python objects into nose tests?
Our tests are organized in a testlib with a bunch of modules that exercise different ty... | Passing custom Python objects to nosetests | I am attempting to re-organize our test libraries for automation and nose seems really promising. My question is, what is the best strategy for passing Python objects into nose tests?
Our tests are organized in a testlib with a bunch of modules that exercise different types of request operations. Something like this:... | [
"Could you use a factory create the connections, then have the functions test_something1() (taking no arguments) use the factory to get a connection?\n",
"As far as I can tell, there is no easy way to simply pass custom objects to Nose.\nHowever, as Matt pointed out there are some viable workarounds to achieve si... | [
0,
0
] | [] | [] | [
"automation",
"nose",
"nosetests",
"python",
"testing"
] | stackoverflow_0004941272_automation_nose_nosetests_python_testing.txt |
Q:
Is C++ SDL and (Python PyGame) used by people other than hobbyists?
As a hobbyists who has a little experience making 2D games using PyGame, and has ventured into using C++ with the SDL library (in Visual Studio), I'm curious. Is the library used professionally?
A:
http://en.wikipedia.org/wiki/List_of_games_usi... | Is C++ SDL and (Python PyGame) used by people other than hobbyists? | As a hobbyists who has a little experience making 2D games using PyGame, and has ventured into using C++ with the SDL library (in Visual Studio), I'm curious. Is the library used professionally?
| [
"http://en.wikipedia.org/wiki/List_of_games_using_SDL\nDoom3 and Unreal Tournament are on that list, so I'd say it is used professionally\n",
"SDL is used professionally and some great games were made with it. Many times it is used as a cross-platform window creation system to initialize openGL (as I assume it is... | [
3,
3
] | [] | [] | [
"c++",
"pygame",
"python",
"sdl"
] | stackoverflow_0004993101_c++_pygame_python_sdl.txt |
Q:
plot a daily profile with python
I want to make a daily profile plot: hour vs concentrations. I'm using matplotlib and datetime module.
When I write:
import datetime
from pylab import *
b = [datetime.time(12,0), datetime.time(13,0)]
c = [4,5]
plot(b,c)
show()
... it doesn't work.
I have to use datetime objects in... | plot a daily profile with python | I want to make a daily profile plot: hour vs concentrations. I'm using matplotlib and datetime module.
When I write:
import datetime
from pylab import *
b = [datetime.time(12,0), datetime.time(13,0)]
c = [4,5]
plot(b,c)
show()
... it doesn't work.
I have to use datetime objects instead of time objects to be able to ma... | [
"Have a look at the matplotlib documentation here:\nhttp://matplotlib.sourceforge.net/api/dates_api.html\nThe issue is that matplotlib only knows how to convert the datetime object to a float and it doesn't look there is the same support for datetime.time\nEdit:\nOne possible solution is to just get a default date ... | [
3,
0
] | [] | [] | [
"datetime",
"matplotlib",
"plot",
"python",
"time"
] | stackoverflow_0004993722_datetime_matplotlib_plot_python_time.txt |
Q:
PIL Converting an image's hue, then saving out in Python
I'm loading and saving out images with PIL just fine but I can't seem to change the "overall" hue of a given image ~ google and here revealed an answer, sort of, with the numpy module, but thats not an option for me
It should be quite simple, given a gray im... | PIL Converting an image's hue, then saving out in Python | I'm loading and saving out images with PIL just fine but I can't seem to change the "overall" hue of a given image ~ google and here revealed an answer, sort of, with the numpy module, but thats not an option for me
It should be quite simple, given a gray image with alpha, I'd like to make it's hue red
| [
"I think you want a mono-hue image. Is this true?\nIt's not clear what you want done with the existing bands (alpha and greyscale/level). Do you want alpha to remain alpha and the greyscale to become red saturation? Do you want the alpha to become your red saturation? Do you want greyscale to be the image light... | [
6
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0004993062_python_python_imaging_library.txt |
Q:
How can I iterate over and modify the values in a dict?
records = {'foo':foo, 'bar':bar, 'baz':baz}
I want to change the values to 0 if it is None. How can I do this?
eg:
records = {'foo':None, 'bar':None, 'baz':1}
I want to change foo and bar to 0.
Final dict:
records = {'foo':0, 'bar':0, 'baz':1}
A:
for k i... | How can I iterate over and modify the values in a dict? | records = {'foo':foo, 'bar':bar, 'baz':baz}
I want to change the values to 0 if it is None. How can I do this?
eg:
records = {'foo':None, 'bar':None, 'baz':1}
I want to change foo and bar to 0.
Final dict:
records = {'foo':0, 'bar':0, 'baz':1}
| [
"for k in records:\n if records[k] is None:\n records[k] = 0\n\n",
"Another way\nrecords.update((k, 0) for k,v in records.iteritems() if v is None)\n\nExample\n>>> records\n{'bar': None, 'baz': 1, 'foo': None}\n>>> records.update((k, 0) for k,v in records.iteritems() if v is None)\n>>> records\n{'bar': ... | [
20,
19,
13,
9,
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004992739_dictionary_python.txt |
Q:
How do you get the list data from a wxpyton gui click event?
I have a list ctrl box and I populate it with data.
self.listView1.Append([sFilename,sTitle,sArtist,sAlbum,sDestDir])
I created an event that triggers when a user clicks on a specific item in the list
def OnListView1ListItemSelected(self, event):
... | How do you get the list data from a wxpyton gui click event? | I have a list ctrl box and I populate it with data.
self.listView1.Append([sFilename,sTitle,sArtist,sAlbum,sDestDir])
I created an event that triggers when a user clicks on a specific item in the list
def OnListView1ListItemSelected(self, event):
print "onListViewSelect"
This works, but what I am stuck on is ho... | [
"Using wxPython 2.8.10, this is one way to drop the text from all columns in the selected row into a list. You're getting the object, selected index, number of columns, and then grabbing the text from each column:\ndef onListView1ListItemSelected(self, event):\n obj = event.GetEventObject()\n index = e... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004992963_python_wxpython.txt |
Q:
Changing the color of the offset in scientific notation in matplotlib
I am plotting some curves using twin-axis and also scientific notation. I have set some color to the label but the setting don't seem to affect the power indicator of the scientific notation of its axis. Is there any trick?
Example
Here is my co... | Changing the color of the offset in scientific notation in matplotlib | I am plotting some curves using twin-axis and also scientific notation. I have set some color to the label but the setting don't seem to affect the power indicator of the scientific notation of its axis. Is there any trick?
Example
Here is my code:
fig = pylab.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
# Pl... | [
"It's probably just an oversight that tick_params doesn't already do this, but you can simply set it manually.\nFor example, just add these two lines to your example code:\nax1.yaxis.get_offset_text().set_color(plot_ax1.get_color())\nax2.yaxis.get_offset_text().set_color(plot_ax2.get_color())\n\nAs a more complete ... | [
10
] | [] | [] | [
"colors",
"matplotlib",
"python"
] | stackoverflow_0004991178_colors_matplotlib_python.txt |
Q:
Ordered options in Python's optparse
First of all, I know optparse is deprecated since version 2.7, but I only have Python 2.3 available in the machine I'm working.
The question is how to know the order in which the options were given in the command line, for instance:
python example.py -f foo -b bar
will execut... | Ordered options in Python's optparse | First of all, I know optparse is deprecated since version 2.7, but I only have Python 2.3 available in the machine I'm working.
The question is how to know the order in which the options were given in the command line, for instance:
python example.py -f foo -b bar
will execute first the option f and then the option b... | [
"It's against convention to have option flags that trigger different behaviors depending on the order. But if you really want check for the order, you can just look in sys.argv\n#assuming both -f and -b are given in cmdline and you need to check for order\nindex_f = sys.argv.find(\"-f\")\nindex_b = sys.argv.find(\"... | [
4
] | [] | [] | [
"command_line_arguments",
"optional_arguments",
"python"
] | stackoverflow_0004994634_command_line_arguments_optional_arguments_python.txt |
Q:
Generate a list of file names based on month and year arithmetic
How can I list the numbers 01 to 12 (one for each of the 12 months) in such a way so that the current month always comes last where the oldest one is first. In other words, if the number is grater than the current month, it's from the previous year.... | Generate a list of file names based on month and year arithmetic | How can I list the numbers 01 to 12 (one for each of the 12 months) in such a way so that the current month always comes last where the oldest one is first. In other words, if the number is grater than the current month, it's from the previous year.
e.g. 02 is Feb, 2011 (the current month right now), 03 is March, 2010... | [
"Third Update:\nimport os, sys\nfrom time import strftime\nfrom calendar import month_abbr\n\nthismonth = int(strftime(\"%m\"))\nsortedmonths = [\"%02d\" % (m % 12 + 1) for m in range(thismonth, thismonth + 12)]\ninFiles = [m for m in sortedmonths if m in os.listdir('.')]\n\nfor inFile in inFiles:\n readFile = o... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004988790_python.txt |
Q:
Why would the variable name being assigned _to_ affect the lookup of the value?
In python, the following works fine:
def test_foo():
class Foo(object):
pass
class Fam(object):
bar = Foo
test_foo()
However the following fails with NameError: name 'Foo' is not defined:
def test_foo():
c... | Why would the variable name being assigned _to_ affect the lookup of the value? | In python, the following works fine:
def test_foo():
class Foo(object):
pass
class Fam(object):
bar = Foo
test_foo()
However the following fails with NameError: name 'Foo' is not defined:
def test_foo():
class Foo(object):
pass
class Fam(object):
Foo = Foo
test_foo()
... | [
"The mere fact that you assign to the name Foo inside the class definition makes the name Foo a local name in that scope (i.e. the scope of the class). The local names are determined statically, during parsing and compiling to byte code. When the execution reaches the statement\nFoo = Foo\n\nPython first evaluate... | [
6
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0004994890_namespaces_python.txt |
Q:
Encoding for Multilingual .py Files
I am writing a .py file that contains strings from multiple charactersets, including English, Spanish, and Russian. For example, I have something like:
string_en = "The quick brown fox jumped over the lazy dog."
string_es = "El veloz murciélago hindú comía feliz cardillo y kiw... | Encoding for Multilingual .py Files | I am writing a .py file that contains strings from multiple charactersets, including English, Spanish, and Russian. For example, I have something like:
string_en = "The quick brown fox jumped over the lazy dog."
string_es = "El veloz murciélago hindú comía feliz cardillo y kiwi."
string_ru = "В чащах юга жил бы цитру... | [
"There are two aspects to proper encoding of strings in your use case:\n\nFor Python to understand that you are using UTF-8 encoding, you must include in the first or second line of your code, a line that looks like # coding=utf-8. See PEP 0263 for details.\nYour editor also must use UTF-8. This requires to configu... | [
13,
1
] | [] | [] | [
"encoding",
"nlp",
"python",
"unicode"
] | stackoverflow_0004994899_encoding_nlp_python_unicode.txt |
Q:
Python: Appending to a list in a dictionary
SO,
Having a case of the Monday's and none of my references are helping me out.
I have a file formatted like this:
x1 y1 z1
x1 y2 z2
x2 y3 z3
I would like to make a dictionary formatted like this: {x1: [[y1, z1], [y2,z2]], x2: [y3,z3]} but I'm getting ... | Python: Appending to a list in a dictionary | SO,
Having a case of the Monday's and none of my references are helping me out.
I have a file formatted like this:
x1 y1 z1
x1 y2 z2
x2 y3 z3
I would like to make a dictionary formatted like this: {x1: [[y1, z1], [y2,z2]], x2: [y3,z3]} but I'm getting stuck on an efficient way to do this. Help?
| [
"I'm going to say you start with a string\ndata_str = \"\"\"x1 y1 z1\n x1 y2 z2\n x2 y3 z3\"\"\"\n\nThen you'll have\ndata_list = [d.split() for d in data_str.splitlines()] # [['x1', 'y1', 'z1'], ['x1', 'y2', 'z2'], ['x2', 'y3', 'z3']]\n\nThen create a defaultdict\nfrom c... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004995026_python.txt |
Q:
How to get the last N lines of a subprocess' stderr stream output?
I am a Python newbie writing a Python (2.7) script that needs to exec a number of external applications, one of which writes a lot of output to its stderr stream. What I am trying to figure out is a concise and succinct way (in Python) to get the l... | How to get the last N lines of a subprocess' stderr stream output? | I am a Python newbie writing a Python (2.7) script that needs to exec a number of external applications, one of which writes a lot of output to its stderr stream. What I am trying to figure out is a concise and succinct way (in Python) to get the last N lines from that subprocess' stderr output stream.
Currently, I am ... | [
"N = 3 # for 3 lines of output\np = subprocess.Popen(['/path/to/external-app.sh'], \n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = p.communicate()\n\nif p.returncode != 0:\n print (\"ERROR: External app did not complete successfully \"\n \"(error code is %s)\" % p.returncode)\n ... | [
3,
1
] | [] | [] | [
"python",
"scripting",
"subprocess"
] | stackoverflow_0004995095_python_scripting_subprocess.txt |
Q:
Django question: Want to display only one number
Hello I have a set of numbers in Django Defined as:
def order_list_service(request, type_id = 1):
orders = models.Order.objects.filter(is_hot = False, is_storage = False, orderservicelist__service__type = type_id).order_by('pk').distinct()
request.session['ord... | Django question: Want to display only one number | Hello I have a set of numbers in Django Defined as:
def order_list_service(request, type_id = 1):
orders = models.Order.objects.filter(is_hot = False, is_storage = False, orderservicelist__service__type = type_id).order_by('pk').distinct()
request.session['orders']= orders
def service_order(request, client_id = ... | [
"Either limit the order to one object in the view, or in the template. \nIn the view: \n order = orders[0], orders.get(id=3), etc.\n return render_to_response('service_step1.html', {'orders':order }, context_instance = RequestContext(request))\n\nIn the template:\n {{ orders.0.id }}\n {{ orders.5.id }}\n\nB... | [
0
] | [] | [] | [
"django",
"html",
"python",
"views"
] | stackoverflow_0004995025_django_html_python_views.txt |
Q:
Recursion, calling a function using input
I'm working on some recursion stuff. I've created some functions in the vein of the twelve days of xmas, but I can't think of a way to call a function using input. I'll give an example:
def day1():
print 'A Partridge in a Pear Tree'
def day2():
print '2 Turtle Dove... | Recursion, calling a function using input | I'm working on some recursion stuff. I've created some functions in the vein of the twelve days of xmas, but I can't think of a way to call a function using input. I'll give an example:
def day1():
print 'A Partridge in a Pear Tree'
def day2():
print '2 Turtle Doves'
day1()
def day3():
print '3 French H... | [
"Well, you could do globals()['day%d' % n](), but that's even more horrible and messy.\nJust put the functions into a collection. A list, for instance, or a dict if you need sparse or non-integer keys. day_funcs = [day0, day1, day, day3] (day0 should propably be a placeholder, a non-callable works if you check the ... | [
2,
2,
0
] | [] | [] | [
"function",
"input",
"python",
"recursion"
] | stackoverflow_0004995287_function_input_python_recursion.txt |
Q:
C++ Python embedding: Run on machine with no Python?
I'm trying to make a small game that supports Python scripting. I've no problems with using the Python C-API, but I don't know how to ensure that the game will run on a computer with no Python installed.
I know I need pythonXY.dll -- what else is there? When I t... | C++ Python embedding: Run on machine with no Python? | I'm trying to make a small game that supports Python scripting. I've no problems with using the Python C-API, but I don't know how to ensure that the game will run on a computer with no Python installed.
I know I need pythonXY.dll -- what else is there? When I try to run the program it tells me it cannot find encodings... | [
"You need the encodings/__init__.py file, otherwise encodings is a folder and not a python package.\nChances are that you'll need a lot of stuff from within the python standard library. To make everything just work you'll need to include the entire standard library along with your program.\nYou can make this a bit ... | [
0
] | [] | [] | [
"embed",
"python",
"python_c_api"
] | stackoverflow_0004995336_embed_python_python_c_api.txt |
Q:
processing an image using CUDA implementation, python (pycuda) or C++?
I am in a project to process an image using CUDA. The project is simply an addition or subtraction of the image.
May I ask your professional opinion, which is best and what would be the advantages and disadvantages of those two?
I appreciate ev... | processing an image using CUDA implementation, python (pycuda) or C++? | I am in a project to process an image using CUDA. The project is simply an addition or subtraction of the image.
May I ask your professional opinion, which is best and what would be the advantages and disadvantages of those two?
I appreciate everyone's opinions and/or suggestions since this project is very important to... | [
"General answer: It doesn't matter. Use the language you're more comfortable with. \nKeep in mind, however, that pycuda is only a wrapper around the CUDA C interface, so it may not always be up-to-date, also it adds another potential source of bugs, … \nPython is great at rapid prototyping, so I'd personally go for... | [
6,
3,
2,
0
] | [] | [] | [
"c++",
"cuda",
"pycuda",
"python"
] | stackoverflow_0004970580_c++_cuda_pycuda_python.txt |
Q:
C# analog of multi-variable iteration in Python?
In Python one can iterate over multiple variables simultaneously like this:
my_list = [[1, 2, 3], [4, 5, 6]]
for a, b, c in my_list:
pass
Is there a C# analog closer than this?
List<List<int>> myList = new List<List<int>> {
new List<int> { 1, 2, 3 },
n... | C# analog of multi-variable iteration in Python? | In Python one can iterate over multiple variables simultaneously like this:
my_list = [[1, 2, 3], [4, 5, 6]]
for a, b, c in my_list:
pass
Is there a C# analog closer than this?
List<List<int>> myList = new List<List<int>> {
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 }
};
foreach (List<int> subite... | [
"Not too different from what you have but how about this ?\nforeach (var subitem in myList.Select(si => new {a = si[0], b = si[1], c = si[2]})\n{\n int a = subitem.a;\n int b = subitem.b;\n int c = subitem.c;\n continue;\n}\n\n",
"You can try something l... | [
2,
1,
0,
0
] | [] | [] | [
"c#",
"iteration",
"multidimensional_array",
"python"
] | stackoverflow_0004995667_c#_iteration_multidimensional_array_python.txt |
Q:
Python split string on regex
I'm trying to split a string using a regular expression.
Friday 1Friday 11 JAN 11
The output I want to achieve is
['Friday 1', 'Friday 11', ' JAN 11']
My snippet so far is not producing the desired results:
>>> import re
>>> p = re.compile(r'(Sunday|Monday|Tuesday|Wednesday|Thursd... | Python split string on regex | I'm trying to split a string using a regular expression.
Friday 1Friday 11 JAN 11
The output I want to achieve is
['Friday 1', 'Friday 11', ' JAN 11']
My snippet so far is not producing the desired results:
>>> import re
>>> p = re.compile(r'(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)\s*\d{1,2}')
>>... | [
"The problem is the capturing parentheses. This syntax: (?:...) makes them non-capturing. Try:\np = re.compile(r'((?:Friday|Saturday)\\s*\\d{1,2})')\n\n",
"You can also use 're.findall' function. \n\\>>> val \n'Friday 1Friday 11 JAN 11 ' \n\\>>> pat = re.compile(r'(\\w+\\s*\\d*)') \n\\>>> m=re.findall(pat,val)... | [
23,
6,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004995892_python_regex.txt |
Q:
Is it possible to have an admin inline without original data being shown?
In the django admin I have a model with an inline. I would like to be able to only show "add new" lines for the inline, and not show any preexisting, original data in the table belonging to the inline. Is this possible? I have tried every co... | Is it possible to have an admin inline without original data being shown? | In the django admin I have a model with an inline. I would like to be able to only show "add new" lines for the inline, and not show any preexisting, original data in the table belonging to the inline. Is this possible? I have tried every combination of max_num and extra, and it always shows existing table data.
Thanks... | [
"I think this is not possible with a simple switch in the InlineAdmin\nsubclass. But I can think of a small \"hack\" that achieves the same:\nUse the template attribute on your InlineAdmin to specify a custom template\nto render your inlines. Now copy the original template you want to use into\nyour custom template... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002094140_django_python.txt |
Q:
algorithm for testing mutliple substrings in multiple strings
I have several million strings, X, each with less than 20 or so words. I also have a list of several thousand candidate substrings C. for each x in X, I want to see if there are any strings in C that are contained in x. Right now I am using a naive d... | algorithm for testing mutliple substrings in multiple strings | I have several million strings, X, each with less than 20 or so words. I also have a list of several thousand candidate substrings C. for each x in X, I want to see if there are any strings in C that are contained in x. Right now I am using a naive double for loop, but it's been a while and it hasn't finished yet...... | [
"Encode one of your sets of strings as a trie (I recommend the bigger set). Lookup time should be faster than an imperfect hash and you will save some memory too.\n",
"It's gonna be a long while. You have to check every one of those several million strings against every one of those several thousand candidate s... | [
4,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"python",
"string",
"substring"
] | stackoverflow_0004994363_algorithm_python_string_substring.txt |
Q:
Pointers in Python? ` x.pointerDest = y.pointerDest`?
I am breaking my old question to parts because it is very messy beast here. This question is related to this answer and this answer. I try to understand pointers, not sure even whether they exist in Python.
# Won't change x with y=4
>>> x = 0; y = x; y = 4; x
0... | Pointers in Python? ` x.pointerDest = y.pointerDest`? | I am breaking my old question to parts because it is very messy beast here. This question is related to this answer and this answer. I try to understand pointers, not sure even whether they exist in Python.
# Won't change x with y=4
>>> x = 0; y = x; y = 4; x
0
# Won't change y
>>> x = 0; y = x; x = 2; y
0
#so how ca... | [
"Scalar objects in Python are immutable. If you use a non-scalar object, such as a list, you can do this:\n>>> x = [0]\n>>> y = x\n>>> y[0] = 4\n>>> y\n[4]\n>>> x\n[4]\n>>> x is y\nTrue\n\nPython does not have the concept of a \"pointer\" to a simple scalar value.\n",
"Don't confuse pointers to references. They ... | [
6,
2,
1
] | [] | [] | [
"pointers",
"python"
] | stackoverflow_0004996174_pointers_python.txt |
Q:
Idiomatic Python for generating a new object from within a class
I have a method on one of my objects that returns a new instance of that same class. I'm trying to figure out the most idiomatic way to write this method such that it generates a new object of the same type without duplicating code.
Since this method... | Idiomatic Python for generating a new object from within a class | I have a method on one of my objects that returns a new instance of that same class. I'm trying to figure out the most idiomatic way to write this method such that it generates a new object of the same type without duplicating code.
Since this method uses data from the instance, my first pass is:
class Foo(object):
... | [
"If you want to make it more flexible for subclassing, you can simply use the self.__class__ special attribute:\nclass Foo(object):\n def __init__(self, data):\n self.data = data\n\n def get_new(self):\n data = # Do interesting things\n return self.__class__(data)\n\nNote that using the @... | [
23,
3
] | [] | [] | [
"python"
] | stackoverflow_0004996565_python.txt |
Q:
Is the PyThreadState* of the main python thread expected to be NULL?
I have a python program that calls into a c++ library, which wishes to release all the python locks so that other python threads can run.
Using PyEval_SaveThread and PyEval_ReleaseThread I get errors that the thread state is NULL:
Fatal Python er... | Is the PyThreadState* of the main python thread expected to be NULL? | I have a python program that calls into a c++ library, which wishes to release all the python locks so that other python threads can run.
Using PyEval_SaveThread and PyEval_ReleaseThread I get errors that the thread state is NULL:
Fatal Python error: PyEval_SaveThread: NULL tstate
However, the lower-level function see... | [
"Answer: no, it is never meant to be NULL (if it is, it's a fatal error). Turned out this was because I was linking against two different versions of python, one via boost_python, and the other directly.\nTop Tip:\nuse ldd or otool -L to check your library dependencies when funny stuff happens ;)\n"
] | [
3
] | [] | [] | [
"c",
"gil",
"multithreading",
"python"
] | stackoverflow_0004985933_c_gil_multithreading_python.txt |
Q:
CherryPy 60x as slow in benchmark with 8 requesting threads compared to 7
I'm curious why when benchmarking Python web server CherryPy using ab, with -c 7 (7 concurrent threads) it can server 1500 requests/s (about what I expect), but when I change to -c 8 it drops way down to 25 requests/s. I'm running CherryPy w... | CherryPy 60x as slow in benchmark with 8 requesting threads compared to 7 | I'm curious why when benchmarking Python web server CherryPy using ab, with -c 7 (7 concurrent threads) it can server 1500 requests/s (about what I expect), but when I change to -c 8 it drops way down to 25 requests/s. I'm running CherryPy with numthreads=10 (but it doesn't make a different if I use numthreads=8 or 20)... | [
"On my linux box, it's due to the retransmission of a TCP packet from ab, although I'm not exactly sure why:\nNo. Time Source Destination Protocol Info Delta\n 10682 21.218156 127.0.0.1 127.0.0.1 ... | [
3
] | [] | [] | [
"apachebench",
"cherrypy",
"gil",
"multithreading",
"python"
] | stackoverflow_0004993526_apachebench_cherrypy_gil_multithreading_python.txt |
Q:
Access Python Development Server from External IP
I am learning Django and have deployed apps on my iMac locally. I want to show the apps from external IPs over the internet. I did add an exception to the firewall for port 8000, and ran the python dev server over 8000. Able to access at localhost, but not over the... | Access Python Development Server from External IP | I am learning Django and have deployed apps on my iMac locally. I want to show the apps from external IPs over the internet. I did add an exception to the firewall for port 8000, and ran the python dev server over 8000. Able to access at localhost, but not over the net. However, when I tried XAMPP (Apache) over the sam... | [
"python manage.py runserver 0.0.0.0:8000\n\nThis will make it listen to any address. Quite useful when you want to develop over ssh from a machine that you cannot install stuff on.\n"
] | [
62
] | [] | [] | [
"django",
"networking",
"python",
"xampp"
] | stackoverflow_0004997293_django_networking_python_xampp.txt |
Q:
Is there no way to serve a static directory and its children i Cherrypy?
Using Cherrypy version 3.0.2
Given a file-structure like this:
static-dir
2011
2010
2009
...
I use the configuration: '/static': {'tools.staticdir.on': True, 'tools.staticdir.dir': 'static-dir'}
This works fine fore getting /static/a... | Is there no way to serve a static directory and its children i Cherrypy? | Using Cherrypy version 3.0.2
Given a file-structure like this:
static-dir
2011
2010
2009
...
I use the configuration: '/static': {'tools.staticdir.on': True, 'tools.staticdir.dir': 'static-dir'}
This works fine fore getting /static/anyfile
But if I try /static/2009/anyfile I get an error. I can add an entry in... | [
"Not sure in CherryPY, but why not configure your front end webserver to serve static files? You really don't want that traffic hitting your framework.\n",
"You shouldn't have to enter multiple entries; it should descend as far down as you need to. What error are you getting? 404? If you're using Cherrypy 3.2, tr... | [
1,
1
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0004994493_cherrypy_python.txt |
Q:
Solution to allow Python script to open any file in a directory, instead of hardcoded name
I have a Python script which opens a file and processes the contents ultimately creating a separate output file that I need to provide to other individuals. The problem is that this script will need to be run every day, and... | Solution to allow Python script to open any file in a directory, instead of hardcoded name | I have a Python script which opens a file and processes the contents ultimately creating a separate output file that I need to provide to other individuals. The problem is that this script will need to be run every day, and the file I open with the script will not have the same filename every day. So I know I can't h... | [
"Since you tagged wxpython, it can be something like this (untested) fragment:\nfrom wxPython.wx import *\n...\napplication = wxPySimpleApp()\n...\ndialog = wxFileDialog ( None, style = wxOPEN )\nif dialog.ShowModal() == wxID_OK:\n print 'Selected:', dialog.GetPath()\n bs_ref = csv.reader(open(dialog.GetPath(),... | [
4,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004997351_python_wxpython.txt |
Q:
calling cgi/py within PHP with parameters
I am trying to execute a cgi/python script from within php, and at the same time pass the cgi/python script a paramter.
in my php I have
<? echo exec('/var/www/cgi-bin/test.cgi ' + $_POST["var"]); ?>
However it doesn't work, and in the apache log it says 'sh:0 not Found'
... | calling cgi/py within PHP with parameters | I am trying to execute a cgi/python script from within php, and at the same time pass the cgi/python script a paramter.
in my php I have
<? echo exec('/var/www/cgi-bin/test.cgi ' + $_POST["var"]); ?>
However it doesn't work, and in the apache log it says 'sh:0 not Found'
This test script is very simple :
#!/usr/bin/py... | [
"As someone pointed out, the string concatenation operator in PHP is ., not +.\nThe result of \"adding\" non-numeric strings is 0. That's why the shell tries to run the command \"0\" and returns error: \"sh:0 not found\".\nTry this:\nexec('/var/www/cgi-bin/test.cgi ' . escapeshellcmd($_POST[\"var\"]));\n\nAlso, not... | [
2
] | [] | [] | [
"cgi",
"php",
"python",
"variables"
] | stackoverflow_0004996969_cgi_php_python_variables.txt |
Q:
Problem with shutil.move - extra \
I have a log file and in the log, some of the files have errors, so when a file has an error I want to read its name (including path) and move it to another directory.
I can read the input file properly, for example one of the files is: C:\test\test1 i can find the file and I ju... | Problem with shutil.move - extra \ | I have a log file and in the log, some of the files have errors, so when a file has an error I want to read its name (including path) and move it to another directory.
I can read the input file properly, for example one of the files is: C:\test\test1 i can find the file and I just want to move it. However, when I use ... | [
"Several things are wrong here.\n\nFrom your edited error messages, I see you're moving C:/test/test1 to C:/test/test1... this will (if I remember correctly) always fail on Windows. Try a different destination directory for testing.\n\nanother_directory = \"C:\\test\"\n\nShould be \"C:/test\" or use os.path.join, ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004997024_python.txt |
Q:
Index python dict by object or two floats
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.
I need to record that, for example:
Point(X = 2.765, ... | Index python dict by object or two floats | I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.
I need to record that, for example:
Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7... | [
"Add a hash method to your Point class:\n...\ndef __hash__(self):\n return hash(self.x) ^ hash(self.y)\n...\n\nIn other words, the hash of a point is a munging of the hash of the x and y coordinates.\nEDIT: a better hash function (based on comments here) is:\n...\ndef __hash__(self):\n return hash((self.x, s... | [
10,
4,
1,
1,
1
] | [] | [] | [
"dictionary",
"floating_point",
"hash",
"python"
] | stackoverflow_0004763193_dictionary_floating_point_hash_python.txt |
Q:
sys.stdout.write not working properly for binary files on windows
I have a python script that handles all the incoming requests and generates/returns content based on the type of input.
When I run my python script with
print "Content-Type: text/plain\r\n\r\n" #debug mode
The generated html is what I expect to be.... | sys.stdout.write not working properly for binary files on windows | I have a python script that handles all the incoming requests and generates/returns content based on the type of input.
When I run my python script with
print "Content-Type: text/plain\r\n\r\n" #debug mode
The generated html is what I expect to be. But, when I comment the above line, it truncates a part of the output.... | [
"There was not a problem in print or stdout (as expected).\nI was trying to read from a binary file (on windows) and write it to stdout. Since the 'sys' module opens the 'stdout' file object on your behalf and normally does so in text mode, things were going haywire.\nSo, to fix this problem:\nmsvcrt.setmode(sys.st... | [
3
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0004996547_file_io_python.txt |
Q:
Iterate through parts of a string
I have string in the form
[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5, ... ]
I want to iterate through the comma separated key-value pairs. What is the best or shortest way to do this?
A:
s = "[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5]"
s = s.strip("[]") # Drop the bracket... | Iterate through parts of a string | I have string in the form
[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5, ... ]
I want to iterate through the comma separated key-value pairs. What is the best or shortest way to do this?
| [
"s = \"[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5]\"\ns = s.strip(\"[]\") # Drop the brackets\nfor kv in s.split(\",\"):\n key, value = kv.split(\":\")\n print key, value\n\nAlternatively, you could convert this into a dictionary (after stripping the brackets):\nd = dict(kv.split(\":\") for kv in s.split(\... | [
10,
4
] | [] | [] | [
"iterator",
"python",
"string",
"string_conversion"
] | stackoverflow_0004997944_iterator_python_string_string_conversion.txt |
Q:
How to group elements in python by n elements
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I'd like to get groups of size n elements from a list l:
ie:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
A:
Well, the brute force answer is:
subList = [theList[n:n+N] ... | How to group elements in python by n elements |
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I'd like to get groups of size n elements from a list l:
ie:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
| [
"Well, the brute force answer is:\nsubList = [theList[n:n+N] for n in range(0, len(theList), N)]\n\nwhere N is the group size (3 in your case):\n>>> theList = list(range(10))\n>>> N = 3\n>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]\n>>> subList\n[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\nIf you ... | [
48,
37,
6,
5,
0
] | [] | [] | [
"arrays",
"grouping",
"list",
"python"
] | stackoverflow_0004998427_arrays_grouping_list_python.txt |
Q:
Web crawler capable of interpreting Javascript in python for Windows
My ultimate goal is to build a web crawler capable of downloading all of the images on a webpage. My understanding from the reading I've done is that I need to embed a rendering/layout engine such as Gecko or Webkit.
Unfortunately, I'm running... | Web crawler capable of interpreting Javascript in python for Windows | My ultimate goal is to build a web crawler capable of downloading all of the images on a webpage. My understanding from the reading I've done is that I need to embed a rendering/layout engine such as Gecko or Webkit.
Unfortunately, I'm running windows, so PyWebkit is out and short learning C++ for Gecko or Java to u... | [
"You don't need Webkit to do that. All you need it an engine to run Javascript code, so take a look at Gogole V8 or Mozilla SpiderMonkey.\nIf you're prefer Python to build your crawler, you may want to use PyV8 as it provides all necessary bindings.\n"
] | [
3
] | [] | [] | [
"gecko",
"python",
"webkit"
] | stackoverflow_0004998566_gecko_python_webkit.txt |
Q:
Unpredictable results from os.path.join in windows
So what I'm trying to do is to join something in the form of
os.path.join('C:\path\to\folder', 'filename').
**edit :
Actual code is :
filename = 'creepy_%s.pcl' % identifier
file = open(os.path.join(self.cache_dir, filename), 'w')
where self.cache_dir is read ... | Unpredictable results from os.path.join in windows | So what I'm trying to do is to join something in the form of
os.path.join('C:\path\to\folder', 'filename').
**edit :
Actual code is :
filename = 'creepy_%s.pcl' % identifier
file = open(os.path.join(self.cache_dir, filename), 'w')
where self.cache_dir is read from a file using configobj (returns string) and in the ... | [
"Your code is malformed. You need to double those backslashes or use a raw string.\nos.path.join('C:\\\\path\\\\to\\\\folder', 'filename'). \n\nI don't know why it works in one interpreter and not the other but your code will not be interpreted properly as is. The weird thing is i'd have expected a different output... | [
0,
0,
0,
0
] | [] | [] | [
"pygtk",
"python",
"windows_xp"
] | stackoverflow_0004982105_pygtk_python_windows_xp.txt |
Q:
Django model class inheritance - default fields and overrides
I'm attempting to have inherited class templates, so that all my models have certain default fields, and all have default overrides for a few functions like save_model()
If I do it like this, I get the overrides, but then have to go and manually set met... | Django model class inheritance - default fields and overrides | I'm attempting to have inherited class templates, so that all my models have certain default fields, and all have default overrides for a few functions like save_model()
If I do it like this, I get the overrides, but then have to go and manually set meta data like db_table...
class ModelExtension(models.Model):
alt... | [
"What's an MRO error? Have you read the django docs on model inheritance? You can either have Abstract Base Classes, Multi-table inheritance, or proxy models.\nhttp://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes\nWhat you've done there is a multi-table inheritance - there's a hidden OneT... | [
3,
0
] | [] | [] | [
"class",
"django",
"inheritance",
"python"
] | stackoverflow_0004997774_class_django_inheritance_python.txt |
Q:
How to create a glib.Source from Python?
I want to integrate some asyncore.dispatcher instances into GLib's default main context.
I figure I can create a custom GSource that's able to detect event readiness on the various sockets in asyncore.socket_map. From C I believe this is done by creating the necessary GSour... | How to create a glib.Source from Python? | I want to integrate some asyncore.dispatcher instances into GLib's default main context.
I figure I can create a custom GSource that's able to detect event readiness on the various sockets in asyncore.socket_map. From C I believe this is done by creating the necessary GSourceFuncs which could involve cheap and non-bloc... | [
"glib.io_add_watch does it (add a watch over a fd to the main loop):\nhttp://library.gnome.org/devel/pygobject/2.26/glib-functions.html#function-glib--io-add-watch\n",
"An easy way to integrate a dispatcher with a glib loop is shown, very simplified, below:\nfrom asyncore import dispatcher, loop\nfrom glib import... | [
0,
0
] | [] | [] | [
"asyncore",
"glib",
"pygtk",
"python"
] | stackoverflow_0004688943_asyncore_glib_pygtk_python.txt |
Q:
How to detect I/O in python source code(standard library way of I/O)
I'm build an optimizing compiler for a small subset of python code for my final year project. First thing I'm doing is testing whether a variable is involved in or leads to I/O. If I were to statically trace a function call down the proverbial ra... | How to detect I/O in python source code(standard library way of I/O) | I'm build an optimizing compiler for a small subset of python code for my final year project. First thing I'm doing is testing whether a variable is involved in or leads to I/O. If I were to statically trace a function call down the proverbial rabbit hole, how exactly would I know that it involves I/O? Would there be a... | [
"It's not as simple as just looking at the bytecode because calls for things are just symbol lookups:\n>>> def write_to_a_file(s):\n f = open('foo.txt', 'w')\n f.write(s)\n f.close()\n\n\n>>> import dis\n>>> dis.dis(write_to_a_file)\n 2 0 LOAD_GLOBAL 0 (open)\n 3 LOAD_C... | [
2
] | [] | [] | [
"abstract_syntax_tree",
"compiler_construction",
"io",
"optimization",
"python"
] | stackoverflow_0004998759_abstract_syntax_tree_compiler_construction_io_optimization_python.txt |
Q:
Gap detection in Django / MySQL
I have timeseries data stored in MySQL InnoDB and I access it using Django's object relational mapper.
My question is: how can I best identify and locate gaps in this timeseries data?
Edit for clarification: although it's fairly easy to get a list of all the missing data points, tha... | Gap detection in Django / MySQL | I have timeseries data stored in MySQL InnoDB and I access it using Django's object relational mapper.
My question is: how can I best identify and locate gaps in this timeseries data?
Edit for clarification: although it's fairly easy to get a list of all the missing data points, that doesn't completely solve my problem... | [
"You have to give some sort of sample data and how you like it processed. Telling us that you are storing it in MySQL or with innodb is not central to the problem (e.g., the ORM handles that). I assume you are able to extract your time series data as a list of integers, and you are trying to find where gaps start... | [
1,
0,
0
] | [] | [] | [
"django",
"mysql",
"python",
"rdbms",
"time_series"
] | stackoverflow_0004996426_django_mysql_python_rdbms_time_series.txt |
Q:
Python import txt formatting
I have an Excel file with a list of numbers and I saved it as a .txt file and then went to say:
open_file = open('list_of_numbers.txt','r')
for number in open_file:
number = int(number)
while x < 20000:
if (x > number):
print number
x = x + 100
... | Python import txt formatting | I have an Excel file with a list of numbers and I saved it as a .txt file and then went to say:
open_file = open('list_of_numbers.txt','r')
for number in open_file:
number = int(number)
while x < 20000:
if (x > number):
print number
x = x + 100
y = y + 100
And I received th... | [
"Let's put it as an answer. The problem is not \\r\\n. The problem is that you try to parse string that contains a float value as an integer. See (no line feed, new line characters):\n>>> int(\"2100.00\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for i... | [
4,
1
] | [
"Try this:\nnumber = int(number.strip(string.whitespace + \"'\"))\n\nYou will need to add import string to the beginning of the your script. See also: http://docs.python.org/library/stdtypes.html#str.strip\n"
] | [
-1
] | [
"import",
"python",
"string",
"text_files"
] | stackoverflow_0004998863_import_python_string_text_files.txt |
Q:
How to configure the flex crossdomain.xml in Python Google App Engine Sdk
I have created a flex application in the Python Gae sdk and I got the error 2048, so I put a crossdomain.xml under the static folder.
The crossdomain.xml is following:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM “/xml/dtds/cr... | How to configure the flex crossdomain.xml in Python Google App Engine Sdk | I have created a flex application in the Python Gae sdk and I got the error 2048, so I put a crossdomain.xml under the static folder.
The crossdomain.xml is following:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM “/xml/dtds/cross-domain-policy.dtd”>
<cross-domain-policy>
<site-control permitted-cross-do... | [
"I haven't used crossdomain.xml with Flash, but I have with Unity3d. I've gotten it to work, and what you have looks correct.\nHave you visited yoursite.com/crossdomain.xml to make sure it's visible in a browser?\nIf Flash is really picky you might need to specify a mimetype (text/xml or application/xml)\n- url: /c... | [
4,
1
] | [] | [] | [
"apache_flex",
"crossdomain.xml",
"flash",
"google_app_engine",
"python"
] | stackoverflow_0004993157_apache_flex_crossdomain.xml_flash_google_app_engine_python.txt |
Q:
Actionscript Three Asymmetric Encryption
I cant seem to find a reliable asymmetric encryption solution to secure data between a python based server application and a client over an open data channel.
I need some way for my client to prevent a man in the middle attack over an open data channel, my current exchange ... | Actionscript Three Asymmetric Encryption | I cant seem to find a reliable asymmetric encryption solution to secure data between a python based server application and a client over an open data channel.
I need some way for my client to prevent a man in the middle attack over an open data channel, my current exchange has me sending my clients a token they use to ... | [
"Since decompiling swf content is not a major problem for experienced hackers, I would strongly advise against hardcoding keys. Have you thought about using SSL at all?\n",
"Hardcoding they public keys won't help you, if someone really plans an attack, because the SWF itself is transfered over an unsafe channel,... | [
0,
0,
0
] | [] | [] | [
"actionscript",
"cryptography",
"encryption_asymmetric",
"python",
"token"
] | stackoverflow_0004931126_actionscript_cryptography_encryption_asymmetric_python_token.txt |
Q:
Ways to make a class immutable in Python
I'm doing some distributed computing in which several machines communicate under the assumption that they all have identical versions of various classes. Thus, it seems to be good design to make these classes immutable; not in the sense that it must thwart a user with bad i... | Ways to make a class immutable in Python | I'm doing some distributed computing in which several machines communicate under the assumption that they all have identical versions of various classes. Thus, it seems to be good design to make these classes immutable; not in the sense that it must thwart a user with bad intentions, just immutable enough that it is ne... | [
"If the old trick of using __slots__ does not fit you, this, or some variant of thereof can do: \nsimply write the __setattr__ method of your metaclass to be your guard. In this example, I prevent new attributes of being assigned, but allow modification of existing ones:\ndef immutable_meta(name, bases, dct):\n ... | [
9,
6,
1
] | [] | [] | [
"immutability",
"metaclass",
"python"
] | stackoverflow_0004996815_immutability_metaclass_python.txt |
Q:
Get specific info about calling code in Python decorators
I have a Python decorator that I'm using for marking functions/methods as deprecated. It works sufficiently, but I'd like it to work better. Specifically, what I want for it to do is to be able to tell the exact line number of the call to the deprecated f... | Get specific info about calling code in Python decorators | I have a Python decorator that I'm using for marking functions/methods as deprecated. It works sufficiently, but I'd like it to work better. Specifically, what I want for it to do is to be able to tell the exact line number of the call to the deprecated function. That way one does not have to grep through source cod... | [
"You don't need all that stuff:\nfrom functools import wraps\nimport warnings\n\ndef deprecated(message, newfunc):\n def _deprecated(func):\n @wraps(func)\n def _wrapped(*args, **kwds):\n warnings.warn(message + ', ' + newfunc, \n DeprecationWarning, stacklevel=2)\n ... | [
9
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0004999122_decorator_python.txt |
Q:
Program not executing full, stops in the middle
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
from brisa.core.threaded_call import run_async_function
from brisa.upnp.control_point.control_point import ControlPoint
from datetime import datetime
servic... | Program not executing full, stops in the middle | from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
from brisa.core.threaded_call import run_async_function
from brisa.upnp.control_point.control_point import ControlPoint
from datetime import datetime
service = ('u', 'urn:schemas-upnp-org:service:SwitchPower:1... | [
"I am not familiar with this 'brisa' library. I would gather that, for some reason, the ControlPoint constructor is exiting the entire program using sys.exit() (or is calling some equivalent C code).\nRun the program on the command-line, like this:\n$ python\n>>> import controlpt\n>>> controlpt.main()\n\nThen you s... | [
0
] | [] | [] | [
"dictionary",
"python",
"service"
] | stackoverflow_0004999238_dictionary_python_service.txt |
Q:
Emitting namespace specifications with ElementTree in Python
I am trying to emit an XML file with element-tree that contains an XML declaration and namespaces. Here is my sample code:
from xml.etree import ElementTree as ET
ET.register_namespace('com',"http://www.company.com") #some name
# build a tree structure
... | Emitting namespace specifications with ElementTree in Python | I am trying to emit an XML file with element-tree that contains an XML declaration and namespaces. Here is my sample code:
from xml.etree import ElementTree as ET
ET.register_namespace('com',"http://www.company.com") #some name
# build a tree structure
root = ET.Element("STUFF")
body = ET.SubElement(root, "MORE_STUFF"... | [
"Although the docs say otherwise, I only was able to get an <?xml> declaration by specifying both the xml_declaration and the encoding.\nYou have to declare nodes in the namespace you've registered to get the namespace on the nodes in the file. Here's a fixed version of your code:\nfrom xml.etree import ElementTre... | [
45,
8
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0004997848_elementtree_python_xml.txt |
Q:
Log Into Website and Scrape Streaming Data
I am not really a programmer but am asking this out of general curiosity. I visited a website recently where I logged in, went to a page, and without leaving, data on that page refreshes before my eyes.
Is it possible to mimic a browser (I was using Chrome) and log into ... | Log Into Website and Scrape Streaming Data | I am not really a programmer but am asking this out of general curiosity. I visited a website recently where I logged in, went to a page, and without leaving, data on that page refreshes before my eyes.
Is it possible to mimic a browser (I was using Chrome) and log into the site, navigate to a page, and "scrape" that ... | [
"If the data \"refreshes before your eyes\" it is probably AJAX (javascript in the page pulling new page-data from the server).\nThere are two ways of approaching this;\n\nusing Selenium you can wrap an actual browser which will load the page, run the javascript, then you can grab page-bits from the active page.\ny... | [
3,
1
] | [] | [] | [
"python",
"screen_scraping"
] | stackoverflow_0004999485_python_screen_scraping.txt |
Q:
Python: Display and count divisors of two integers
Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there ... | Python: Display and count divisors of two integers | Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.... | [
"Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:\n\nGet first number \nGet second number\nCalculate\n\nThis you can break down futher\n\nGet first number:\n\nGet Number from User \nLoop while Number is not ok\n\n\n...\nThis way you ... | [
3,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004996376_python.txt |
Q:
Creating a variable length color lookup table
I was wondering if anyone has any words of advice or could point me to any good resources regarding the creation of color lookup tables for image synthesis. In my application I have floating point values between -1.0 and 1.0 that need to be mapped onto RGB space. The p... | Creating a variable length color lookup table | I was wondering if anyone has any words of advice or could point me to any good resources regarding the creation of color lookup tables for image synthesis. In my application I have floating point values between -1.0 and 1.0 that need to be mapped onto RGB space. The problem is, I don't know beforehand what precision t... | [
"The term you are looking for is false color image.\nHow to pick the color bands depends on what you are trying to show.\nThe simple way is to split the data into two halves, above and below the mid-range\nFor the low half you set red=0, then blue=(255 - your value), green=(your value). This will give you a color ... | [
1,
1
] | [] | [] | [
"image_processing",
"lookup_tables",
"python"
] | stackoverflow_0003459070_image_processing_lookup_tables_python.txt |
Q:
Django ORM way of going through multiple Many-to-Many relationship
Dear people trying to help others,
I am trying to figure out how to get Django to do a join for me without writing custom SQL.
Let's say I have the following models
class Parent(models.Model):
name = models.CharField()
children = models.ManyT... | Django ORM way of going through multiple Many-to-Many relationship | Dear people trying to help others,
I am trying to figure out how to get Django to do a join for me without writing custom SQL.
Let's say I have the following models
class Parent(models.Model):
name = models.CharField()
children = models.ManyToManyField(Child, through="Parent_Child", related_name="parents")
class... | [
"Simply write something like:\nToy.objects.filter(toy_owners__parents=parent)\n\n",
"If you don't store extra information in the intermediate tables Parent_Child and Child_Toy you can just leave them out - Django will create them automatically for you. So a simplified setup would look like this:\nclass Parent(mod... | [
9,
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004999577_django_python.txt |
Q:
Getting full list of revisions on document level using CouchDB-Python?
I was working couchdb-python ( http://code.google.com/p/couchdb-python/ ) and i was wondering if I have any way to retrieve a full list
of revisions that have occurred on a document level?
Suppose I have a database named "movies" and it contain... | Getting full list of revisions on document level using CouchDB-Python? | I was working couchdb-python ( http://code.google.com/p/couchdb-python/ ) and i was wondering if I have any way to retrieve a full list
of revisions that have occurred on a document level?
Suppose I have a database named "movies" and it contains several documents.
Each of my documents have more than 3 revisions.
Can I ... | [
"I am not sure about couchdb-python, however you can get the entire known revision history of a document via the HTTP API.\nLearn all about it in the CouchDB Document API documentation.\nA normal query:\n$ curl jhs.couchone.com/db/doc\n{ _id: 'doc',\n _rev: '3-825cb35de44c433bfb2df415563a19de' }\n\nAdd ?revs=true ... | [
13,
2
] | [] | [] | [
"couchdb",
"python"
] | stackoverflow_0004966427_couchdb_python.txt |
Q:
merging n sorted lists of tuples in python
I have n lists (n<10) of tuples in the format [(ListID, [(index,value),(index, value),...)] and want to sort them by index to get to following outcome
Example Input:
[('A',[(0.12, 'how'),(0.26,'are'),(0.7, 'you'),(0.9,'mike'),(1.9, "I'm fine too")]),
('B',[(1.23, 'fine'),... | merging n sorted lists of tuples in python | I have n lists (n<10) of tuples in the format [(ListID, [(index,value),(index, value),...)] and want to sort them by index to get to following outcome
Example Input:
[('A',[(0.12, 'how'),(0.26,'are'),(0.7, 'you'),(0.9,'mike'),(1.9, "I'm fine too")]),
('B',[(1.23, 'fine'),(1.50, 'thanks'),(1.6,'and you')]),
('C',[(2.12,... | [
">>> from operator import itemgetter\n>>> import pprint\n>>> pprint.pprint(sorted(((i,k) for i,j in INPUT for k in j), key=itemgetter(1)))\n[('A', (0.12, 'how')),\n ('A', (0.26000000000000001, 'are')),\n ('A', (0.69999999999999996, 'you')),\n ('A', (0.90000000000000002, 'mike')),\n ('B', (1.23, 'fine')),\n ('B', (1... | [
5,
2,
2,
2
] | [] | [] | [
"algorithm",
"merge",
"python",
"sorting",
"tuples"
] | stackoverflow_0004999968_algorithm_merge_python_sorting_tuples.txt |
Q:
Python RSA library?
from Crypto.PublicKey import RSA
private = RSA.generate(1024, os.urandom)
Now how do I export or import keys? Everything is there except these 2 functions!
private.exportKey()
private.publickey.exportKey()
Preferably in --armor format :)
Any ideas?
Thanks all. Turned out that Ubuntu installs... | Python RSA library? | from Crypto.PublicKey import RSA
private = RSA.generate(1024, os.urandom)
Now how do I export or import keys? Everything is there except these 2 functions!
private.exportKey()
private.publickey.exportKey()
Preferably in --armor format :)
Any ideas?
Thanks all. Turned out that Ubuntu installs an old version of PyCryp... | [
"If you are using PyCryto, then I see that PyCryto 2.2 has that functionality. Otherwise you will find the patch here useful.\n",
"Crypto.PublicKey's exportKey is within module rsa, under _RSAobj class. You can look at the documentation here. You can export the public or private key with 'DER' (PKCS#1) or 'PEM' (... | [
2,
0
] | [] | [] | [
"cryptography",
"python",
"rsa"
] | stackoverflow_0005000434_cryptography_python_rsa.txt |
Q:
Why is Jython much slower than CPython, despite the JVM's advances?
No flame wars please. I am admittedly no fan of Java, but I consider the JVM to be a fairly decent and well-optimized virtual machine. It's JIT-enabled and very close to the common denominator of the prevalent CPU architectures. I'd assume that th... | Why is Jython much slower than CPython, despite the JVM's advances? | No flame wars please. I am admittedly no fan of Java, but I consider the JVM to be a fairly decent and well-optimized virtual machine. It's JIT-enabled and very close to the common denominator of the prevalent CPU architectures. I'd assume that the CPython runtime would be farther from the metal than a corresponding JV... | [
"Keep in mind that IronPython was started by one of the original Jython devs (Jim Huginin) in an attempt to prove that the .NET CLR was a poor platform for dynamic languages. He ended up proving himself wrong and the core of IronPython eventually became the .NET Dynamic Language Runtime (making other dynamic langua... | [
25
] | [] | [] | [
"jvm",
"jython",
"python"
] | stackoverflow_0005000360_jvm_jython_python.txt |
Q:
I don't understand Jinja2 Call Blocks
I understand the concept, but I don't understand the syntax.
I'm going to use the example used on their site
{% macro render_dialog(title, class='dialog') -%}
<div class="{{ class }}">
<h2>{{ title }}</h2>
<div class="contents">
{{ caller() }}
</div>
</div... | I don't understand Jinja2 Call Blocks | I understand the concept, but I don't understand the syntax.
I'm going to use the example used on their site
{% macro render_dialog(title, class='dialog') -%}
<div class="{{ class }}">
<h2>{{ title }}</h2>
<div class="contents">
{{ caller() }}
</div>
</div>
{%- endmacro %}
{% call render_dialog('H... | [
"This is the output:\n<div class=\"dialog\">\n <h2>Hello World</h2>\n <div class=\"contents\">\n\n This is a simple dialog rendered by using a macro and\n a call block.\n\n </div>\n</div>\n\nSo when we call render_dialog we pass 'Hello World' as title, when it reach caller() it passes the contents of ... | [
14
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0005000469_jinja2_python.txt |
Q:
Need help with python exception handling
Here is the code I'm currently working with:
url = locations[state]['url']
headers = {'User-Agent':'Firefox/3.6.13'}
req = urllib.request.Request(url, headers=headers)
try:
resp = urllib.request.urlopen(req)
except:
print('Caught error, trying again...')
print('... | Need help with python exception handling | Here is the code I'm currently working with:
url = locations[state]['url']
headers = {'User-Agent':'Firefox/3.6.13'}
req = urllib.request.Request(url, headers=headers)
try:
resp = urllib.request.urlopen(req)
except:
print('Caught error, trying again...')
print('This should be handled better, I\'m sorry')
... | [
"Take a look at http://docs.python.org/py3k/library/urllib.error.html\nOnce you look at the reason attribute on the exception you should be able to determine:\n\nIs the reason attribute a socket.error instance?\nIf so, is the value of that error a 2-tuple, with the first element corresponding to errno.ECONNRESET?\n... | [
1
] | [
"First, there's no reason to use urllib in new code, urllib2 is recommended instead.\nAs I understood, you want to retry only if you've got error 104. This is how it's usually done in python:\nimport time, urllib.request, urllib2.error\nRETRY_DELAY = 2\n\n# build req here\n# ...\n\nfor x in range(10): # Always lim... | [
-1
] | [
"exception",
"exception_handling",
"python",
"python_3.x",
"urllib"
] | stackoverflow_0005000138_exception_exception_handling_python_python_3.x_urllib.txt |
Q:
pygame.gfxdraw.aacircle gows funny for big circles, any alternatives?
Working on my Major project for software design and development and have run into the hurdle that when using pygame.gfxdraw.aacircle to draw big circles, the output goes screwy as seen here
the window in the picture is showing a section of a ci... | pygame.gfxdraw.aacircle gows funny for big circles, any alternatives? | Working on my Major project for software design and development and have run into the hurdle that when using pygame.gfxdraw.aacircle to draw big circles, the output goes screwy as seen here
the window in the picture is showing a section of a circle with a radius of size 1561
if no-one can suggest a fix or alternate wa... | [
"I would suggest not to use pygame.gfxdraw, since it is clearly marked as experimental. \nFrom the documentation:\n\nEXPERIMENTAL!: meaning this api may change, or dissapear in later\n pygame releases. If you use this, your\n code will break with the next pygame\n release.\n\nJust stick with the regular circle f... | [
2
] | [] | [] | [
"antialiasing",
"draw",
"geometry",
"pygame",
"python"
] | stackoverflow_0005001070_antialiasing_draw_geometry_pygame_python.txt |
Q:
the underscore of python
def host(self):
""" Return user host """
_ = self._request.getText
host = self.isCurrentUser() and self._cfg.show_hosts and self._request.remote_addr
return host or _("<unknown>")
for this code , _ is represent the getText function of _request . and i found _ sometimes rep... | the underscore of python | def host(self):
""" Return user host """
_ = self._request.getText
host = self.isCurrentUser() and self._cfg.show_hosts and self._request.remote_addr
return host or _("<unknown>")
for this code , _ is represent the getText function of _request . and i found _ sometimes represent for the last output of ... | [
"It's mostly a matter of convention. When your application is subject to i18n (internationalization), almost all your (display) strings go through a function to turn them into the proper language. Having a long function name for that will make the code unreadable, so naming it _ has become sort of a convention. \n(... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0005000928_python.txt |
Q:
Problem with django's wsgi
Trying to run on production.
wsgi:
import sys
import os ... | Problem with django's wsgi | Trying to run on production.
wsgi:
import sys
import os ... | [
"Before running modwsgi on your production code, test the \"Hello World\" program https://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide. If it is running fine, there is an issue with your apache config. Else, the issue lies with modwsgi or wsgi config file.\n"
] | [
0
] | [] | [] | [
"apache",
"centos",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0004998708_apache_centos_django_mod_wsgi_python.txt |
Q:
how to write and execute a hello world program in hadoop?
Am an absolute beginner in apache hadoop.
could you please tell me how to do a hello world python program in apache hadoop,and also hoe programs are run in hadoop( I just need to do it in a single culster). I have to do it in no time and am posting this bec... | how to write and execute a hello world program in hadoop? | Am an absolute beginner in apache hadoop.
could you please tell me how to do a hello world python program in apache hadoop,and also hoe programs are run in hadoop( I just need to do it in a single culster). I have to do it in no time and am posting this because am so desperate. I've configured hadoop on my ubuntu 10.10... | [
"i suggest to read docs,\nhttp://hadoop.apache.org/common/docs/r0.20.2/index.html\nand the wiki\nhttp://wiki.apache.org/hadoop/FrontPage\nin docs, you'll find some samples as shown by answer before. Good luck.\n",
"Since you can run this example in hadoop, it's the same way to run an application.\nCheck the doc h... | [
2,
1,
0
] | [] | [] | [
"hadoop",
"java",
"python"
] | stackoverflow_0004870908_hadoop_java_python.txt |
Q:
Multiple Database Config in Django 1.2
This is hopefully an easy question.
I'm having some trouble understanding the documentation for the new multiple database feature in Django 1.2. Primarily, I cant seem to find an example of how you actually USE the second database in one of your models.
When I define a new cl... | Multiple Database Config in Django 1.2 | This is hopefully an easy question.
I'm having some trouble understanding the documentation for the new multiple database feature in Django 1.2. Primarily, I cant seem to find an example of how you actually USE the second database in one of your models.
When I define a new class in my models.py how do I specify which d... | [
"Yeah, it is a little bit complicated.\nThere are a number of ways you could implement it. Basically, you need some way of indicating which models are associated with which database. \nFirst option\nHere's the code that I use; hope it helps.\nfrom django.db import connections\n\nclass DBRouter(object):\n \"\"\"A... | [
25,
8,
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003637419_django_django_models_python.txt |
Q:
adding menu to a curses python program
I am writing a text UI program using python and curses and am trying to add menus to the display but I cant find any documentation on adding menus for curses in python.Any pointers to how this can be done??
A:
Python library for curses does not seem to support the menu exte... | adding menu to a curses python program | I am writing a text UI program using python and curses and am trying to add menus to the display but I cant find any documentation on adding menus for curses in python.Any pointers to how this can be done??
| [
"Python library for curses does not seem to support the menu extensions available for n-curses. However, if you can using Python2 (most likely), you can try patch available here.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005001567_python.txt |
Q:
Determining charset from html meta tags w/python
I have a script that needs to determine the charset before being read by lxml.HTML() for parsing. I will assume ISO-8859-1(that's the normal assumed charset for this right?) if it can't be found and search the html for the meta tag with the charset attribute. Howeve... | Determining charset from html meta tags w/python | I have a script that needs to determine the charset before being read by lxml.HTML() for parsing. I will assume ISO-8859-1(that's the normal assumed charset for this right?) if it can't be found and search the html for the meta tag with the charset attribute. However I'm not sure the best way to do that. I could try to... | [
"You should first try to extract encoding from HTTP headers. If it is not present there, you should parse it with the lxml. This might be tricky since lxml throws parse errors if charset does not match. A work-around would be decoding and encoding the data ignoring the unknown characters.\nhtml_data=html_data.decod... | [
3,
3
] | [] | [] | [
"html",
"html_parsing",
"python",
"python_3.x"
] | stackoverflow_0005001618_html_html_parsing_python_python_3.x.txt |
Q:
When I write into CSV file, it writes only the second time
I am in the learning process and I face this problem..
writer = csv.writer(open("db.csv", "w"))
connection = sqlite3.connect('hx.db')
cur_baseboard = connection.cursor()
cur_baseboard.execute('select * from baseboard')
writer.writerows(cur_baseboard)
Wh... | When I write into CSV file, it writes only the second time | I am in the learning process and I face this problem..
writer = csv.writer(open("db.csv", "w"))
connection = sqlite3.connect('hx.db')
cur_baseboard = connection.cursor()
cur_baseboard.execute('select * from baseboard')
writer.writerows(cur_baseboard)
When I run this code, the first time it creates the csv file db.cs... | [
"You're not closing the underlying file at the end, so the data is not flushed. Also, you should use the \"b\" flag to make sure the file is opened in binary mode. ( http://docs.python.org/library/csv.html#csv.writer ) Use:\nfrom __future__ import with_statement\nwith open(\"db.csv\", \"wb\") as f:\n writer = cs... | [
3,
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0005001896_csv_python.txt |
Q:
[Python/Project Euler]Problem 41
I am trying to solve problem 41, but i don't know why my code stops at 987654319:
def IsPandigital(No):
a = sorted(str(No))
for i in range(1,10):
if a[i - 1] != str(i):
return False
return True
def IsPrime(No):
i = 2
while i < No:
if No % i == 0:
return False
i += ... | [Python/Project Euler]Problem 41 | I am trying to solve problem 41, but i don't know why my code stops at 987654319:
def IsPandigital(No):
a = sorted(str(No))
for i in range(1,10):
if a[i - 1] != str(i):
return False
return True
def IsPrime(No):
i = 2
while i < No:
if No % i == 0:
return False
i += 1
return True
i = 987654321
while i >... | [
"Your IsPrime function is very slow. It quickly calculated that 987654321 is dividable by 3 and 987654320 is dividable by 2. However, 987654319 is prime and it takes very very long to check it against all divisors so it seems as if it stopped.\nThe problem requires more than just simple calculation, as you did. Cal... | [
10,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003379811_python.txt |
Q:
i need some directions in comparing values from different sources using python
I need to compare values that i have by executing wmi commands(using python) and values from inside a db.. is it best to compare them without storing in separate files or is storing and then comparing is the only possible way?
can someo... | i need some directions in comparing values from different sources using python | I need to compare values that i have by executing wmi commands(using python) and values from inside a db.. is it best to compare them without storing in separate files or is storing and then comparing is the only possible way?
can someone pls direct me in the right way.. also, where should i look for, for getting more ... | [
"If in doubt, go for the simplest solution. In this case, compare them in memory.\nIf you want to be ultra-reliable (i.e. survive after crashes of your application / power outage) or cache values for long times (i.e. it's a requirement to continue working even when the database is down), you may consider files. Be ... | [
1
] | [] | [] | [
"comparison",
"python"
] | stackoverflow_0005002359_comparison_python.txt |
Q:
How to generate strong one time session key for AES in python
I am using M2Crypto's AES for encrypting message, but confused about how to generate a strong random session key and of what length. Does M2Crypto provide any function for generation random key.
A:
AES-128 has 128 bit key = 16 bytes.
random_key = os.... | How to generate strong one time session key for AES in python | I am using M2Crypto's AES for encrypting message, but confused about how to generate a strong random session key and of what length. Does M2Crypto provide any function for generation random key.
| [
"AES-128 has 128 bit key = 16 bytes.\nrandom_key = os.urandom(16)\n\nshould be sufficient for most uses. When you feed this random value to M2 (or whatever crypto library), it is transformed internally into a \"key schedule\" actually used for encryption.\n",
"M2Crypto is notorious for lack of good documentation.... | [
18,
4,
0
] | [] | [] | [
"m2crypto",
"python"
] | stackoverflow_0005000946_m2crypto_python.txt |
Q:
From PHP and now to Python ( Based on project needs )
Basically I'm php web programmer, and I am now facing a difficulties on school project with ajax long polling (which has module with notification push). So after doing some research and read the weaknesses on doing "long-polling" with php and I found this artic... | From PHP and now to Python ( Based on project needs ) | Basically I'm php web programmer, and I am now facing a difficulties on school project with ajax long polling (which has module with notification push). So after doing some research and read the weaknesses on doing "long-polling" with php and I found this article which is as below link:
Simpler long polling with Django... | [
"First. Do a better search.\nhttp://blog.perplexedlabs.com/2009/05/04/php-jquery-ajax-javascript-long-polling/\nSeems to be PHP-based. Why not use that?\n\nplug into my php project.\n\nThis is rarely going to be helpful. If you have to learn Python to implement \"long-polling\", then you may as well stop using P... | [
3
] | [] | [] | [
"ajax",
"notifications",
"php",
"polling",
"python"
] | stackoverflow_0005002688_ajax_notifications_php_polling_python.txt |
Q:
I am getting same version name for WSS and MOSS 2007?
I am getting same version name for WSS and MOSS 2007?
response = urllib2.urlopen(url)
print response.info().getheader('MicrosoftSharePointTeamServices')
I am using the above python code to get the verion of the sharepoint verion using the site URL.
WSS:Microso... | I am getting same version name for WSS and MOSS 2007? | I am getting same version name for WSS and MOSS 2007?
response = urllib2.urlopen(url)
print response.info().getheader('MicrosoftSharePointTeamServices')
I am using the above python code to get the verion of the sharepoint verion using the site URL.
WSS:MicrosoftSharePointTeamServices: 12.0.0.4518
MOSS:MicrosoftSharePo... | [
"The version is exactly the same for both. MOSS is nothing more than a couple of extra modules on top of WSS.\nHave a look at this post about how to differentiate between MOSS and WSS from inside SharePoint code. \nNot sure if this will help you as you want to look remotely. You may want to consider adding a simple... | [
1
] | [] | [] | [
"python",
"response_headers",
"sharepoint",
"version"
] | stackoverflow_0005002569_python_response_headers_sharepoint_version.txt |
Q:
Getting module name with ast
How to get a python module name using ast? I tried the following to get the Module Node, but looks like it does not have the name information:
class v(ast.NodeVisitor):
def visit_Module(self, node):
print "Module : %s" % node
v().visit_Module(ast.parse(f.read(), filename))... | Getting module name with ast | How to get a python module name using ast? I tried the following to get the Module Node, but looks like it does not have the name information:
class v(ast.NodeVisitor):
def visit_Module(self, node):
print "Module : %s" % node
v().visit_Module(ast.parse(f.read(), filename))
I basically need the actual modu... | [
"AFAIU, this information doesn't exist in ast. More formally, the abstract grammar for Module in Python is:\nmod = Module(stmt* body)\n | Interactive(stmt* body)\n | Expression(expr body)\n\n -- not really an actual node but useful in Jython's typesystem.\n | Suite(stmt* body)\n\nSo as you can see a Mod... | [
5
] | [] | [] | [
"abstract_syntax_tree",
"parsing",
"python"
] | stackoverflow_0005002971_abstract_syntax_tree_parsing_python.txt |
Q:
sqlautocode for mysql giving syntax error
I am using TG2.1 on WinXP.
Python ver is 2.6.
Trying to use sqlautocode (0.5.2) for working with my existing MySQL schema.
SQLAlchemy ver is 0.6.6
import sqlautocode # works OK
While trying to reflect the schema ----
sqlautocode mysql:\\username:pswd@hostname:3306\sche... | sqlautocode for mysql giving syntax error | I am using TG2.1 on WinXP.
Python ver is 2.6.
Trying to use sqlautocode (0.5.2) for working with my existing MySQL schema.
SQLAlchemy ver is 0.6.6
import sqlautocode # works OK
While trying to reflect the schema ----
sqlautocode mysql:\\username:pswd@hostname:3306\schema_name -o tables.py
SyntaxError: invalid ... | [
"Your issue may be the backslash \"\\\" Try going from this:\nsqlautocode mysql:\\\\username:pswd@hostname:3306\\schema_name -o tables.py\n\nto this:\nsqlautocode mysql://username:pswd@hostname:3306/schema_name -o tables.py\n\n",
"Hey, I got it right somehow.\nThe problem seems to be version mismatch between SA 0... | [
1,
1
] | [] | [] | [
"python",
"turbogears2",
"web_applications"
] | stackoverflow_0004994838_python_turbogears2_web_applications.txt |
Q:
Genshi Layout Include In Chameleon ZPT
In Genshi, you can do include for layout (which to me is the only way to ensure all the 500 content templates will have the same layout) --
"""layout.xml"""
<py:match path="head" once="true">
<head py:attrs="select('@*')">
<title>Myapp</title>
</head>
</py:match>
<py:... | Genshi Layout Include In Chameleon ZPT | In Genshi, you can do include for layout (which to me is the only way to ensure all the 500 content templates will have the same layout) --
"""layout.xml"""
<py:match path="head" once="true">
<head py:attrs="select('@*')">
<title>Myapp</title>
</head>
</py:match>
<py:match path="body" once="true">
<body py:at... | [
"You could try something like this:\nlayout.pt\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:tal=\"http://xml.zope.org/namespaces/tal\"\n metal:define-macro=\"layout\">\n<head>\n <title>${page_title} :: My Website</title>\n</head>\n<body>\n <div metal:define-slot=\"main_content\">\n Content\n... | [
2
] | [] | [] | [
"genshi",
"html",
"pylons",
"python",
"templates"
] | stackoverflow_0004824556_genshi_html_pylons_python_templates.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.