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:
Installing a module/script in Python on OSX
I am running Python 2.6.2 in Mac OSX 10.5.8.
I am trying to generate scientific graphs for a publication and am experimenting with python/matplotlib to do that. Varun Hiremath created a module called plot_settings.py (link text and I am trying to figure out how to install the module so that I can import it. I'm not sure if easy_install is applicable here, which is why I'm confused. Thanks!
A:
Put that file in the same folder as your script and import it: import plot_settings.
| Installing a module/script in Python on OSX | I am running Python 2.6.2 in Mac OSX 10.5.8.
I am trying to generate scientific graphs for a publication and am experimenting with python/matplotlib to do that. Varun Hiremath created a module called plot_settings.py (link text and I am trying to figure out how to install the module so that I can import it. I'm not sure if easy_install is applicable here, which is why I'm confused. Thanks!
| [
"Put that file in the same folder as your script and import it: import plot_settings.\n"
] | [
1
] | [] | [] | [
"installation",
"macos",
"module",
"python"
] | stackoverflow_0003886324_installation_macos_module_python.txt |
Q:
python: breaking a string into substrings using a for loop
i have a string like this:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i have this loop:
for n in range (1,int(len(row)/55)+1):
print row[(n-1)*55:n*55]
it is working well!!
however, it is cutting the spaces:
saint george 1739 1799 violin concerti g 029 039 050 sy
mphonie concertante for two violins g 024 bertrand cerv
era in 024 039 christophe guiot in 024 029 and thibault
i do not want it to cut the spaces (however i still want either 55 characters or less per line)
A:
import textwrap
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
print(textwrap.fill(row,width=55))
# saint george 1739 1799 violin concerti g 029 039 050
# symphonie concertante for two violins g 024 bertrand
# cervera in 024 039 christophe guiot in 024 029 and
# thibault vieux violin soloists orchestre les archets de
# paris
A:
have a look at textwrap module.
A:
I think the clearest way would be
for i in range(0, len(row), 55):
print test[i:i+55]
where the third parameter to range is the step value, i.e. the difference between range elements.
edit: just reread your question, and realized that I'm not sure if you want it to break along word boundaries or to just do a hard break at the 55th character of each line.
If you do want it to break along word boundaries, you should check out the textwrap module as suggested by unutbu and SilentGhost.
| python: breaking a string into substrings using a for loop | i have a string like this:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i have this loop:
for n in range (1,int(len(row)/55)+1):
print row[(n-1)*55:n*55]
it is working well!!
however, it is cutting the spaces:
saint george 1739 1799 violin concerti g 029 039 050 sy
mphonie concertante for two violins g 024 bertrand cerv
era in 024 039 christophe guiot in 024 029 and thibault
i do not want it to cut the spaces (however i still want either 55 characters or less per line)
| [
"import textwrap\n\nrow='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'\n\nprint(textwrap.fill(row,width=55))\n# saint george 1739 1799 violin ... | [
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003886465_python.txt |
Q:
PyQT4 and Ctrl C
I have a programs that runs several threads (on a while loop until
Ctrl C is pressed). The app also has a GUI that I developed in PyQt. However, I am facing the following problem:
If I press Ctrl C on the console, and then close the GUI, the program exits fine. However, if I close the GUI first, the other threads won't stop and the program keeps running after Ctrl C. Anyone knows how I could address this problem?
A:
In Qt you would overload the OnClose method for the widget/frame or hook the lastwindowsdclosed signal to do whatever you need to shut down the app - don't know if it's diiferent from python
| PyQT4 and Ctrl C | I have a programs that runs several threads (on a while loop until
Ctrl C is pressed). The app also has a GUI that I developed in PyQt. However, I am facing the following problem:
If I press Ctrl C on the console, and then close the GUI, the program exits fine. However, if I close the GUI first, the other threads won't stop and the program keeps running after Ctrl C. Anyone knows how I could address this problem?
| [
"In Qt you would overload the OnClose method for the widget/frame or hook the lastwindowsdclosed signal to do whatever you need to shut down the app - don't know if it's diiferent from python\n"
] | [
0
] | [] | [] | [
"copy_paste",
"multithreading",
"pyqt",
"python"
] | stackoverflow_0003886500_copy_paste_multithreading_pyqt_python.txt |
Q:
python: turning textwrap into a list
i have a variable:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i am doing this:
textwrap.fill(row,55)
i would like some list line to have line[0]='saint george 1739 1799 violin concerti g 029 039 050' and line[1]='symphonie concertante for two violins g 024 bertrand' etc.....
please help me with this conversion from textwrap into a list
please note that textwrap breaks things up by \n
A:
use textwrap.wrap instead of textwrap.fill
A:
textwrap.wrap returns a list. Why not use that?
textwrap.fill(text, ...) is the equivalent of "\n".join(wrap(text, ...)). As explained in the docs.
A:
You can just split it using e.g.
textwrap.fill(row, 55).split('\n')
or use textwrap.wrap instead.
| python: turning textwrap into a list | i have a variable:
row='saint george 1739 1799 violin concerti g 029 039 050 symphonie concertante for two violins g 024 bertrand cervera in 024 039 christophe guiot in 024 029 and thibault vieux violin soloists orchestre les archets de paris'
i am doing this:
textwrap.fill(row,55)
i would like some list line to have line[0]='saint george 1739 1799 violin concerti g 029 039 050' and line[1]='symphonie concertante for two violins g 024 bertrand' etc.....
please help me with this conversion from textwrap into a list
please note that textwrap breaks things up by \n
| [
"use textwrap.wrap instead of textwrap.fill\n",
"textwrap.wrap returns a list. Why not use that?\ntextwrap.fill(text, ...) is the equivalent of \"\\n\".join(wrap(text, ...)). As explained in the docs.\n",
"You can just split it using e.g.\ntextwrap.fill(row, 55).split('\\n')\n\nor use textwrap.wrap instead.\n"... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003886540_python.txt |
Q:
how to prevent QTableModel from updating table depending on some condition
i have a mysql tables that uses lock-write mechanism. the lock might go for too long (we're talking about 1-2 minutes here).
i had to make a check if the table is in use or not before the update is done (using beforeUpdate signal)
but after checking and returning that my table is in use , system hang until the other user unlocks the table . is it possible to prevent data from updating if the flag returned that the table is in use.,
im searching for a better way to handle this i don't want to re-implement the setData method since doing this is a pain. or if you have a good re-implementation for it . it will be very helpfull.
thanks in advance
A:
Python threading: http://docs.python.org/library/thread.html You can create threads that wait until the table is finished and it should be negligible in system resources, also your end user wont have to wait for the system to respond to continue with a different task.
| how to prevent QTableModel from updating table depending on some condition | i have a mysql tables that uses lock-write mechanism. the lock might go for too long (we're talking about 1-2 minutes here).
i had to make a check if the table is in use or not before the update is done (using beforeUpdate signal)
but after checking and returning that my table is in use , system hang until the other user unlocks the table . is it possible to prevent data from updating if the flag returned that the table is in use.,
im searching for a better way to handle this i don't want to re-implement the setData method since doing this is a pain. or if you have a good re-implementation for it . it will be very helpfull.
thanks in advance
| [
"Python threading: http://docs.python.org/library/thread.html You can create threads that wait until the table is finished and it should be negligible in system resources, also your end user wont have to wait for the system to respond to continue with a different task.\n"
] | [
0
] | [] | [] | [
"mysql",
"pyqt",
"python",
"qt"
] | stackoverflow_0003854049_mysql_pyqt_python_qt.txt |
Q:
Is appengine Python datastore query much (>3x) slower than Java?
I've been investigating the appengine to see if I can use it for a
project and while trying to choose between Python and Java, I ran into
a surprising difference in datastore query performance: medium to
large datastore queries are more than 3 times slower in Python than in
Java.
My question is: is this performance difference for datastore queries
(Python 3x slower than Java) normal, or am I doing something wrong in
my Python code that's messing with the numbers?
My entity looks like this:
Person
firstname (length 8)
lastname (length 8)
address (20)
city (10)
state (2)
zip (5)
I populate the datastore with 2000 Person records, with each field
exactly the length noted here, all filled with random data and with no
fields indexed (just so the inserts go faster).
I then query 1k Person records from Python (no filters, no ordering):
q = datastore.Query("Person")
objects = list(q.Get(1000))
And 1k Person records from Java (likewise no filters, no ordering):
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Person");
PreparedQuery pq = ds.prepare(q);
// Force the query to run and return objects so we can be sure
// we've timed a full query.
List<Entity> entityList = new ArrayList<Entity>(pq.asList(withLimit(1000)));
With this code, the Java code returns results in ~200ms; the Python
code takes much longer, averaging >700ms. Both apps are on the same
app id (with different versions), so they use the same datastore and should
be on a level playing field.
All my code is available here, in case I've missed any details:
http://github.com/greensnark/appenginedatastoretest
A:
This would be an expected difference between Python and Java. Most likely you aren't seeing differences in the amount of time to make the query, but the amount of time it takes to parse the result and fill the receiving data structure.
You can test this by comparing the time it takes to query a single record. Remember that you'll need to test several times and average the total to get a true benchmark to account for possible fluctuations in latency on the backend.
In general, you can expect a compiled statically typed language like Java or Scala to always be faster than an interpreted language dynamically typed language like Ruby or Python.
| Is appengine Python datastore query much (>3x) slower than Java? | I've been investigating the appengine to see if I can use it for a
project and while trying to choose between Python and Java, I ran into
a surprising difference in datastore query performance: medium to
large datastore queries are more than 3 times slower in Python than in
Java.
My question is: is this performance difference for datastore queries
(Python 3x slower than Java) normal, or am I doing something wrong in
my Python code that's messing with the numbers?
My entity looks like this:
Person
firstname (length 8)
lastname (length 8)
address (20)
city (10)
state (2)
zip (5)
I populate the datastore with 2000 Person records, with each field
exactly the length noted here, all filled with random data and with no
fields indexed (just so the inserts go faster).
I then query 1k Person records from Python (no filters, no ordering):
q = datastore.Query("Person")
objects = list(q.Get(1000))
And 1k Person records from Java (likewise no filters, no ordering):
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Person");
PreparedQuery pq = ds.prepare(q);
// Force the query to run and return objects so we can be sure
// we've timed a full query.
List<Entity> entityList = new ArrayList<Entity>(pq.asList(withLimit(1000)));
With this code, the Java code returns results in ~200ms; the Python
code takes much longer, averaging >700ms. Both apps are on the same
app id (with different versions), so they use the same datastore and should
be on a level playing field.
All my code is available here, in case I've missed any details:
http://github.com/greensnark/appenginedatastoretest
| [
"This would be an expected difference between Python and Java. Most likely you aren't seeing differences in the amount of time to make the query, but the amount of time it takes to parse the result and fill the receiving data structure.\nYou can test this by comparing the time it takes to query a single record. Rem... | [
5
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0003886341_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
Basic Widget Interaction with PyQt
Please can someone tell me what im doing wrong here with respect to calling pwTxt.text.
#!/usr/bin/python
import sys
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def on_pwExtract_pressed(self):
print self.pwTxt.text
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
The line print self.pwTxt.text fails because it can't find the widget, pwTxt is a QLineEdit defined on the main window. I just made it in QTDesigner and generated python code with pyuic4.
How do I correctly reference other widgets on the same window, in this case I just want to get the text from a QLineEdit named pwTxt when the QPushButton pwExtract is pressed.
Thanks a lot.
A:
Try:
print self.ui.pwTxt.text()
| Basic Widget Interaction with PyQt | Please can someone tell me what im doing wrong here with respect to calling pwTxt.text.
#!/usr/bin/python
import sys
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def on_pwExtract_pressed(self):
print self.pwTxt.text
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
The line print self.pwTxt.text fails because it can't find the widget, pwTxt is a QLineEdit defined on the main window. I just made it in QTDesigner and generated python code with pyuic4.
How do I correctly reference other widgets on the same window, in this case I just want to get the text from a QLineEdit named pwTxt when the QPushButton pwExtract is pressed.
Thanks a lot.
| [
"Try:\nprint self.ui.pwTxt.text()\n\n"
] | [
2
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0003886745_pyqt_python.txt |
Q:
Specify Framework Version on OSX
I am compiling a program that embeds Python, in particular Python v3.1. On my system I have several versions of the Python framework: 3.1, 2.5, 2.6. When I pass "-framework Python" to g++ when compiling, g++ seems to pull in version 2.6 (lives at "/System/Library/Frameworks/") instead of version 3.1 (lives at "/Library/Frameworks/"), resulting in an error. Both paths are in the framework search path, as is evident from attempting the same compilation in verbose mode (passing in -v to g++).
Although this would seem to be a simple thing, I have not been able to find mention of it in any documentation about g++, ld or xcode. Currently, I accomplish successful compilation by moving /System/Library/Frameworks/Python.framework to /System/Library/Frameworks/Python.framework.moved, but this is un ugly, temporary solution.
So, does anyone know what the best way of resolving this issue? In particular, I would like to be able to compile this program against the correct version of the Python framework, regardless of any other versions installed on the system.
Thanks.
A:
Try first changing the Current symlink in the Python framework in /Library/Frameworks:
$ cd /Library/Frameworks/Python.framework/Versions
$ ls -l
total 4
drwxrwxr-x 8 root admin 340 Aug 31 02:10 2.6/
drwxrwxr-x 8 root admin 340 Oct 6 21:56 2.7/
drwxrwxr-x 7 root admin 306 Oct 6 14:00 3.1/
lrwxr-xr-x 1 root admin 3 Oct 7 00:33 Current@ -> 2.7
$ sudo rm Current
$ sudo ln -s 3.1 Current
(UPDATE) I was hoping, without testing it, that ensuring the Current link in /Library/Frameworks pointing at the right version would be enough. But, based on the OP's experimentation, you probably need to modify the analogous link in /System/Library as well. Usually it's a bad idea to be modifying anything in /System/Library because anything within it is considered part of OS X and is managed by Apple and, thus, any changes you make can, at best, be erased by the next System Update and, at worst, break your system. In this case, it probably won't make a big difference as the Current link is likely only used in this situation, that is, linking an embedded library. If you are really fastidious, you might consider restoring the original value when you are finished.
| Specify Framework Version on OSX | I am compiling a program that embeds Python, in particular Python v3.1. On my system I have several versions of the Python framework: 3.1, 2.5, 2.6. When I pass "-framework Python" to g++ when compiling, g++ seems to pull in version 2.6 (lives at "/System/Library/Frameworks/") instead of version 3.1 (lives at "/Library/Frameworks/"), resulting in an error. Both paths are in the framework search path, as is evident from attempting the same compilation in verbose mode (passing in -v to g++).
Although this would seem to be a simple thing, I have not been able to find mention of it in any documentation about g++, ld or xcode. Currently, I accomplish successful compilation by moving /System/Library/Frameworks/Python.framework to /System/Library/Frameworks/Python.framework.moved, but this is un ugly, temporary solution.
So, does anyone know what the best way of resolving this issue? In particular, I would like to be able to compile this program against the correct version of the Python framework, regardless of any other versions installed on the system.
Thanks.
| [
"Try first changing the Current symlink in the Python framework in /Library/Frameworks:\n$ cd /Library/Frameworks/Python.framework/Versions\n$ ls -l\ntotal 4\ndrwxrwxr-x 8 root admin 340 Aug 31 02:10 2.6/\ndrwxrwxr-x 8 root admin 340 Oct 6 21:56 2.7/\ndrwxrwxr-x 7 root admin 306 Oct 6 14:00 3.1/\nlrwxr-x... | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003884470_macos_python.txt |
Q:
Tuple to string
I have a tuple.
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
And I want to convert it to a string..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
what is a good way to do this?
Thanks!
A:
tst2 = str(tst)
E.g.:
>>> tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
>>> tst2 = str(tst)
>>> print tst2
([['name', u'bob-21'], ['name', u'john-28']], True)
>>> repr(tst2)
'"([[\'name\', u\'bob-21\'], [\'name\', u\'john-28\']], True)"'
A:
While I like Adam's suggestion for str(), I'd be leaning towards repr() instead, given the fact you are explicitly looking for a python-syntax-like representation of the object. Judging help(str), its string conversion for a tuple might end up defined differently in future versions.
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
...
As opposed to help(repr):
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
In todays practice and environment though, there'd be little difference between the two, so use what describes your need best - something you can feed back to eval(), or something meant for user consumption.
>>> str(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
>>> repr(tst)
"([['name', u'bob-21'], ['name', u'john-28']], True)"
| Tuple to string | I have a tuple.
tst = ([['name', u'bob-21'], ['name', u'john-28']], True)
And I want to convert it to a string..
print tst2
"([['name', u'bob-21'], ['name', u'john-28']], True)"
what is a good way to do this?
Thanks!
| [
"tst2 = str(tst)\n\nE.g.:\n>>> tst = ([['name', u'bob-21'], ['name', u'john-28']], True)\n>>> tst2 = str(tst)\n>>> print tst2\n([['name', u'bob-21'], ['name', u'john-28']], True)\n>>> repr(tst2)\n'\"([[\\'name\\', u\\'bob-21\\'], [\\'name\\', u\\'john-28\\']], True)\"'\n\n",
"While I like Adam's suggestion for st... | [
17,
4
] | [] | [] | [
"python"
] | stackoverflow_0003886669_python.txt |
Q:
Why does initializing a variable via a python default variable keep state across object instantiation?
I hit an interesting python bug today in which instantiating a class repeatedly appears to be holding state. In later instantiation calls the variable is already defined.
I boiled down the issue into the following class/shell interaction. I realize that this is not the best way to initialize a class variable, but it sure should not be behaving like this. Is this a true bug or is this a "feature"? :D
tester.py:
class Tester():
def __init__(self):
self.mydict = self.test()
def test(self,out={}):
key = "key"
for i in ['a','b','c','d']:
if key in out:
out[key] += ','+i
else:
out[key] = i
return out
Python prompt:
Python 2.6.6 (r266:84292, Oct 6 2010, 00:44:09)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
>>> import tester
>>> t = tester.Tester()
>>> print t.mydict
{'key': 'a,b,c,d'}
>>> t2 = tester.Tester()
>>> print t2.mydict
{'key': 'a,b,c,d,a,b,c,d'}
A:
It is a feature that pretty much all Python users run into once or twice. The main usage is for caches and the like to avoid repetitive lengthy calculations (simple memoizing, really), although I am sure people have found other uses for it.
The reason for this is that the def statement only gets executed once, which is when the function is defined. Thus the initializer value only gets created once. For a reference type (as opposed to an immutable type which cannot change) like a list or a dictionary, this ends up as a visible and surprising pitfall, whereas for value types, it goes unnoticed.
Usually, people work around it like this:
def test(a=None):
if a is None:
a = {}
# ... etc.
A:
In general, default method arguments shouldn't be mutable. Instead do:
def test(self, out=None):
out = out or {}
# other code goes here.
See these links for more details on why this is necessary and why it's a "feature" of the python language rather than a bug.
"Least Astonishment" and the Mutable Default Argument
http://effbot.org/zone/default-values.htm
A:
You are modifying the value of the function keyword parameter out in your method.
This blog post explains it succintly:
expressions in default arguments are calculated when the function is defined, not when it’s called.
The function is defined when the class is created, not for each instance. If you modify it like so, the problem goes away:
def test(self,out=None):
if out is None:
out = {}
key = "key"
for i in ['a','b','c','d']:
if key in out:
out[key] += ','+i
else:
out[key] = i
return out
| Why does initializing a variable via a python default variable keep state across object instantiation? | I hit an interesting python bug today in which instantiating a class repeatedly appears to be holding state. In later instantiation calls the variable is already defined.
I boiled down the issue into the following class/shell interaction. I realize that this is not the best way to initialize a class variable, but it sure should not be behaving like this. Is this a true bug or is this a "feature"? :D
tester.py:
class Tester():
def __init__(self):
self.mydict = self.test()
def test(self,out={}):
key = "key"
for i in ['a','b','c','d']:
if key in out:
out[key] += ','+i
else:
out[key] = i
return out
Python prompt:
Python 2.6.6 (r266:84292, Oct 6 2010, 00:44:09)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
>>> import tester
>>> t = tester.Tester()
>>> print t.mydict
{'key': 'a,b,c,d'}
>>> t2 = tester.Tester()
>>> print t2.mydict
{'key': 'a,b,c,d,a,b,c,d'}
| [
"It is a feature that pretty much all Python users run into once or twice. The main usage is for caches and the like to avoid repetitive lengthy calculations (simple memoizing, really), although I am sure people have found other uses for it.\nThe reason for this is that the def statement only gets executed once, wh... | [
15,
5,
3
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0003887079_arguments_python.txt |
Q:
Letting users to choose what type of content they want to input
This is my first post here, and I'd like to describe what I want to do as specific as possible.
I'd like to make a model that is 'selectable.'
for example,
class SimpleModel(models.Model):
property = models.CharField(max_length=255)
value = GeneralField()
GeneralField can be "CharField", "URLField", "TextField" so that user can select appropriate input type for specific property.
I'm kinda thinking of this similar to Wordpress's custom_field.
My initial thought is making TextField and tweak input interface depends on user's selection, but it's a bit tricky and if it involves file uploading functionality, it's gonna be complicated.
of course, I googled a lot. If you have any thoughts on this, please give me a tip :)
thanx in advance
A:
How about creating a separate model for each type of field you want to support, and then another model consisting of a list of (table_name, entry_id) pairs, which could be customized to use any combination of fields?
| Letting users to choose what type of content they want to input | This is my first post here, and I'd like to describe what I want to do as specific as possible.
I'd like to make a model that is 'selectable.'
for example,
class SimpleModel(models.Model):
property = models.CharField(max_length=255)
value = GeneralField()
GeneralField can be "CharField", "URLField", "TextField" so that user can select appropriate input type for specific property.
I'm kinda thinking of this similar to Wordpress's custom_field.
My initial thought is making TextField and tweak input interface depends on user's selection, but it's a bit tricky and if it involves file uploading functionality, it's gonna be complicated.
of course, I googled a lot. If you have any thoughts on this, please give me a tip :)
thanx in advance
| [
"How about creating a separate model for each type of field you want to support, and then another model consisting of a list of (table_name, entry_id) pairs, which could be customized to use any combination of fields?\n"
] | [
0
] | [] | [] | [
"django_models",
"field",
"input",
"python"
] | stackoverflow_0003887017_django_models_field_input_python.txt |
Q:
python: append only specific elements from a list
i have a list of a list:
b=[[1,2,3],[4,5,6],[7,8,9]]
i have a list:
row = [1,2,3]
how do i append to b only row[0] and '3847' and row[2] such that b will equal:
b=[[1,2,3],[4,5,6],[7,8,9],[1,3847,3]]
A:
You're going to have to be more specific.
This will accomplish what you want:
b.append([row[0], 3847, row[2]])
But isn't really a general solution.
A:
b.append([ x if x != 2 else 3847 for x in row])
A:
b + [[row[0],3847,row[2]]]
A:
b + [row[0],3847,row[2]] would give you:
>>> b + [row[0],3847,row[2]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], 1, 3847, 3]
In order to get b=[[1,2,3],[4,5,6],[7,8,9],[1,3847,3]], you need to use append as suggested by "Nick Presta". You may have received other suitable solutions if you made the problem statement clearer.
| python: append only specific elements from a list | i have a list of a list:
b=[[1,2,3],[4,5,6],[7,8,9]]
i have a list:
row = [1,2,3]
how do i append to b only row[0] and '3847' and row[2] such that b will equal:
b=[[1,2,3],[4,5,6],[7,8,9],[1,3847,3]]
| [
"You're going to have to be more specific.\nThis will accomplish what you want:\nb.append([row[0], 3847, row[2]])\n\nBut isn't really a general solution.\n",
"b.append([ x if x != 2 else 3847 for x in row])\n\n",
"b + [[row[0],3847,row[2]]]\n\n",
"b + [row[0],3847,row[2]] would give you:\n>>> b + [row[0],3847... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003887336_python.txt |
Q:
Automate paster create -t plone3_buildout
I want to automate the process of plone3_buildout.
Explanation:
The default(the one I use) way of building a plone site is using paster, like so:
paster create -t plone3_buildout
This asks me a few questions and then create a default buildout for the site.
What I want:
I want to automate this process using buildout. My buildout will execute this paster command, feed in my preconfigured values to the paster.
I haven't found a recipe which can do this. If someone has an idea of how to do this, please share the info.
If there is a recipe which can feed values to interactive commands(with known output, like with plone3_buildout command), that would be useful too.
A:
The paster create command can accept a --config option. This allows you to generate or use a file with answers to the questions.
$ paster create -t plone3_buildout --config=saved.cfg my-buildout
...
answer questions
...
Now there will be a buildout.config file in the current directory.
$ cat saved.cfg
[pastescript]
eggifiedplone__eval__ = True
zope_user = admin
expert_mode = all
zope2_install =
plone_products_install =
tarballs__eval__ = False
egg_plugins__eval__ = []
plone_version = 3.3.4
debug_mode = off
plus = +
dot = .
zope_password =
http_port__eval__ = 8080
egg = test_buildout
z29tarballs__eval__ = False
eggifiedzope__eval__ = False
verbose_security = off
You can modify this file and run paster with the same command.
$ paster create -t plone3_buildout --config=saved.cfg my-new-buildout
This time it won't ask you any questions. All of the answers will come from the config file. The latest ZopeSkel (2.15+) also has a way to store these settings in $HOME/.zopeskel.
A:
There is a utility called "expect" which is designed for automating interactive command line operations.
http://expect.nist.gov
Another approach would be to modify or clone-and-customize the plone3_buildout script and template in the ZopeSkel package.
However at that point, if you're hardcoding all the variables, you might as well create the buildout once, put in into version control, and copy/clone it to make new instances.
| Automate paster create -t plone3_buildout | I want to automate the process of plone3_buildout.
Explanation:
The default(the one I use) way of building a plone site is using paster, like so:
paster create -t plone3_buildout
This asks me a few questions and then create a default buildout for the site.
What I want:
I want to automate this process using buildout. My buildout will execute this paster command, feed in my preconfigured values to the paster.
I haven't found a recipe which can do this. If someone has an idea of how to do this, please share the info.
If there is a recipe which can feed values to interactive commands(with known output, like with plone3_buildout command), that would be useful too.
| [
"The paster create command can accept a --config option. This allows you to generate or use a file with answers to the questions.\n$ paster create -t plone3_buildout --config=saved.cfg my-buildout\n...\nanswer questions\n...\n\nNow there will be a buildout.config file in the current directory.\n$ cat saved.cfg\n[pa... | [
2,
1
] | [] | [] | [
"automation",
"buildout",
"plone",
"python"
] | stackoverflow_0002894455_automation_buildout_plone_python.txt |
Q:
Python Desktop Integration - Drag and drop
I have a pygame window that I want to know when a file has been dragged and dropped onto it. I only need to be able to fetch the name of the file. How can this be accomplished?
A:
Here's a forum thread that might be what you're looking for.
And another forum.
And a link to the msdn page. You'll probably want the pythoncom library.
A:
one option for a similar effect is is to use pygame's scrap module so you can copy-paste into the window, your program would just need to look for ctr-V events.
On this XFCE desktop I'm using
If I hit ctrl-C with a file selected, the file name shows up when I type
pygame.scrap.init()
types= pygame.scrap.get_types()
print dict(
[type,pygame.scrap.get(type)]
for type intypes
)
| Python Desktop Integration - Drag and drop | I have a pygame window that I want to know when a file has been dragged and dropped onto it. I only need to be able to fetch the name of the file. How can this be accomplished?
| [
"Here's a forum thread that might be what you're looking for. \nAnd another forum.\nAnd a link to the msdn page. You'll probably want the pythoncom library.\n",
"one option for a similar effect is is to use pygame's scrap module so you can copy-paste into the window, your program would just need to look for ctr... | [
3,
0
] | [] | [] | [
"desktop_integration",
"drag_and_drop",
"pygame",
"python"
] | stackoverflow_0000682692_desktop_integration_drag_and_drop_pygame_python.txt |
Q:
Modelling Data with Google App Engine Datastore
I am currently building a web application on Google App Engine in Python to harvest horse racing data of the form. The basic data structure is Course has many Meetings has many Races has many Horses has one Jockey and had one Trainer. So far I have got the following models (reduced number of fields for sake of brevity).
class Course(db.Model):
course_number = db.IntegerProperty() # course id (third party)
course_description = db.StringProperty() # course name
class Meeting(db.Model):
course = db.ReferenceProperty(Course) # reference to course
meeting_number = db.IntegerProperty() # lifetime meeting number for course
meeting_date = db.DateProperty() # meeting date
class Race(db.Model):
meeting = db.ReferenceProperty(Meeting) # reference to meeting
race_number = db.IntegerProperty() # eg 1 for 1st race of meeting
race_name = db.StringProperty() # race name
time_of_race = db.TimeProperty() # race time
I am having trouble working out how to store data on Horses, Trainers, Jockeys in the data store.
My application will be harvesting data for say the last 2 years, for this I will be saving relevant result information for Horse, Trainer, Jockey. The information on a particular horses result is the same for Trainer and Jockey at that time point. However over time a Horse can have different trainer and different jockey.
My main brain ache is coming when I realise that in analysis I may need to look at the result for the last 10 races for either Horse, Jockey, Trainer. Results which may not be stored either because the results occured outside of UK racing (data is still available) or happened before the date I start complete race storage.
Can anyone shed any light on how to optimise the storage of Horse, Jockey, Trainer results so that I can accomodate for this?
Source of data: http://form.horseracing.betfair.com/timeform
All required data can be easily accessed via JSON requests.
A:
You are on the right track with using HorseResult, TrainerResult, and JockeyResult models. Do not forget, the datastore does not have grouping or aggregate functions, so you might want to pre-compute any aggregates or statistics of interest when you are loading the data.
Perhaps you will also want to have statistics type models for tracking horse, jockey, and trainer performance over time and the combinations of each. Something like HorseMonth, which might track how many races the horse was involved in and how it placed by month.
I would also consider keeping details on how the combinations of horse and jockey, or horse and trainer did over time. Unfortunately I do not know enough about horse racing to give you specific suggestions for which combinations are meaningful.
Since it sounds like this is a tool largely for your own use, you might look into the mapper API. It might be of great value when you are exploring the data.
If a race is not included in your data, aside from expanding the harvest range, there may not be a lot you can do. You will probably just want to return the results you have, and perhaps something indicating there is not enough data in the date range?
| Modelling Data with Google App Engine Datastore | I am currently building a web application on Google App Engine in Python to harvest horse racing data of the form. The basic data structure is Course has many Meetings has many Races has many Horses has one Jockey and had one Trainer. So far I have got the following models (reduced number of fields for sake of brevity).
class Course(db.Model):
course_number = db.IntegerProperty() # course id (third party)
course_description = db.StringProperty() # course name
class Meeting(db.Model):
course = db.ReferenceProperty(Course) # reference to course
meeting_number = db.IntegerProperty() # lifetime meeting number for course
meeting_date = db.DateProperty() # meeting date
class Race(db.Model):
meeting = db.ReferenceProperty(Meeting) # reference to meeting
race_number = db.IntegerProperty() # eg 1 for 1st race of meeting
race_name = db.StringProperty() # race name
time_of_race = db.TimeProperty() # race time
I am having trouble working out how to store data on Horses, Trainers, Jockeys in the data store.
My application will be harvesting data for say the last 2 years, for this I will be saving relevant result information for Horse, Trainer, Jockey. The information on a particular horses result is the same for Trainer and Jockey at that time point. However over time a Horse can have different trainer and different jockey.
My main brain ache is coming when I realise that in analysis I may need to look at the result for the last 10 races for either Horse, Jockey, Trainer. Results which may not be stored either because the results occured outside of UK racing (data is still available) or happened before the date I start complete race storage.
Can anyone shed any light on how to optimise the storage of Horse, Jockey, Trainer results so that I can accomodate for this?
Source of data: http://form.horseracing.betfair.com/timeform
All required data can be easily accessed via JSON requests.
| [
"You are on the right track with using HorseResult, TrainerResult, and JockeyResult models. Do not forget, the datastore does not have grouping or aggregate functions, so you might want to pre-compute any aggregates or statistics of interest when you are loading the data.\nPerhaps you will also want to have statis... | [
0
] | [] | [] | [
"betfair",
"google_app_engine",
"python"
] | stackoverflow_0003885012_betfair_google_app_engine_python.txt |
Q:
Sending data received in one Twisted factory to second factory
I am trying to write a simple program using Twisted framework and I am struggling with resolving (or even with imaging how to write it) issue I couldnt find any relevant documentation for:
The main reactor uses two factories, one custom, listening for TCP connections on given port (say, 8000) and second one, to log into given IRC server and channel. On receiving data (simple, one line text) on the factory listening at 8000, I need to pass that data to second factory, so it could be then processed accordingly - either send a message with that text to a channel, or a priv message to some person, thats not really important now. I cant find any way to get the data from first factory and send it to another, for processing (maybe like usual received connection for second IRC factory?).
If this could be somehow resolved, then I would like to add one or even more factories (Jabber for example) to send the received data on port 8000 to all of them at once, to pass it accordingly to protocols (IRC to a channel, Jabber to a contact, and so on).
Is there anyone who met similar issue and is willing to give me some advice or even share some lines of code? Any help will be highly appreciated!
Thanks in advance.
A:
Factories are just objects. To pass data from one to another, you define and call methods and pass the data as parameter, or set attributes. I think this faq question will help you:
How do I make input on one connection
result in output on another?
This seems like it's a Twisted
question, but actually it's a Python
question. Each Protocol object
represents one connection; you can
call its transport.write to write some
data to it. These are regular Python
objects; you can put them into lists,
dictionaries, or whatever other data
structure is appropriate to your
application.
As a simple example, add a list to
your factory, and in your protocol's
connectionMade and connectionLost, add
it to and remove it from that list.
Here's the Python code:
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class MultiEcho(Protocol):
def connectionMade(self):
self.factory.echoers.append(self)
def dataReceived(self, data):
for echoer in self.factory.echoers:
echoer.transport.write(data)
def connectionLost(self, reason):
self.factory.echoers.remove(self)
class MultiEchoFactory(Factory):
protocol = MultiEcho
def __init__(self):
self.echoers = []
reactor.listenTCP(4321, MultiEchoFactory())
reactor.run()
A:
I think your comment above is along the right lines - you need to have a reference or a 'handle' for the object you wish to send the data to.
In other words the sending factory object must have a reference for the receiving factory object if you want to use object to object communication - i.e. method calls. One way to achieve this is for the name of the receiving factory to be passed to the sending factory at initialization.
It is not always obvious from examples but a factory can have data passed to it when it is initialized. For example in the case above the line that creates the MultiEchoFactory could be modified to:
reactor.listenTCP(4321, MultiEchoFactory(someOtherObject))
and the MultiEchoFactory object itself modified in it's init method:
class MultiEchoFactory(Factory):
protocol = MultiEcho
def __init__(self, otherObjectReference):
self.echoers = []
self.otherObject = otherObjectReference
Now you have a reference to the other object and call methods on it.
Another approach might be to have a completely separate object which all your factories are given a reference to on initialization, and which acts as a sort of 'look up' server for object references when one object wants to speak to another. This functionality could be provided by a function if you would rather not use an object.
A:
The way I do it is by creating a container class.
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
self.factory.message_siblings("Got a client")
self.transport.loseConnection()
class MyFactory(Factory):
protocol = QOTD
def __init__(self,root,name):
self.clients = []
self.root = root
self.name = name
#self.root.add_child(name,self)
def message_siblings(self,message):
self.root.message_children(self.name,message)
def message_sibling(self,message):
self.root.message_child(self.name,message)
def get_message(self,name,message):
#do something here
print name,message
class Container(object):
def __init__(self):
self.servers = {}
def add_child(self,obj,name):
self.servers[name] = obj(self,name)
def message_children(self,name,message):
for server in self.servers:
if server != name:
self.servers[server].get_message(name,message)
def message_child(self,name,message):
if name in self.servers.keys():
self.servers[server].get_message(name,message)
container = Container()
container.add_child(MyFactory,'test')
container.add_child(MyFactory,'test2')
reactor.listenTCP(8007, container.servers['test'])
reactor.listenTCP(8008, container.servers['test2'])
reactor.run()
This may not be the best method but it works and allows for some flexibility
| Sending data received in one Twisted factory to second factory | I am trying to write a simple program using Twisted framework and I am struggling with resolving (or even with imaging how to write it) issue I couldnt find any relevant documentation for:
The main reactor uses two factories, one custom, listening for TCP connections on given port (say, 8000) and second one, to log into given IRC server and channel. On receiving data (simple, one line text) on the factory listening at 8000, I need to pass that data to second factory, so it could be then processed accordingly - either send a message with that text to a channel, or a priv message to some person, thats not really important now. I cant find any way to get the data from first factory and send it to another, for processing (maybe like usual received connection for second IRC factory?).
If this could be somehow resolved, then I would like to add one or even more factories (Jabber for example) to send the received data on port 8000 to all of them at once, to pass it accordingly to protocols (IRC to a channel, Jabber to a contact, and so on).
Is there anyone who met similar issue and is willing to give me some advice or even share some lines of code? Any help will be highly appreciated!
Thanks in advance.
| [
"Factories are just objects. To pass data from one to another, you define and call methods and pass the data as parameter, or set attributes. I think this faq question will help you:\n\nHow do I make input on one connection\n result in output on another?\nThis seems like it's a Twisted\n question, but actually it... | [
6,
0,
0
] | [] | [] | [
"factory",
"irc",
"python",
"twisted",
"xmpp"
] | stackoverflow_0003737885_factory_irc_python_twisted_xmpp.txt |
Q:
How to display an image next to a menu item?
I am trying to get an image to appear next to a menu item but it isn't working.
In order to make this as simple as possible, I have created a very simple example below that highlights the problem:
import pygtk
pygtk.require('2.0')
import gtk
class MenuExample:
def __init__(self):
window = gtk.Window()
window.set_size_request(200, 100)
window.connect("delete_event", lambda w,e: gtk.main_quit())
menu = gtk.Menu()
menu_item = gtk.ImageMenuItem("Refresh")
img = gtk.image_new_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU)
img.show()
menu_item.set_image(img)
menu.append(menu_item)
menu_item.show()
root_menu = gtk.MenuItem("File")
root_menu.show()
root_menu.set_submenu(menu)
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
menu_bar = gtk.MenuBar()
vbox.pack_start(menu_bar, False, False, 2)
menu_bar.show()
menu_bar.append(root_menu)
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
MenuExample()
main()
When I run the application, it shows the menu item, but it does not show the image next to it.
OS: Ubuntu 10.04 64-bit
Python version: 2.6.5
A:
Hmmm... it turns out the answer was that my desktop theme had disabled icons for menus. (Who knows why.)
After enabling the option, the icons now show up.
| How to display an image next to a menu item? | I am trying to get an image to appear next to a menu item but it isn't working.
In order to make this as simple as possible, I have created a very simple example below that highlights the problem:
import pygtk
pygtk.require('2.0')
import gtk
class MenuExample:
def __init__(self):
window = gtk.Window()
window.set_size_request(200, 100)
window.connect("delete_event", lambda w,e: gtk.main_quit())
menu = gtk.Menu()
menu_item = gtk.ImageMenuItem("Refresh")
img = gtk.image_new_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU)
img.show()
menu_item.set_image(img)
menu.append(menu_item)
menu_item.show()
root_menu = gtk.MenuItem("File")
root_menu.show()
root_menu.set_submenu(menu)
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
menu_bar = gtk.MenuBar()
vbox.pack_start(menu_bar, False, False, 2)
menu_bar.show()
menu_bar.append(root_menu)
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
MenuExample()
main()
When I run the application, it shows the menu item, but it does not show the image next to it.
OS: Ubuntu 10.04 64-bit
Python version: 2.6.5
| [
"Hmmm... it turns out the answer was that my desktop theme had disabled icons for menus. (Who knows why.)\nAfter enabling the option, the icons now show up.\n"
] | [
2
] | [] | [] | [
"image",
"menuitem",
"pygtk",
"python"
] | stackoverflow_0003887944_image_menuitem_pygtk_python.txt |
Q:
Changing the active database in django
i'm writing a testing application that i'm using to test the rest of my code base. What i'd like to be able to do for it is when i test using this manage.py command, automatically change to be logging to a different database. is there a good way to do this?
A:
Django automatically creates and drops a test database for you. Unless otherwise specified (we'll see how to in a second) this will be test_ + <the name of the database in the settings file>. So if your settings uses database foo, the tests will be executed against test_foo. No configuration changes are needed for this.
If you wish to execute tests against a custom database (rather than test_foo) you can do that by tweaking the TEST_NAME setting. You can add TEST_NAME to each dictionary in DATABASES.
A:
Create a testing version of settings.py, and specify it on the command line when you run your test:
$ python manage.py test --settings=settings_test
| Changing the active database in django | i'm writing a testing application that i'm using to test the rest of my code base. What i'd like to be able to do for it is when i test using this manage.py command, automatically change to be logging to a different database. is there a good way to do this?
| [
"Django automatically creates and drops a test database for you. Unless otherwise specified (we'll see how to in a second) this will be test_ + <the name of the database in the settings file>. So if your settings uses database foo, the tests will be executed against test_foo. No configuration changes are needed for... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003886298_django_python.txt |
Q:
Can You Use a Single Regular Expression to Parse Function Parameters?
Problem
There is a program file that contains the following code snippet at some point in the file.
...
food($apples$ , $oranges$ , $pears$ , $tomato$){
...
}
...
This function may contain any number of parameters but they must be strings separated by commas. All the parameter strings are lowercase words.
I want to be able to parse out each of the parameters using a regular expression. For example the resulting list in python would be as follows:
["apples", "oranges", "pears", "tomato"]
Attempted Solution
Using the python RE module, I was able to achieve this by breaking the problem into two parts.
Find the function in the code and extract the list of parameters.
plist = re.search(r'food\((.*)\)', programString).group(1)
Split the list using another regular expression.
params = re.findall(r'[a-z]+', plist)
Question
Is there anyway I could achieve this with one regular expression instead of two?
Edit
Thanks to Tim Pietzcker's answer I was able to find some related questions:
Python regular expressions - how to capture multiple groups from a wildcard expression?
Which regex flavors support captures (as opposed to capturing groups)?
A:
To answer your question "Can it be done in a single regex?": Yes, but not in Python.
If you want to match and capture (individually) an unknown number of matches as in your example, using only a single regular expression, then you need a regex engine that supports captures (as opposed to capturing groups). Only .NET and Perl 6 do this currently.
So in Python, you either need to do it in two steps (find the entire food(...) function call, and then findall individual matches with a second regex as suggested by Dingo).
Or use a parser like Paul McGuire's pyparsing.
A:
Pyparsing is handy for this kind of thing, when you don't know when you'll run into extra whitespace, comments, whatever. Like named groups in RE, this example defines the results name 'parameters' which is used to retrieve the desired data:
>>> code = """\
... ...
...
... food($apples$ , $oranges$ , $pears$ , $tomato$){
... ...
... }
... ...
... food($peanuts$, $popcorn$ ,$candybars$ ,$icecream$){
... ...
... }
... """
>>> from pyparsing import *
>>> LPAR,RPAR,LBRACE,RBRACE,DOLLAR = map(Suppress,"(){}$")
>>> param = DOLLAR + Word(alphas) + DOLLAR
>>> funcCall = "food" + LPAR + delimitedList(param)("parameters") + RPAR + LBRACE
>>> for fn in funcCall.searchString(code):
... print fn.parameters
...
['apples', 'oranges', 'pears', 'tomato']
['peanuts', 'popcorn', 'candybars', 'icecream']
If I change the second function to:
... food($peanuts$, $popcorn$ ,/*$candybars$ ,*/$icecream$){
And then add this line:
>>> funcCall.ignore(cStyleComment)
Then I get:
>>> for fn in funcCall.searchString(code):
... print fn.parameters
...
['apples', 'oranges', 'pears', 'tomato']
['peanuts', 'popcorn', 'icecream']
A:
Why regex?
for line in open("file"):
line=line.rstrip()
if line.lstrip().startswith("food") :
for item in line.split(")"):
if "food" in item:
print item.split("(")[-1].split(",")
output
$ ./python.py
['$apples$ ', ' $oranges$ ', ' $pears$ ', ' $tomato$']
A:
params = re.findall(r'\$([a-z]+)\$', programString)
A:
Something like this regex should work
food\((\$(?<parm>\w+)\$\s*,?\s*)+\).*
it puts all the matching parameter names in the 'parm' group
| Can You Use a Single Regular Expression to Parse Function Parameters? | Problem
There is a program file that contains the following code snippet at some point in the file.
...
food($apples$ , $oranges$ , $pears$ , $tomato$){
...
}
...
This function may contain any number of parameters but they must be strings separated by commas. All the parameter strings are lowercase words.
I want to be able to parse out each of the parameters using a regular expression. For example the resulting list in python would be as follows:
["apples", "oranges", "pears", "tomato"]
Attempted Solution
Using the python RE module, I was able to achieve this by breaking the problem into two parts.
Find the function in the code and extract the list of parameters.
plist = re.search(r'food\((.*)\)', programString).group(1)
Split the list using another regular expression.
params = re.findall(r'[a-z]+', plist)
Question
Is there anyway I could achieve this with one regular expression instead of two?
Edit
Thanks to Tim Pietzcker's answer I was able to find some related questions:
Python regular expressions - how to capture multiple groups from a wildcard expression?
Which regex flavors support captures (as opposed to capturing groups)?
| [
"To answer your question \"Can it be done in a single regex?\": Yes, but not in Python.\nIf you want to match and capture (individually) an unknown number of matches as in your example, using only a single regular expression, then you need a regex engine that supports captures (as opposed to capturing groups). Only... | [
3,
2,
2,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0003885653_parsing_python_regex.txt |
Q:
Need help processing upload form with Google App Engine Blobstore
I'm trying to learn the blobstore API... and I'm able to successfully upload files and get them back, but I'm not having any luck trying to combine an upload form with a regular webform to be able to associated extra info with the file, such as a nickname for the file.
Below is the code for a simple app I've been playing with. It's based on the sample google provides.
#!/usr/bin/env python
#
import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class StoredFiles(db.Model):
nickname = db.StringProperty()
blobkey = blobstore.BlobReferenceProperty()
@staticmethod
def get_all():
query = db.Query(StoredFiles)
files = query.get()
return files
def doRender(handler, page, templatevalues=None):
path = os.path.join(os.path.dirname(__file__), page)
handler.response.out.write(template.render(path, templatevalues))
class MainHandler(webapp.RequestHandler):
def get(self):
allfiles = StoredFiles.get_all()
upload_url = blobstore.create_upload_url('/upload')
templatevalues = {
'allfiles': allfiles,
'upload_url': upload_url,
}
doRender(self, 'index.html', templatevalues)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/save/%s' % blob_info.key())
class SaveHandler(webapp.RequestHandler):
def get(self, resource):
newFile = StoredFiles()
newFile.nickname = self.request.get('nickname')
resource = str(urllib.unquote(resource))
newFile.blobkey = resource
newFile.put()
self.redirect('/')
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
('/save/([^/]+)?', SaveHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
According to the docs, the blobstore handler is supposed to pass through the blob key and the rest of the form to the handler its redirected to... blob key is coming through just fine, but nothing else is.
Can someone please point out where I'm messing up or point me to a good tutorial describing this use case?
A:
The problem is that your posted form data is lost when you redirect the request to "/save/%s", which is normal.
Instead of redirecting, you should put your code inside UploadHandler, like this (untested code) :
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
try:
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
newFile = StoredFiles()
newFile.nickname = self.request.get('nickname')
newFile.blobkey = blob_info.key()
newFile.put()
self.redirect('/')
except:
self.redirect('/upload_failure.html')
See this page from the docs for a similar example : http://code.google.com/appengine/docs/python/tools/webapp/blobstorehandlers.html#BlobstoreUploadHandler
| Need help processing upload form with Google App Engine Blobstore | I'm trying to learn the blobstore API... and I'm able to successfully upload files and get them back, but I'm not having any luck trying to combine an upload form with a regular webform to be able to associated extra info with the file, such as a nickname for the file.
Below is the code for a simple app I've been playing with. It's based on the sample google provides.
#!/usr/bin/env python
#
import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class StoredFiles(db.Model):
nickname = db.StringProperty()
blobkey = blobstore.BlobReferenceProperty()
@staticmethod
def get_all():
query = db.Query(StoredFiles)
files = query.get()
return files
def doRender(handler, page, templatevalues=None):
path = os.path.join(os.path.dirname(__file__), page)
handler.response.out.write(template.render(path, templatevalues))
class MainHandler(webapp.RequestHandler):
def get(self):
allfiles = StoredFiles.get_all()
upload_url = blobstore.create_upload_url('/upload')
templatevalues = {
'allfiles': allfiles,
'upload_url': upload_url,
}
doRender(self, 'index.html', templatevalues)
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
self.redirect('/save/%s' % blob_info.key())
class SaveHandler(webapp.RequestHandler):
def get(self, resource):
newFile = StoredFiles()
newFile.nickname = self.request.get('nickname')
resource = str(urllib.unquote(resource))
newFile.blobkey = resource
newFile.put()
self.redirect('/')
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
('/save/([^/]+)?', SaveHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
According to the docs, the blobstore handler is supposed to pass through the blob key and the rest of the form to the handler its redirected to... blob key is coming through just fine, but nothing else is.
Can someone please point out where I'm messing up or point me to a good tutorial describing this use case?
| [
"The problem is that your posted form data is lost when you redirect the request to \"/save/%s\", which is normal.\nInstead of redirecting, you should put your code inside UploadHandler, like this (untested code) :\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n try:\n... | [
4
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0003887535_blobstore_google_app_engine_python.txt |
Q:
How to return and use an array of strings from a jQuery ajax call?
I'm using Google App Engine (Python) along with jQuery for Ajax calls to the server. I have a page where I want to load up a list of strings in Javascript from an Ajax call to the server.
The server method I want to invoke:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
// TODO: How to return these ids to the invoking ajax call?
self.response.out.write(ids_to_return)
The HTML page where I want to be able to access the returned ids:
var strings_from_server = new Array();
$.ajax({
type: "GET",
url: "/get_ids.html",
success: function(responseText){
// TODO: How to read these IDS in here?
strings_from_server = responseText
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
My experience with Ajax is limited-- I've only used them to store data to the server (a-la POST commands) and so I really have no idea how to get data back from the server. Thanks in advance for all help
Edit: My final answer:
I've switched to a full Ajax call (to prevent from cross-domain requests) and also to handle 'error' callbacks. My working client method looks like:
$.ajax({
type: "GET",
dataType: "json",
url: "/get_ids.html",
success: function(reponseText){
strings_from_server = responseText
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
Note I specify the dataType as 'json'.
And my final server function, with sahid's answer, looks like:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
# Note: I have to map all my objects as `str` objects
response_json = simplejson.dumps(map(str, ids_to_return))
self.response.out.write(response_json)
Thanks all!
A:
The SDK of Google AppEngine provided by django the lib "simplejson".
from django.utils import simplejson
So your handler maybe it simply:
from django.utils import simplejson
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
response_json = simplejson.dumps (ids_to_return)
self.response.out.write(response_json)
There are a good article about ajax/rpc: http://code.google.com/appengine/articles/rpc.html
A:
It's probably not the cleanest solution, but it will work. Since they are just IDs, it sounds like it's safe to push them directly into a string.
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
response_html = '["'
response_html += ids_to_return.join('","')
# Edit: since my ids are Key objects (not strings)
# I had to use the following instead:
# response_html += '","'.join(map(str, ids_to_return))
response_html += '"]'
self.response.out.write(response_html)
and
var strings_from_server = new Array();
$.getJSON("/get_ids.html", function(responseData){
strings_from_server = responseData;
});
You can check to see if the response was empty incase of an error, and you can use $.each to loop through the results.
I am using jQuerys getJSON feature to automatically parse the response. Since I'm just returning a json list, it will generate the array of data in the strings_from_server variable.
| How to return and use an array of strings from a jQuery ajax call? | I'm using Google App Engine (Python) along with jQuery for Ajax calls to the server. I have a page where I want to load up a list of strings in Javascript from an Ajax call to the server.
The server method I want to invoke:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
// TODO: How to return these ids to the invoking ajax call?
self.response.out.write(ids_to_return)
The HTML page where I want to be able to access the returned ids:
var strings_from_server = new Array();
$.ajax({
type: "GET",
url: "/get_ids.html",
success: function(responseText){
// TODO: How to read these IDS in here?
strings_from_server = responseText
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
My experience with Ajax is limited-- I've only used them to store data to the server (a-la POST commands) and so I really have no idea how to get data back from the server. Thanks in advance for all help
Edit: My final answer:
I've switched to a full Ajax call (to prevent from cross-domain requests) and also to handle 'error' callbacks. My working client method looks like:
$.ajax({
type: "GET",
dataType: "json",
url: "/get_ids.html",
success: function(reponseText){
strings_from_server = responseText
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
Note I specify the dataType as 'json'.
And my final server function, with sahid's answer, looks like:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
# Note: I have to map all my objects as `str` objects
response_json = simplejson.dumps(map(str, ids_to_return))
self.response.out.write(response_json)
Thanks all!
| [
"The SDK of Google AppEngine provided by django the lib \"simplejson\".\nfrom django.utils import simplejson\nSo your handler maybe it simply:\nfrom django.utils import simplejson\nclass BrowseObjects(webapp.RequestHandler):\n def get(self):\n ids_to_return = get_ids_to_return()\n response_json = si... | [
6,
3
] | [] | [] | [
"ajax",
"google_app_engine",
"javascript",
"jquery",
"python"
] | stackoverflow_0003887266_ajax_google_app_engine_javascript_jquery_python.txt |
Q:
pythonic way to optimize the logic to filter/extract data from list
I have a list like below:
['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))',
'3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))',
'5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen))',
'7 (UID 3243 FLAGS (\\Seen))', '8 (UID 3244 FLAGS (\\Seen))',
'9 (UID 3245 FLAGS (\\Seen))', '10 (UID 3247 FLAGS (\\Seen))',
'11 (UID 3252 FLAGS (\\Seen))', '12 (UID 3253 FLAGS (\\Deleted))',
'13 (UID 3254 FLAGS ())', '14 (UID 3256 FLAGS (\\Seen))', '15 (UID 3304 FLAGS ())',
'16 (UID 3318 FLAGS (\\Seen))', '17 (UID 3430 FLAGS (\\Seen))',
'18 (UID 3431 FLAGS ())', '19 (UID 3434 FLAGS (\\Seen))',
'20 (UID 3447 FLAGS (-FLAGS \\Seen +FLAGS))', '21 (UID 3478 FLAGS ())',
'22 (UID 3479 FLAGS ())', '23 (UID 3480 FLAGS ())', '24 (UID 3481 FLAGS ())']
From this list i want Three different list as a result. I want result using single iteration on list.
list of all uids i.e [3234,3235,3236,3237,3241 .....]
list of Seen uids i.e [3234,3235 ...] <-- uid of item which has \Seen Flag
list of deleted uids i.e [3236,3253] <-- uid of item which has \Deleted Flag
A:
The best thing to do would be to turn your data into a dict mapping UID to FLAGS, then searching it will be easy. So the data will look something like this:
{'3254': '', '3304': '', '3236': '\\Deleted', '3237': '-FLAGS \\Seen +FLAGS', '3234': 'seen \\Seen', '3235': '\\Seen', '3430': '\\Seen', '3431': '', '3252': '\\Seen', '3253':'\\Deleted', '3478': '', '3479': '', '3256': '\\Seen', '3481': '', '3480': '', '3318': '\\Seen', '3434': '\\Seen', '3243': '\\Seen', '3242': '\\Seen', '3241': '-FLAGS \\Seen +FLAGS', '3247': '\\Seen', '3245': '\\Seen', '3244': '\\Seen', '3447': '-FLAGS \\Seen +FLAGS'}
You can do this using a Regular Expression to match each entry in the list. If we get the regexp to return two groups in the match we can easily build the dict.
So we end up with something like this:
items = ['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))', '3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))', '5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen))', '7 (UID 3243 FLAGS (\\Seen))', '8 (UID 3244 FLAGS (\\Seen))', '9 (UID 3245 FLAGS (\\Seen))', '10 (UID 3247 FLAGS (\\Seen))', '11 (UID 3252 FLAGS (\\Seen))', '12 (UID 3253 FLAGS (\\Deleted))', '13 (UID 3254 FLAGS ())', '14 (UID 3256 FLAGS (\\Seen))', '15 (UID 3304 FLAGS ())', '16 (UID 3318 FLAGS (\\Seen))', '17 (UID 3430 FLAGS (\\Seen))', '18 (UID 3431 FLAGS ())', '19 (UID 3434 FLAGS (\\Seen))', '20 (UID 3447 FLAGS (-FLAGS \\Seen +FLAGS))', '21 (UID 3478 FLAGS ())', '22 (UID 3479 FLAGS ())', '23 (UID 3480 FLAGS ())', '24 (UID 3481 FLAGS ())']
import re
pattern = re.compile(r"\d+ \(UID (\d+) FLAGS \(([^)]*)\)\)")
values = dict(pattern.match(item).groups() for item in items)
We can then easily query the items in values to get what you want:
print "All UIDs:",values.keys()
print "Seen UIDs:",[uid for uid,flags in values.iteritems() if r"\Seen" in flags]
print "Deleted UIDs:",[uid for uid,flags in values.iteritems() if r"\Deleted" in flags]
A:
import re
data = ['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))',
'3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))',
'5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen))',
'7 (UID 3243 FLAGS (\\Seen))', '8 (UID 3244 FLAGS (\\Seen))',
'9 (UID 3245 FLAGS (\\Seen))', '10 (UID 3247 FLAGS (\\Seen))',
'11 (UID 3252 FLAGS (\\Seen))', '12 (UID 3253 FLAGS (\\Deleted))',
'13 (UID 3254 FLAGS ())', '14 (UID 3256 FLAGS (\\Seen))', '15 (UID 3304 FLAGS ())',
'16 (UID 3318 FLAGS (\\Seen))', '17 (UID 3430 FLAGS (\\Seen))',
'18 (UID 3431 FLAGS ())', '19 (UID 3434 FLAGS (\\Seen))',
'20 (UID 3447 FLAGS (-FLAGS \\Seen +FLAGS))', '21 (UID 3478 FLAGS ())',
'22 (UID 3479 FLAGS ())', '23 (UID 3480 FLAGS ())', '24 (UID 3481 FLAGS ())']
r = re.compile('\d+\s\(UID\s(?P<uid>\d+)\sFLAGS\s\((?P<data>.*)\)\)')
uid_list = []
seen_uid_list = []
deleted_uid_list = []
for s in data:
m = r.match(s)
if m:
uid_list.append(m.group('uid'))
if m.group('data').rfind('Seen') > 0: seen_uid_list.append(m.group('uid'))
if m.group('data').rfind('Deleted') > 0: deleted_uid_list.append(m.group('uid'))
print uid_list
print seen_uid_list
print deleted_uid_list
A:
I'm not sure about list comprehensions since those usually map one list to another (using either filtering or mapping). I've not seen them being used to split lists. However, you could do this with a combination of a genexp and a loop in a single iteration. I've blown this up a little so that it's clear.
import re
grepper = re.compile(r'[0-9]+ \(UID (?P<uid>[0-9]+) FLAGS (?P<flags>\(.*\))\)')
t = [..] #your list
items = (grepper.search(m).groupdict() for m in t)
all = []
seen = []
deleted = []
for i in items:
if "Seen" in i:
seen.append(i["uid"])
if "Deleted" in i:
deleted.append(i["uid"])
all.append(i["uid"])
You should have your 3 lists now.
A:
all,deleted,seen = [list(filter(None, a)) for a in \
zip(*map(lambda a: (a[2], '\Deleted' in a[-1] and a[2], '\Seen' in a[-1] and a[2]), map(lambda a: a.split(' '), items)))]
which will be faster using re or without re - you need to check with timeit !!!
A:
This one works for your data sample....
uids, seen, deleted = [], [], []
for item in myList:
uids.append(int(item[7:12]))
if 'Se' in item[20:]: seen.append(uids[-1])
elif 'De' in item[20:]: deleted.append(uids[-1])
A:
all=[]
seen=[]
deleted=[]
for item in alist:
s=item.split(" ",4)
all.append(s[2])
if "seen" in s[-1].lower():
seen.append(s[2])
elif "delete" in s[-1].lower():
deleted.append(s[2])
A:
The only way I can think of of doing it in one iteration generating the three lists you ask, is by iterating manually. No python magic I can come up with.
You can easily improve this if you know specifics about the format and how it's generated. I don't know why +FLAGS and -FLAGS in some items, for example, and didn't know when to expect parenthesis, so I had to use find(). Also, I could've just split() the string in two, but then again, I don't know what the flag format means,...
def parseList(l):
lall = []
lseen = []
ldeleted = []
for item in l:
spl = item.split()
uid = int(spl[2])
lall.append(uid)
for word in spl[4:]:
if word.find("\Seen") != -1:
lseen.append(uid)
elif word.find("\Deleted") != -1:
ldeleted.append(uid)
return lall, lseen, ldeleted
| pythonic way to optimize the logic to filter/extract data from list | I have a list like below:
['1 (UID 3234 FLAGS (seen \\Seen))', '2 (UID 3235 FLAGS (\\Seen))',
'3 (UID 3236 FLAGS (\\Deleted))', '4 (UID 3237 FLAGS (-FLAGS \\Seen +FLAGS))',
'5 (UID 3241 FLAGS (-FLAGS \\Seen +FLAGS))', '6 (UID 3242 FLAGS (\\Seen))',
'7 (UID 3243 FLAGS (\\Seen))', '8 (UID 3244 FLAGS (\\Seen))',
'9 (UID 3245 FLAGS (\\Seen))', '10 (UID 3247 FLAGS (\\Seen))',
'11 (UID 3252 FLAGS (\\Seen))', '12 (UID 3253 FLAGS (\\Deleted))',
'13 (UID 3254 FLAGS ())', '14 (UID 3256 FLAGS (\\Seen))', '15 (UID 3304 FLAGS ())',
'16 (UID 3318 FLAGS (\\Seen))', '17 (UID 3430 FLAGS (\\Seen))',
'18 (UID 3431 FLAGS ())', '19 (UID 3434 FLAGS (\\Seen))',
'20 (UID 3447 FLAGS (-FLAGS \\Seen +FLAGS))', '21 (UID 3478 FLAGS ())',
'22 (UID 3479 FLAGS ())', '23 (UID 3480 FLAGS ())', '24 (UID 3481 FLAGS ())']
From this list i want Three different list as a result. I want result using single iteration on list.
list of all uids i.e [3234,3235,3236,3237,3241 .....]
list of Seen uids i.e [3234,3235 ...] <-- uid of item which has \Seen Flag
list of deleted uids i.e [3236,3253] <-- uid of item which has \Deleted Flag
| [
"The best thing to do would be to turn your data into a dict mapping UID to FLAGS, then searching it will be easy. So the data will look something like this:\n{'3254': '', '3304': '', '3236': '\\\\Deleted', '3237': '-FLAGS \\\\Seen +FLAGS', '3234': 'seen \\\\Seen', '3235': '\\\\Seen', '3430': '\\\\Seen', '3431': '... | [
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"filtering",
"python"
] | stackoverflow_0003889038_filtering_python.txt |
Q:
How do I get access to the request object when validating a django.contrib.comments form?
I would like to run a check on the IP-adress when users post with django comments.
I can easily override and customize the form used by django.comments, but I need access to the request object to add an IP-test to its clean(). Is it possible to get access to this in a clean way?
An alternative could be to check the IP when recieving the save signal, but then the only way to abort the save seems to be returning a code 400 to the user.
A:
The comments framework provides a comment_will_be_posted signal:
http://docs.djangoproject.com/en/1.2/ref/contrib/comments/signals/#comment-will-be-posted
If you register at this signal, your handler will be passed the (not yet saved) comment object and the request as arguments. If your handler returns False, the post_comment view answers with CommentPostBadRequest, as it does on any other sort of error like failed form validation.
A:
One possible way, but you still do not have request object in this level of validation...
class SomeForm(forms.ModelForm):
somefield = forms.CharField(...)
def check_somefield(self):
somefield = self.cleaned_data['somefield']
... #do what you want
return somefield
Hope this can help, or i do not understand what you want correctly.
A:
I think this is the answer to your question:
How do I access the request object or any other variable in a form's clean() method?
| How do I get access to the request object when validating a django.contrib.comments form? | I would like to run a check on the IP-adress when users post with django comments.
I can easily override and customize the form used by django.comments, but I need access to the request object to add an IP-test to its clean(). Is it possible to get access to this in a clean way?
An alternative could be to check the IP when recieving the save signal, but then the only way to abort the save seems to be returning a code 400 to the user.
| [
"The comments framework provides a comment_will_be_posted signal:\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/comments/signals/#comment-will-be-posted\nIf you register at this signal, your handler will be passed the (not yet saved) comment object and the request as arguments. If your handler returns False, th... | [
1,
0,
0
] | [] | [] | [
"comments",
"django",
"python"
] | stackoverflow_0003888322_comments_django_python.txt |
Q:
Using Python code coverage tool for understanding and pruning back source code of a large library
My project targets a low-cost and low-resource embedded device. I am dependent on a relatively large and sprawling Python code base, of which my use of its APIs is quite specific.
I am keen to prune the code of this library back to its bare minimum, by executing my test suite within a coverage tools like Ned Batchelder's coverage or figleaf, then scripting removal of unused code within the various modules/files. This will help not only with understanding the libraries' internals, but also make writing any patches easier. Ned actually refers to the use of coverage tools to "reverse engineer" complex code in one of his online talks.
My question to the SO community is whether people have experience of using coverage tools in this way that they wouldn't mind sharing? What are the pitfalls if any? Is the coverage tool a good choice? Or would I be better off investing my time with figleaf?
The end-game is to be able to automatically generate a new source tree for the library, based on the original tree, but only including the code actually used when I run nosetests.
If anyone has developed a tool that does a similar job for their Python applications and libraries, it would be terrific to get a baseline from which to start development.
Hopefully my description makes sense to readers...
A:
What you want isn't "test coverage", it is the transitive closure of "can call" from the root of the computation. (In threaded applications, you have to include "can fork").
You want to designate some small set (perhaps only 1) of functions that make up the entry points of your application, and want to trace through all possible callees (conditional or unconditional) of that small set. This is the set of functions you must have.
Python makes this very hard in general (IIRC, I'm not a deep Python expert) because of dynamic dispatch and especially due to "eval". Reasoning about what function can get called can be pretty tricky for a static analyzers applied to highly dynamic languages.
One might use test coverage as a way to seed the "can call" relation with specific "did call" facts; that could catch a lot of dynamic dispatches (dependent on your test suite coverage). Then the result you want is the transitive closure of "can or did" call. This can still be erroneous, but is likely to be less so.
Once you get a set of "necessary" functions, the next problem will be removing the unnecessary functions from the source files you have. If the number of files you start with is large, the manual effort to remove the dead stuff may be pretty high. Worse, you're likely to revise your application, and then the answer as to what to keep changes. So for every change (release), you need to reliably recompute this answer.
My company builds a tool that does this analysis for Java packages (with appropriate caveats regarding dynamic loads and reflection): the input is a set of Java files and (as above) a designated set of root functions. The tool computes the call graph, and also finds all dead member variables and produces two outputs: a) the list of purportedly dead methods and members, and b) a revised set of files with all the "dead" stuff removed. If you believe a), then you use b). If you think a) is wrong, then you add elements listed in a) to the set of roots and repeat the analysis until you think a) is right. To do this, you need a static analysis tool that parse Java, compute the call graph, and then revise the code modules to remove the dead entries. The basic idea applies to any language.
You'd need a similar tool for Python, I'd expect.
Maybe you can stick to just dropping files that are completely unused, although that may still be a lot of work.
A:
As others have pointed out, coverage can tell you what code has been executed. The trick for you is to be sure that your test suite truly exercises the code fully. The failure case here is over-pruning because your tests skipped some code that will really be needed in production.
Be sure to get the latest version of coverage.py (v3.4): it adds a new feature to indicate files that are never executed at all.
BTW:: for a first cut prune, Python provides a neat trick: remove all the .pyc files in your source tree, then run your tests. Files that still have no .pyc file were clearly not executed!
A:
I haven't used coverage for pruning out, but it seems like it should do well. I've used the combination of nosetests + coverage, and it worked better for me than figleaf. In particular, I found the html report from nosetests+coverage to be helpful -- this should be helpful to you in understanding where the unused portions of the library are.
| Using Python code coverage tool for understanding and pruning back source code of a large library | My project targets a low-cost and low-resource embedded device. I am dependent on a relatively large and sprawling Python code base, of which my use of its APIs is quite specific.
I am keen to prune the code of this library back to its bare minimum, by executing my test suite within a coverage tools like Ned Batchelder's coverage or figleaf, then scripting removal of unused code within the various modules/files. This will help not only with understanding the libraries' internals, but also make writing any patches easier. Ned actually refers to the use of coverage tools to "reverse engineer" complex code in one of his online talks.
My question to the SO community is whether people have experience of using coverage tools in this way that they wouldn't mind sharing? What are the pitfalls if any? Is the coverage tool a good choice? Or would I be better off investing my time with figleaf?
The end-game is to be able to automatically generate a new source tree for the library, based on the original tree, but only including the code actually used when I run nosetests.
If anyone has developed a tool that does a similar job for their Python applications and libraries, it would be terrific to get a baseline from which to start development.
Hopefully my description makes sense to readers...
| [
"What you want isn't \"test coverage\", it is the transitive closure of \"can call\" from the root of the computation. (In threaded applications, you have to include \"can fork\").\nYou want to designate some small set (perhaps only 1) of functions that make up the entry points of your application, and want to tra... | [
9,
2,
0
] | [] | [] | [
"code_analysis",
"code_coverage",
"python",
"reverse_engineering"
] | stackoverflow_0003883484_code_analysis_code_coverage_python_reverse_engineering.txt |
Q:
Why is tempfile using DOS 8.3 directory names on my XP box?
>>> import tempfile
>>> tempfile.mkstemp()
(3, 'c:\\docume~1\\k0811260\\locals~1\\temp\\tmpk6tpd3')
It works, but looks a bit strange. and the actual temporary file name is more than 8 letters.
Why doesn't it use long file names instead?
A:
mkstemp uses the environment variables TMPDIR, TEMP or TMP (the first one that is set) to determine where to put your temporary file. One of these is probably set to c:\docume~1\k0811260\locals~1\temp on your system. Issue
echo %%tmp%%
etc. in a command window ("DOS box") to find out for sure.
Which, in fact, is a good thing because some naïve modules/programs (e.g., those that call external OS commands) may get confused when a directory name contains a space, due to quoting issues.
| Why is tempfile using DOS 8.3 directory names on my XP box? | >>> import tempfile
>>> tempfile.mkstemp()
(3, 'c:\\docume~1\\k0811260\\locals~1\\temp\\tmpk6tpd3')
It works, but looks a bit strange. and the actual temporary file name is more than 8 letters.
Why doesn't it use long file names instead?
| [
"mkstemp uses the environment variables TMPDIR, TEMP or TMP (the first one that is set) to determine where to put your temporary file. One of these is probably set to c:\\docume~1\\k0811260\\locals~1\\temp on your system. Issue\necho %%tmp%%\n\netc. in a command window (\"DOS box\") to find out for sure.\nWhich, in... | [
3
] | [] | [] | [
"python",
"temporary_files"
] | stackoverflow_0003890233_python_temporary_files.txt |
Q:
How to stream my webcam through my site?
Is it possible to stream my webcam form my local machine that's connected to the internet to show up on my website without using any media server or something similar?
A:
You could do it with some kind of java applet or flash/silverlight application, just look at sites like "chat roulette"
A:
If you are wanting for other people to see it, then no.
Web pages have two scopes: Client and Server. Something running on one Client (user) cannot be shown to other Clients (users) without it being on the Server.
You can use things like UStream, but I would expect that they are using a media server or something similar on the back end to show the stream to other clients (users).
| How to stream my webcam through my site? | Is it possible to stream my webcam form my local machine that's connected to the internet to show up on my website without using any media server or something similar?
| [
"You could do it with some kind of java applet or flash/silverlight application, just look at sites like \"chat roulette\"\n",
"If you are wanting for other people to see it, then no.\nWeb pages have two scopes: Client and Server. Something running on one Client (user) cannot be shown to other Clients (users) wit... | [
1,
0
] | [] | [] | [
"python",
"webcam"
] | stackoverflow_0003890271_python_webcam.txt |
Q:
Building tree structure from flat list derived from zope catalog call without recursion
I have all objects which get looked up to provide interpreter with both parents objects and object subobjects. I hope to do this without recursion for zope not appreciating this conventional recursion.
I set the view context as root object for recursion to start attaching object on then iterate across this filtered list of intid/objects looking for object that has this object as parent. From there I seek starter code with hopes someone help me.
A:
Maybe this little trick will be usefull for you as it was for me.
You can restrict your search results by PathIndex (getPhysicalPath) and then just sort it alphabetically:
lst = context.Catalog.searchResults(path='/parentNodeId')
lst.sort()
print lst
You will see something like this:
# /parentNodeId/
# /parentNodeId/folder/
# /parentNodeId/folder/file1.jpg
# /parentNodeId/folder/file2.jpg
# /parentNodeId/folder/file1.jpg
# /parentNodeId/folder2/
# /parentNodeId/folder3/
# /parentNodeId/folder3/file1.jpg
# /parentNodeId/folder3/file2.jpg
I think from this output you can easy build a tree structure
| Building tree structure from flat list derived from zope catalog call without recursion | I have all objects which get looked up to provide interpreter with both parents objects and object subobjects. I hope to do this without recursion for zope not appreciating this conventional recursion.
I set the view context as root object for recursion to start attaching object on then iterate across this filtered list of intid/objects looking for object that has this object as parent. From there I seek starter code with hopes someone help me.
| [
"Maybe this little trick will be usefull for you as it was for me.\nYou can restrict your search results by PathIndex (getPhysicalPath) and then just sort it alphabetically:\nlst = context.Catalog.searchResults(path='/parentNodeId')\nlst.sort()\nprint lst\n\nYou will see something like this:\n# /parentNodeId/\n# /p... | [
1
] | [] | [] | [
"plone",
"python",
"recursion",
"zope"
] | stackoverflow_0003774874_plone_python_recursion_zope.txt |
Q:
add properties to users google app engine
What is the best way to save a user profile with Google App Engine (Python) ?
What I did to solve this problem is create another Model, with a UserProperty, but requesting the profile from the user I have to do something like this:
if user:
profile = Profile.all().filter('user =', user).fetch(1)
if profile:
property = s.get().property
Any ideas?
A:
If you make the user_id of the user the key_name of the user's Profile entity, you can fetch it using Profile.get_by_key_name(), which will be faster than querying and then fetching.
Memcaching including the user_id as part of the key will allow even faster access to the profile.
A:
No, this is a pretty correct approach (though you might want to also store some of those profiles in memcache, of course;-). It's going to be fast, since there will be an index on the user field. You sure can't modify the Google-supplied user model, if that's what you're asking.
A:
This is not a solution but a warning.
user value is not a unique and stable identifier for a User. And the user_id property only exists for google users not for OpenId. So don't trust this solution.
| add properties to users google app engine | What is the best way to save a user profile with Google App Engine (Python) ?
What I did to solve this problem is create another Model, with a UserProperty, but requesting the profile from the user I have to do something like this:
if user:
profile = Profile.all().filter('user =', user).fetch(1)
if profile:
property = s.get().property
Any ideas?
| [
"If you make the user_id of the user the key_name of the user's Profile entity, you can fetch it using Profile.get_by_key_name(), which will be faster than querying and then fetching.\nMemcaching including the user_id as part of the key will allow even faster access to the profile.\n",
"No, this is a pretty corre... | [
4,
1,
1
] | [] | [] | [
"google_app_engine",
"profiling",
"python"
] | stackoverflow_0002504748_google_app_engine_profiling_python.txt |
Q:
quick question: clear an attribute of a model in django
i think this is a pretty easy question for you.
I want to clear an attribute of a django-model.
If i have something like this:
class Book(models.Model):
name = models.TextField()
pages = models.IntegerField()
img = models.ImageField()
In an abstract function i want to clear an attribute, but at that time i don't know what type the field has. So examples would be name="", pages=0 or img=None.. Is there a way to do it in a generic way? I search something like SET_TO_EMPTY(book,"pages")
Do you know a function like that?
many thanks in advance!
A:
I don't think there is a clean way of doing it. However, assuming you've set a default value (which you don't have) you can do it like this:
book.img = book._meta.get_field('img').default
Do note that your current model won't allow a None value. To allow those you have to set null=True and blank=True. For pages you need a default=0.
| quick question: clear an attribute of a model in django | i think this is a pretty easy question for you.
I want to clear an attribute of a django-model.
If i have something like this:
class Book(models.Model):
name = models.TextField()
pages = models.IntegerField()
img = models.ImageField()
In an abstract function i want to clear an attribute, but at that time i don't know what type the field has. So examples would be name="", pages=0 or img=None.. Is there a way to do it in a generic way? I search something like SET_TO_EMPTY(book,"pages")
Do you know a function like that?
many thanks in advance!
| [
"I don't think there is a clean way of doing it. However, assuming you've set a default value (which you don't have) you can do it like this:\nbook.img = book._meta.get_field('img').default\n\nDo note that your current model won't allow a None value. To allow those you have to set null=True and blank=True. For page... | [
1
] | [] | [] | [
"django",
"model",
"python"
] | stackoverflow_0003890525_django_model_python.txt |
Q:
Filter results for Django paginator in template
I'm filtering out results from my page_obj in a generic view to only show entries published in the same language as the languge currently set by django-cms (http://www.django-cms.org/en/documentation/2.0/i18n/).
This works fine, but adding in support for Django pagination (http://docs.djangoproject.com/en/1.2/topics/pagination/) causes the filtered results to still be counted. So, for example when there are three results in English, from a total of ten results and pagination is set to 2, I'll get 5 result pages, most of which are of course blank becuse the filtering of the remaining seven is done in the template.
Can I amend Django Paginator to work with the filter in the template using a template tag, or do I have to rebuild my views? If so, how do I go about doing that?
The relevant code:
managers.py
def update_queryset(view, queryset, queryset_parameter='queryset'):
'''Decorator around views based on a queryset passed in parameter, which will force the update of the queryset before executing the view.
Related to issue: http://code.djangoproject.com/ticket/8378'''
def wrap(*args, **kwargs):
#Regenerate the queryset before passing it to the view.
kwargs[queryset_parameter] = queryset()
return view(*args, **kwargs)
return wrap
views/entries.py
from django.views.generic.list_detail import object_list
from cmsplugin_publisher.models import Entry
from cmsplugin_publisher.managers import update_queryset
entry_index = update_queryset(object_list, Entry.published.all)
urls/entries.py
from django.conf.urls.defaults import *
from cmsplugin_publisher.models import Entry
from cmsplugin_publisher.settings import PAGINATION, ALLOW_EMPTY, ALLOW_FUTURE
entry_conf_list = {'queryset': Entry.published.all(), 'paginate_by': PAGINATION}
entry_conf = { 'queryset': Entry.published.all(),}
entry_conf_detail = entry_conf.copy()
entry_conf_detail['queryset'] = Entry.objects.all()
urlpatterns = patterns('cmsplugin_publisher.views.entries',
url(r'^$', 'entry_index', entry_conf_list, name='cmsplugin_publisher_entry_archive_index'),
url(r'^(?P<page>[0-9]+)/$', 'entry_index', entry_conf_list, name='cmsplugin_publisher_entry_archive_index_paginated'),
)
urlpatterns += patterns('django.views.generic.list_detail',
url(r'^(?P<slug>[-\w]+)/$', 'object_detail', entry_conf_detail, name='cmsplugin_publisher_entry_detail'),
)
in entry_list.html
{% block content %}
{% for object in object_list %}
{% ifequal object.language current_language %}
..
{% endifequal %}
{% endfor %}
{% if is_paginated %}
<ul id="pagination">
{% if page_obj.has_previous %}
{% ifnotequal page_obj.start_index 1 %}<li><a href="../" title="{% trans 'View Latest Entries' %}">{% trans 'Latest Entries' %}</a></li>{% endifnotequal %}
{% ifequal page_obj.previous_page_number 1 %}{% endifequal %}
{% ifnotequal page_obj.previous_page_number 1 %}
<li><a href="../{{ page_obj.previous_page_number }}/" title="{% trans 'View Earlier Entries' %}">{% trans 'Earlier Entries' %}</a></li>
{% endifnotequal %}
{% else%}
{% endif %}
<li>{% trans 'Page' %} {{ page_obj.start_index }} {% trans 'of' %} {{ paginator.num_pages }} {% trans 'Entries' %}</li>
{% if page_obj.has_next %}
{% ifnotequal page_obj.start_index 1 %}
<li><a href="../{{ page_obj.next_page_number }}/" title="{% trans 'View Older Entries' %}">{% trans 'Older Entries' %}</a></li>
{% endifnotequal %}
{% ifequal page_obj.start_index 1 %}
<li><a href="{{ page_obj.next_page_number }}/" title="{% trans 'View Older Entries' %}">{% trans 'Older Entries' %}</a></li>
{% endifequal %}
{% else%}
{% endif %}
</ul>
{% endif %}
I'd appreciate any light you guys can throw on the best solution here.
A:
The soultion, ultimately, was to rebuild the views. Extensive rebuilding required in this case.
Moral of the sory: don't filter in templates!
| Filter results for Django paginator in template | I'm filtering out results from my page_obj in a generic view to only show entries published in the same language as the languge currently set by django-cms (http://www.django-cms.org/en/documentation/2.0/i18n/).
This works fine, but adding in support for Django pagination (http://docs.djangoproject.com/en/1.2/topics/pagination/) causes the filtered results to still be counted. So, for example when there are three results in English, from a total of ten results and pagination is set to 2, I'll get 5 result pages, most of which are of course blank becuse the filtering of the remaining seven is done in the template.
Can I amend Django Paginator to work with the filter in the template using a template tag, or do I have to rebuild my views? If so, how do I go about doing that?
The relevant code:
managers.py
def update_queryset(view, queryset, queryset_parameter='queryset'):
'''Decorator around views based on a queryset passed in parameter, which will force the update of the queryset before executing the view.
Related to issue: http://code.djangoproject.com/ticket/8378'''
def wrap(*args, **kwargs):
#Regenerate the queryset before passing it to the view.
kwargs[queryset_parameter] = queryset()
return view(*args, **kwargs)
return wrap
views/entries.py
from django.views.generic.list_detail import object_list
from cmsplugin_publisher.models import Entry
from cmsplugin_publisher.managers import update_queryset
entry_index = update_queryset(object_list, Entry.published.all)
urls/entries.py
from django.conf.urls.defaults import *
from cmsplugin_publisher.models import Entry
from cmsplugin_publisher.settings import PAGINATION, ALLOW_EMPTY, ALLOW_FUTURE
entry_conf_list = {'queryset': Entry.published.all(), 'paginate_by': PAGINATION}
entry_conf = { 'queryset': Entry.published.all(),}
entry_conf_detail = entry_conf.copy()
entry_conf_detail['queryset'] = Entry.objects.all()
urlpatterns = patterns('cmsplugin_publisher.views.entries',
url(r'^$', 'entry_index', entry_conf_list, name='cmsplugin_publisher_entry_archive_index'),
url(r'^(?P<page>[0-9]+)/$', 'entry_index', entry_conf_list, name='cmsplugin_publisher_entry_archive_index_paginated'),
)
urlpatterns += patterns('django.views.generic.list_detail',
url(r'^(?P<slug>[-\w]+)/$', 'object_detail', entry_conf_detail, name='cmsplugin_publisher_entry_detail'),
)
in entry_list.html
{% block content %}
{% for object in object_list %}
{% ifequal object.language current_language %}
..
{% endifequal %}
{% endfor %}
{% if is_paginated %}
<ul id="pagination">
{% if page_obj.has_previous %}
{% ifnotequal page_obj.start_index 1 %}<li><a href="../" title="{% trans 'View Latest Entries' %}">{% trans 'Latest Entries' %}</a></li>{% endifnotequal %}
{% ifequal page_obj.previous_page_number 1 %}{% endifequal %}
{% ifnotequal page_obj.previous_page_number 1 %}
<li><a href="../{{ page_obj.previous_page_number }}/" title="{% trans 'View Earlier Entries' %}">{% trans 'Earlier Entries' %}</a></li>
{% endifnotequal %}
{% else%}
{% endif %}
<li>{% trans 'Page' %} {{ page_obj.start_index }} {% trans 'of' %} {{ paginator.num_pages }} {% trans 'Entries' %}</li>
{% if page_obj.has_next %}
{% ifnotequal page_obj.start_index 1 %}
<li><a href="../{{ page_obj.next_page_number }}/" title="{% trans 'View Older Entries' %}">{% trans 'Older Entries' %}</a></li>
{% endifnotequal %}
{% ifequal page_obj.start_index 1 %}
<li><a href="{{ page_obj.next_page_number }}/" title="{% trans 'View Older Entries' %}">{% trans 'Older Entries' %}</a></li>
{% endifequal %}
{% else%}
{% endif %}
</ul>
{% endif %}
I'd appreciate any light you guys can throw on the best solution here.
| [
"The soultion, ultimately, was to rebuild the views. Extensive rebuilding required in this case.\nMoral of the sory: don't filter in templates!\n"
] | [
0
] | [] | [] | [
"django",
"django_generic_views",
"django_templates",
"paginator",
"python"
] | stackoverflow_0003512085_django_django_generic_views_django_templates_paginator_python.txt |
Q:
Question on Django: Displaying many to many fields
I seem to have a problem with Django when it comes Rendering ManyToManyField in a template. I can make it work partially, but I cannot make it work properly as I want it.
Firstly I have an invoice template which displays Invoice details from my data base
#invoice_details.html
{% extends "base.html" %}
{% block content %}
<h2>Invoice Details</h2>
<div id="horizontalnav">
<a href="/index/add_invoice">Add an Invoice</a>
<a href="/index/work_orders">Add a Work Order</a>
<a href="/index/add_payment">Add Payment</a>
</div>
<ul>
<div id="list">
{% for invoice in invoices_list %}
{{invoice.client}}<br/>
{{invoice.invoice_no}}<br/>
{{invoice.contract_info}}<br/>
{{invoice.date}}<br/>
{{invoice.work_orders}}<br/>
{% endfor %}
</div>
</ul>
{% endblock %}
In my database, {{invoice.work_orders}} was displayed like the following below. This is because {{invoice.work_orders}} uses a manytomanyfield
<django.db.models.fields.related.ManyRelatedManager object at 0x8a811ec>
Now I tried to change {{invoice.work_orders}} to {{invoice.work_orders.all}} and I got this.
[<Work_Order: Assurance Support Service >]
This sort of works, but I want it to display "Assurance Support Service" only. So I am wondering how I can do this change if possible.
A:
The content of {{invoice.work_orders.all} is a list of Work_Order objects.
If you want to print them, you should iterate the list:
{% for invoice in invoice.work_orders.all %}
{{invoice}}<br />
{% endfor %}
| Question on Django: Displaying many to many fields | I seem to have a problem with Django when it comes Rendering ManyToManyField in a template. I can make it work partially, but I cannot make it work properly as I want it.
Firstly I have an invoice template which displays Invoice details from my data base
#invoice_details.html
{% extends "base.html" %}
{% block content %}
<h2>Invoice Details</h2>
<div id="horizontalnav">
<a href="/index/add_invoice">Add an Invoice</a>
<a href="/index/work_orders">Add a Work Order</a>
<a href="/index/add_payment">Add Payment</a>
</div>
<ul>
<div id="list">
{% for invoice in invoices_list %}
{{invoice.client}}<br/>
{{invoice.invoice_no}}<br/>
{{invoice.contract_info}}<br/>
{{invoice.date}}<br/>
{{invoice.work_orders}}<br/>
{% endfor %}
</div>
</ul>
{% endblock %}
In my database, {{invoice.work_orders}} was displayed like the following below. This is because {{invoice.work_orders}} uses a manytomanyfield
<django.db.models.fields.related.ManyRelatedManager object at 0x8a811ec>
Now I tried to change {{invoice.work_orders}} to {{invoice.work_orders.all}} and I got this.
[<Work_Order: Assurance Support Service >]
This sort of works, but I want it to display "Assurance Support Service" only. So I am wondering how I can do this change if possible.
| [
"The content of {{invoice.work_orders.all} is a list of Work_Order objects. \nIf you want to print them, you should iterate the list: \n{% for invoice in invoice.work_orders.all %}\n {{invoice}}<br />\n{% endfor %}\n\n"
] | [
5
] | [] | [] | [
"django",
"html",
"manytomanyfield",
"python"
] | stackoverflow_0003891321_django_html_manytomanyfield_python.txt |
Q:
how to link python static library with my c++ program
I am implementing a C++ program that uses python/C++ Extensions. As of now I am explicitly linking my program to python static library I compiled. I am wondering is there any way to link my program with system installed python(i mean the default python installation that comes with linux)
A:
Yes. There is a command line utility called python-config:
Usage: /usr/bin/python-config [--prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--help]
For linkage purposes, you have to invoke it with --ldflags parameter. It will print a list of flags you have to pass to the linker (or g++) in order to link with system installed python libraries:
$ python-config --ldflags
-L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm -lpython2.6
It also can give you flags to compilation with --cflags parameter:
$ python-config --cflags
-I/usr/include/python2.6 -I/usr/include/python2.6 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes
Say you have a test program in test.cpp file, then you can do something like this in order to compile and link:
g++ $(python-config --cflags) -o test $(python-config --ldflags) ./test.cpp
That will link your program with shared libraries. If you want to go static, you can pass -static option to the linker. But that will link with all static stuff, including a runtime. If you want to go just with static python, you have to find those libraries yourself. One of the option is to parse python-config --ldflags output and look for libraries with .a extensions. But I'd rather stick to all dynamic or all static.
Hope it helps. Good luck!
| how to link python static library with my c++ program | I am implementing a C++ program that uses python/C++ Extensions. As of now I am explicitly linking my program to python static library I compiled. I am wondering is there any way to link my program with system installed python(i mean the default python installation that comes with linux)
| [
"Yes. There is a command line utility called python-config:\nUsage: /usr/bin/python-config [--prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--help]\n\nFor linkage purposes, you have to invoke it with --ldflags parameter. It will print a list of flags you have to pass to the linker (or g++) in order to l... | [
20
] | [] | [] | [
"python"
] | stackoverflow_0003891202_python.txt |
Q:
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'"
Here is the full stack trace:
Traceback (most recent call last):
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__
handler.post(*groups)
File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post
country=postedcountry
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__
prop.__set__(self, value)
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__
value = self.validate(value)
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate
if value is not None and not value.has_key():
AttributeError: 'unicode' object has no attribute 'has_key'
Let me describe a little bit more about the situation:
First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class
class CMSRequest(db.Model):
country = db.ReferenceProperty(CMSCountry, required=True)
class CMSCountry(db.Model):
name = db.StringProperty(required=True)
Then, I created a bulkloader class to import the data into the CMSCountry
In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object
def post(self):
postedcountry = self.request.get('country')
cmsRequest = models.CMSRequest(postedcountry)
Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.
Thank you everyone!
A:
In this line:
if value is not None and not value.has_key():
value is a unicode string. It looks like the code is expecting it to be a db.Model,
(From what I can see, has_key is a method of db.Model, as well as a method of Python dictionaries, but this must be the db.Model one because it's being called with no arguments.)
Are you passing a string to a GAE API that expects a db.Model?
A:
Your problem is that postedcountry is a string and not a country object. Values retrieved from self.request.get are the string values of variables passed by the browser.
You need to look up a country object using some GQL. Exactly how you do that will depend on what exactly the country field of your HTML form is returning , Object Key?, country name?
def post(self):
postedcountry = self.request.get('country')
# <-------- Need to look up a country here !!!!!
cmsRequest = models.CMSRequest(country=postedcountry)
A:
Note: normally "mapping" types in Python (dictionaries and dictionary like classes ... such as various types of dbm (indexed file) and some DBMS/ORM interfaces ... will implement a has_key() method.
Somehow you have gotten a Unicode (string) object into this statement when you were expecting to have some sort of dictionary or other mapping object reference.
In general AttributeError means that you have tangled up your object bindings (variable assignments). You've given a name to some object other than the type that you intended. (Or sometimes it means you have a typo like ".haskey()" instead of has_key() ... etc).
BTW: the use of has_key() is somewhat dated. Normally it's better to test your containers with the Python in operator (which implicitly calls __contains__() --- and which works on lists, strings, and other sequences as well as mapping types).
Also value.has_key() would raise an error even if value were a dictionary since the .has_key() method requires an argument.
In your code I would either explicitly test for if postedcountry is not None: ... or I'd supply your .get() with an (optional) default for "postedcountry."
How do you want to handle the situation where request had no postedcountry? Do you want to assume it's being posted from some particular default? Force a redirection to some page that requires the user to supply a value for that form element? Alert the Spanish Inquisition?
A:
If you read the traceback, it'll tell you exactly what is going on:
if value is not None and not value.has_key():
AttributeError: 'unicode' object has no attribute 'has_key'
What this says is the the value variable which you're using doesn't have the has_key attribute. And, what it's telling you is that your value variable isn't a dictionary, as it looks like you're expecting...instead, it's a unicode object, which is basically a string.
A:
You're attempting to set a string to a ReferenceProperty. The 'country' field of CMSCountry is a db.ReferenceProperty, which takes a db.Key or a CMSCountry object, but you're attempting to set it to a string.
You should be doing something like this:
def post(self):
postedcountry = self.request.get('country')
country = models.CMSCountry.all().filter('name =', postedcountry)
if not country:
# Couldn't find the country
else:
cmsRequest = models.CMSRequest(country=country)
Please do file a bug about the rather unhelpful error message, though.
A:
The dictionary object's has_key() method is deprecated in 3.0 - use the "in" expression instead. If you are using the old library in 3.x, you must make code changes to accommodate it.
| Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' " | I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'"
Here is the full stack trace:
Traceback (most recent call last):
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__
handler.post(*groups)
File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post
country=postedcountry
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__
prop.__set__(self, value)
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__
value = self.validate(value)
File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate
if value is not None and not value.has_key():
AttributeError: 'unicode' object has no attribute 'has_key'
Let me describe a little bit more about the situation:
First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class
class CMSRequest(db.Model):
country = db.ReferenceProperty(CMSCountry, required=True)
class CMSCountry(db.Model):
name = db.StringProperty(required=True)
Then, I created a bulkloader class to import the data into the CMSCountry
In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object
def post(self):
postedcountry = self.request.get('country')
cmsRequest = models.CMSRequest(postedcountry)
Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.
Thank you everyone!
| [
"In this line:\nif value is not None and not value.has_key():\n\nvalue is a unicode string. It looks like the code is expecting it to be a db.Model,\n(From what I can see, has_key is a method of db.Model, as well as a method of Python dictionaries, but this must be the db.Model one because it's being called with n... | [
6,
3,
2,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001314617_google_app_engine_python.txt |
Q:
Python: loop through a file for specific lines
I have the following lines in a file where I want to take the third column; In the file I don't have the numbers column:
Red; Blue; Green; White; Orange;
Green; White; Orange;
Blue; Green; White;
Red; Blue; Green; White;
Blue; Green; White; Orange;
Orange
Green; White; Orange;
White; Orange
Green;
I used this code line to do that:
lines = i.split(";")[2]
The problem is that some of the lines have only one column or two, so it gives me 'index out of range' error. Please tell me how to go about this problem?
thanks a lot
Adia
A:
what about something like this:
cols = i.split(";")
if (len(cols) >= 3):
lines = cols[2]
else:
#whatever you want here
A:
The simple solution is to check the number of columns and ignore lines with less than three columns.
third_columns = []
with open("...") as infile:
for line in infile:
columns = line.split(';')
if len(columns) >= 3:
third_columns.append(columns[2])
And if you parse CSV (seems like you do), you better use one of the numerous existing CSV parsers, e.g. the one in the standard library.
A:
use a slice instead of an index.
>>> with open('test.txt') as f_in:
... column3 = (line.split(';')[2:3] for line in f_in)
... column3 = [item[0] for item in column3 if item]
...
>>> column3
[' Green', ' Orange', ' White', ' Green', ' White', ' Orange']
A:
for line in open("file"):
try:
s=line.split(";")[2]
except: pass
else:
print s
| Python: loop through a file for specific lines | I have the following lines in a file where I want to take the third column; In the file I don't have the numbers column:
Red; Blue; Green; White; Orange;
Green; White; Orange;
Blue; Green; White;
Red; Blue; Green; White;
Blue; Green; White; Orange;
Orange
Green; White; Orange;
White; Orange
Green;
I used this code line to do that:
lines = i.split(";")[2]
The problem is that some of the lines have only one column or two, so it gives me 'index out of range' error. Please tell me how to go about this problem?
thanks a lot
Adia
| [
"what about something like this:\ncols = i.split(\";\")\nif (len(cols) >= 3):\n lines = cols[2]\nelse:\n #whatever you want here\n\n",
"The simple solution is to check the number of columns and ignore lines with less than three columns.\nthird_columns = []\nwith open(\"...\") as infile:\n for line in inf... | [
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003891299_python.txt |
Q:
Appengine - Upload to Google Spreadsheet datastore values
I´d like to know how to upload to a Google Spreadsheet, values stored in the database of my application.
Objective:
Connecting to Google Spreadsheet and automatically fill in a chart in the admin area with values that were passed by the upload.
I've been giving a look in the docs and it seems to me that I have to use Bulk Loader.
Is this the only way? If yes how to configure the Handler if I have a spreadsheet as a link to link text
Someone could make a script to access the Google Spreadsheet and pass the values of a Model?
Model:
class User (db.Model):
photo= db.BlobProperty()
name = db.StringProperty (required = True)
surname = db.StringProperty (required = True)
adress = db.PostalAddressProperty (required = True)
phone = db.PhoneNumberProperty (required = True)
A:
The Bulk Loader has nothing to do with interacting with a Google Docs Spreadsheet. It is used for adding records to your application's datastore.
To manipulate a Google Spreadsheet, you'll need to use the Google Spreadsheet API, which you could easily find on your own using Google.
No one here is going to write this code for you. This is not a free code-writing service. If you write some code that doesn't work and need some help figuring out why, edit your question and include the code along with a thorough description of what isn't working and why if you have any idea.
| Appengine - Upload to Google Spreadsheet datastore values | I´d like to know how to upload to a Google Spreadsheet, values stored in the database of my application.
Objective:
Connecting to Google Spreadsheet and automatically fill in a chart in the admin area with values that were passed by the upload.
I've been giving a look in the docs and it seems to me that I have to use Bulk Loader.
Is this the only way? If yes how to configure the Handler if I have a spreadsheet as a link to link text
Someone could make a script to access the Google Spreadsheet and pass the values of a Model?
Model:
class User (db.Model):
photo= db.BlobProperty()
name = db.StringProperty (required = True)
surname = db.StringProperty (required = True)
adress = db.PostalAddressProperty (required = True)
phone = db.PhoneNumberProperty (required = True)
| [
"The Bulk Loader has nothing to do with interacting with a Google Docs Spreadsheet. It is used for adding records to your application's datastore.\nTo manipulate a Google Spreadsheet, you'll need to use the Google Spreadsheet API, which you could easily find on your own using Google.\nNo one here is going to write ... | [
3
] | [] | [] | [
"bigtable",
"django",
"google_app_engine",
"google_sheets",
"python"
] | stackoverflow_0003888445_bigtable_django_google_app_engine_google_sheets_python.txt |
Q:
How is generated the python grammar and how the interpreter understand it
I wonder how is generated the grammar of the Python language and how it is understood by the interpreter.
In python, the file graminit.c seems to implement the grammar, but i don't clearly understand it.
More broadly, what are the different ways to generate a grammar and are there differences between how the grammar is implemented in languages such as Perl, Python or Lua.
A:
Grammars are generally of the same form: Backus-Naur Form (BNF) is typical.
Lexer/parsers can take very different forms.
The lexer breaks up the input file into tokens. The parser uses the grammar to see if the stream of tokens is "valid" according to its rules.
Usually the outcome is an abstract syntax tree (AST) that can then be used to generate whatever you want, such as byte code or assembly.
A:
There are many ways to implement lexing/parsing, it really comes down to identifing the patterns and how they fit together. There are a few very nice Python packages for doing this that range from pure python to wrapped C code. Pyparsing in-particular has many excellent examples. One thing worth noting, finding a straight EBNF/BNF parser is kind of hard -- writing a parser with Python code isn't awful but it is one step further from the raw grammar which might be important to you.
Code Talker
SimpleParse
Python Lex Yacc
pyparsing
| How is generated the python grammar and how the interpreter understand it | I wonder how is generated the grammar of the Python language and how it is understood by the interpreter.
In python, the file graminit.c seems to implement the grammar, but i don't clearly understand it.
More broadly, what are the different ways to generate a grammar and are there differences between how the grammar is implemented in languages such as Perl, Python or Lua.
| [
"Grammars are generally of the same form: Backus-Naur Form (BNF) is typical.\nLexer/parsers can take very different forms. \nThe lexer breaks up the input file into tokens. The parser uses the grammar to see if the stream of tokens is \"valid\" according to its rules.\nUsually the outcome is an abstract syntax tr... | [
8,
2
] | [] | [] | [
"grammar",
"python"
] | stackoverflow_0003890321_grammar_python.txt |
Q:
Twill - how do choose multiple selects with same name
I am using twill and python to write a web crawler. showforms() returns
Form name=customRatesForm (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
10 originState hidden originState TN
11 destState hidden destState IL
12 originZip text originZip 37130
13 destZip text destZip 60602
16 classes select classes1 ['0000'] of ['0000', '0500', '0550', ...
17 weight text weight1 600
18 weight text weight2
19 weight text weight3
20 weight text weight4
30 1 submit submi ... submit
I've taken out most of the rows to make it easier to read. My problem is that there are actually 12 selects and all of them have the name 'classes'. These pass through CGI as a list. However, Twill seems unable to distinguish between them. Also, when I run
fv('1', 'classes', '0500')
I get the following error:
_mechanize_dist.ClientForm.AmbiguityError: id=None name='0500' label=None
I have tried a few workarounds including renaming the selects with their ids and then rewriting the submit function to use a jQuery selector and reassign their 'name' attribute back to 'classes':
$('.myclasses').attr('name', 'classes');
when I view this in the browser, it seems to reassign them as expected. However, twill's headers still show it as submitting with the names 'classes1', 'classes2', etc.
any help would be much appreciated. I'm out of workarounds that I know of. Because this isn't my page, I am bound by their controller's expectations of a list for the 'classes' selects.
A:
as far as i've found till now, there is no way to do this with twill. any solution is going to be a workaround outside of twill.
| Twill - how do choose multiple selects with same name | I am using twill and python to write a web crawler. showforms() returns
Form name=customRatesForm (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
10 originState hidden originState TN
11 destState hidden destState IL
12 originZip text originZip 37130
13 destZip text destZip 60602
16 classes select classes1 ['0000'] of ['0000', '0500', '0550', ...
17 weight text weight1 600
18 weight text weight2
19 weight text weight3
20 weight text weight4
30 1 submit submi ... submit
I've taken out most of the rows to make it easier to read. My problem is that there are actually 12 selects and all of them have the name 'classes'. These pass through CGI as a list. However, Twill seems unable to distinguish between them. Also, when I run
fv('1', 'classes', '0500')
I get the following error:
_mechanize_dist.ClientForm.AmbiguityError: id=None name='0500' label=None
I have tried a few workarounds including renaming the selects with their ids and then rewriting the submit function to use a jQuery selector and reassign their 'name' attribute back to 'classes':
$('.myclasses').attr('name', 'classes');
when I view this in the browser, it seems to reassign them as expected. However, twill's headers still show it as submitting with the names 'classes1', 'classes2', etc.
any help would be much appreciated. I'm out of workarounds that I know of. Because this isn't my page, I am bound by their controller's expectations of a list for the 'classes' selects.
| [
"as far as i've found till now, there is no way to do this with twill. any solution is going to be a workaround outside of twill.\n"
] | [
1
] | [] | [] | [
"jquery",
"python",
"twill",
"web_crawler"
] | stackoverflow_0003755595_jquery_python_twill_web_crawler.txt |
Q:
Is there a way to debug a subprocess using pydev?
I'm using Eclipse / PyDev trying to find a way to debug code that uses subprocess.Popen to create a child process: I want to be able to debug the child process that is created. The problem is that I cannot find a way to debug accross process boundaries, and I'm guessing that it is actually not possible. Still, you never know until you ask, and so that I am doing!
A bit of background: I have a complex build process driven by Waf which invokes our unit tests by calling out to nose as required: I want to hook into these processes to debug unit test failures. I know I could try to run nose directly but the problem is that the environment I have to configure for our modules to load correctly is fairly complex and I don't want to duplicate the code to do that if I can avoid it.
I'm aware of the remote debugging mode but thats pretty inconvenient because I have to manually invoke the debugger in the remote process. If anyone knows a way to do what I'm trying to do it would be much appreciated.
A:
I does not seem PyDev can do it (neither can PyDbg and WinDbg), but it looks like gdb can: http://wiki.python.org/moin/DebuggingWithGdb.
A:
I've found something of a workaround that might work for you.
Like you, I first found the remote debugging option of manually inserting calls to pydevd.settrace() at desired breakpoints. But I also noticed that subsequent PyDev breakpoints (i.e. those created by clicking in the left margin) were obeyed. So it seems that you just need the first explicit settrace call to establish the remote debugging session for the process, and afterwards just use the normal debugger breakpoints.
Moreover, you can modify the settrace call so it doesn't actually suspend the process:
import pydevd
pydevd.settrace(suspend=False)
So insert the above code somewhere early in the initialization of the subprocess and you should be good. Still a bit of a hack, but it's definitely better than the manual method.
| Is there a way to debug a subprocess using pydev? | I'm using Eclipse / PyDev trying to find a way to debug code that uses subprocess.Popen to create a child process: I want to be able to debug the child process that is created. The problem is that I cannot find a way to debug accross process boundaries, and I'm guessing that it is actually not possible. Still, you never know until you ask, and so that I am doing!
A bit of background: I have a complex build process driven by Waf which invokes our unit tests by calling out to nose as required: I want to hook into these processes to debug unit test failures. I know I could try to run nose directly but the problem is that the environment I have to configure for our modules to load correctly is fairly complex and I don't want to duplicate the code to do that if I can avoid it.
I'm aware of the remote debugging mode but thats pretty inconvenient because I have to manually invoke the debugger in the remote process. If anyone knows a way to do what I'm trying to do it would be much appreciated.
| [
"I does not seem PyDev can do it (neither can PyDbg and WinDbg), but it looks like gdb can: http://wiki.python.org/moin/DebuggingWithGdb.\n",
"I've found something of a workaround that might work for you.\nLike you, I first found the remote debugging option of manually inserting calls to pydevd.settrace() at desi... | [
4,
3
] | [] | [] | [
"debugging",
"eclipse",
"pydev",
"python",
"waf"
] | stackoverflow_0001624932_debugging_eclipse_pydev_python_waf.txt |
Q:
Python: how to make HTTP request internally/localhost
I want to send some parameters from a python script on my server to a php script on my server using HTTP. Suggestions?
A:
This is pretty easy using urllib:
import urllib
myurl = 'http://localhost/script.php?var1=foo&var2=bar'
# GET is the default action
response = urllib.urlopen(myurl)
# Output from the GET assuming response code was 200
data = response.read()
| Python: how to make HTTP request internally/localhost | I want to send some parameters from a python script on my server to a php script on my server using HTTP. Suggestions?
| [
"This is pretty easy using urllib:\nimport urllib\n\nmyurl = 'http://localhost/script.php?var1=foo&var2=bar'\n\n# GET is the default action\nresponse = urllib.urlopen(myurl) \n\n# Output from the GET assuming response code was 200\ndata = response.read() \n\n"
] | [
2
] | [] | [] | [
"http",
"php",
"python"
] | stackoverflow_0003889283_http_php_python.txt |
Q:
subprocess replacement of popen2 with Python
I tried to run this code from the book 'Python Standard Library' of 'Fred Lunde'.
import popen2, string
fin, fout = popen2.popen2("sort")
fout.write("foo\n")
fout.write("bar\n")
fout.close()
print fin.readline(),
print fin.readline(),
fin.close()
It runs well with a warning of
~/python_standard_library_oreilly_lunde/scripts/popen2-example-1.py:1:
DeprecationWarning: The popen2 module is deprecated. Use the subprocess module.
How to translate the previous function with subprocess? I tried as follows, but it doesn't work.
from subprocess import *
p = Popen("sort", shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
p.stdin("foo\n") #p.stdin("bar\n")
A:
import subprocess
proc=subprocess.Popen(['sort'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
proc.stdin.write('foo\n')
proc.stdin.write('bar\n')
out,err=proc.communicate()
print(out)
A:
Within the multiprocessing module there is a method called 'Pool' which might be perfect for your needs considering you are planning to do sort (not sure how huge the data is, but...).
It's optimizes itself to the number of cores your system has. i.e. only as many processes are spawned as the no. of cores. Of course this is customizable.
from multiprocessing import Pool
def main():
po = Pool()
po.apply_async(sort_fn, (any_args,), callback=save_data)
po.close()
po.join()
return
def sort_fn(any_args):
#do whatever it is that you want to do in a separate process.
return data
def save_data(data):
#data is a object. Store it in a file, mysql or...
return
| subprocess replacement of popen2 with Python | I tried to run this code from the book 'Python Standard Library' of 'Fred Lunde'.
import popen2, string
fin, fout = popen2.popen2("sort")
fout.write("foo\n")
fout.write("bar\n")
fout.close()
print fin.readline(),
print fin.readline(),
fin.close()
It runs well with a warning of
~/python_standard_library_oreilly_lunde/scripts/popen2-example-1.py:1:
DeprecationWarning: The popen2 module is deprecated. Use the subprocess module.
How to translate the previous function with subprocess? I tried as follows, but it doesn't work.
from subprocess import *
p = Popen("sort", shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
p.stdin("foo\n") #p.stdin("bar\n")
| [
"import subprocess\nproc=subprocess.Popen(['sort'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)\nproc.stdin.write('foo\\n')\nproc.stdin.write('bar\\n')\nout,err=proc.communicate()\nprint(out)\n\n",
"Within the multiprocessing module there is a method called 'Pool' which might be perfect for your needs considerin... | [
10,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003892556_python_subprocess.txt |
Q:
How to adapt my current splash screen to allow other pieces of my code to run in the background?
Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).
This is the current (reduced) arquitecture of my program, with the important bits displayed in full. How can I adapt the splash screen currently in place to actually allow the rest of the program to load in the background? Is it possible in python?
Thanks!
import ...
(many other imports)
def ...
def ...
(many other definitions)
class VFrams(wxFrame):
wx.Frame.__init__(self, parent, -1, _("Software"),
size=(1024, 768), style=wx.DEFAULT_FRAME_STYLE)
(a lot of code goes in here)
class MySplashScreen(wx.SplashScreen):
def __init__(self, parent=None):
aBitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
splashDuration = 5000 # ms
wx.SplashScreen.__init__(self, aBitmap, splashStyle, splashDuration, parent)
self.Bind(wx.EVT_CLOSE, self.CloseSplash)
wx.Yield()
def CloseSplash(self, evt):
self.Hide()
global frame
frame = VFrame(parent=None)
app.SetTopWindow(frame)
frame.Show(True)
evt.Skip()
class MyApp(wx.App):
def OnInit(self):
MySplash = MySplashScreen()
MySplash.Show()
return True
if __name__ == '__main__':
DEBUG = viz.addText('DEBUG:', viz.SCREEN)
DEBUG.setPosition(0, 0)
DEBUG.fontSize(16)
DEBUG.color(viz.BLACK)
Start_Mainvars()
Start_Config()
Start_Translation()
Start_DB()
Start_Themes()
Start_Gui()
Start_Get_Isos()
Start_Bars()
Start_Menus()
Start_Event_Handlers()
app = MyApp()
app.MainLoop()
Thank you for all the help, this is how I changed the code (following the provided advice):
def show_splash():
# create, show and return the splash screen
global splash
bitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
splash.Show()
return splash
class MyApp(wx.App):
def OnInit(self):
global frame, splash
splash = show_splash()
Start_Config()
Start_Translation()
Start_DB()
Start_Themes()
Start_Gui()
Start_Get_Isos()
Start_Bars("GDP1POP1_20091224_gdp", "1 pork")
Start_Menus()
Start_Event_Handlers()
frame = VFrame(parent=None)
frame.Show(True)
splash.Destroy()
return True
if __name__ == '__main__':
DEBUG = viz.addText('DEBUG:', viz.SCREEN)
DEBUG.setPosition(0, 0)
DEBUG.fontSize(16)
DEBUG.color(viz.BLACK)
Start_Mainvars()
app = MyApp()
app.MainLoop()
A:
Your code is pretty messy/complicated. There's no need to override wx.SplashScreen and no reason your splash screen close event should be creating the main application window. Here's how I do splash screens.
import wx
def show_splash():
# create, show and return the splash screen
bitmap = wx.Bitmap('images/splash.png')
splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
splash.Show()
return splash
def main():
app = wx.PySimpleApp()
splash = show_splash()
# do processing/initialization here and create main window
frame = MyFrame(...)
frame.Show()
splash.Destroy()
app.MainLoop()
if __name__ == '__main__':
main()
Just create the splash screen as soon as possible with no timeout. Continue loading and create your application's main window. Then destroy the splash screen so it goes away. Showing the splash screen doesn't stop other processing from happening.
A:
You'll want to use two threads: one for the splash screen, one for whatever other code you want to execute. Both threads would run at the same time, providing the result you desire.
| How to adapt my current splash screen to allow other pieces of my code to run in the background? | Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).
This is the current (reduced) arquitecture of my program, with the important bits displayed in full. How can I adapt the splash screen currently in place to actually allow the rest of the program to load in the background? Is it possible in python?
Thanks!
import ...
(many other imports)
def ...
def ...
(many other definitions)
class VFrams(wxFrame):
wx.Frame.__init__(self, parent, -1, _("Software"),
size=(1024, 768), style=wx.DEFAULT_FRAME_STYLE)
(a lot of code goes in here)
class MySplashScreen(wx.SplashScreen):
def __init__(self, parent=None):
aBitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
splashDuration = 5000 # ms
wx.SplashScreen.__init__(self, aBitmap, splashStyle, splashDuration, parent)
self.Bind(wx.EVT_CLOSE, self.CloseSplash)
wx.Yield()
def CloseSplash(self, evt):
self.Hide()
global frame
frame = VFrame(parent=None)
app.SetTopWindow(frame)
frame.Show(True)
evt.Skip()
class MyApp(wx.App):
def OnInit(self):
MySplash = MySplashScreen()
MySplash.Show()
return True
if __name__ == '__main__':
DEBUG = viz.addText('DEBUG:', viz.SCREEN)
DEBUG.setPosition(0, 0)
DEBUG.fontSize(16)
DEBUG.color(viz.BLACK)
Start_Mainvars()
Start_Config()
Start_Translation()
Start_DB()
Start_Themes()
Start_Gui()
Start_Get_Isos()
Start_Bars()
Start_Menus()
Start_Event_Handlers()
app = MyApp()
app.MainLoop()
Thank you for all the help, this is how I changed the code (following the provided advice):
def show_splash():
# create, show and return the splash screen
global splash
bitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
splash.Show()
return splash
class MyApp(wx.App):
def OnInit(self):
global frame, splash
splash = show_splash()
Start_Config()
Start_Translation()
Start_DB()
Start_Themes()
Start_Gui()
Start_Get_Isos()
Start_Bars("GDP1POP1_20091224_gdp", "1 pork")
Start_Menus()
Start_Event_Handlers()
frame = VFrame(parent=None)
frame.Show(True)
splash.Destroy()
return True
if __name__ == '__main__':
DEBUG = viz.addText('DEBUG:', viz.SCREEN)
DEBUG.setPosition(0, 0)
DEBUG.fontSize(16)
DEBUG.color(viz.BLACK)
Start_Mainvars()
app = MyApp()
app.MainLoop()
| [
"Your code is pretty messy/complicated. There's no need to override wx.SplashScreen and no reason your splash screen close event should be creating the main application window. Here's how I do splash screens.\nimport wx\n\ndef show_splash():\n # create, show and return the splash screen\n bitmap = wx.Bitmap... | [
13,
0
] | [] | [] | [
"initialization",
"multithreading",
"python",
"splash_screen",
"wxpython"
] | stackoverflow_0003892327_initialization_multithreading_python_splash_screen_wxpython.txt |
Q:
Best Django 'CMS' component for integration into existing site
So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms.
Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface?
A:
I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices.
The grid comparison at djangopluggables.com certainly can make evaluating each of these easier.
django-cms is the most full-featured and is something you could actually hand over to clients without being irresponsible. Even though it has features for integrating other apps, it doesn't have the extensibility/integration of FeinCMS or the simplicity of django-page-cms. That being said, I think the consensus is that this is the best Open Source CMS for Django. However, it's docs are a little lacking. update: I have been told that integrating apps into DjangoCMS 2.1 has been improved.
FeinCMS - Is a great set of tools for combining and building CMS functionality into your own apps. It's not "out of the box" at all, which means that you can integrate it however you want. It doesn't want to take over your urls.py or control how you route pages. It's probably a prototype for the next-generation of truly pluggable apps in Django. - We are moving from django-page-cms to FeinCMS because our primary models is high volume eCommerce and I have custom content-types I want to integrate that aren't blogs or flash. Good documentation and support as well.
Django-page-cms - Is great if you want to just have some "About Us" pages around your principle application. Its menu system is not truly hierarchical and building your page presentation is up to you. But it's very simple, unobtrusive, and very easy to slap into your app and get a navigation going that clients can manage, or even for yourself. It has no docs that I know of, but you won't really need any. Read the code and you will get it all in 30 minutes or less.
update
Mezzanine - Is a very well designed CMS and one that I have finally settled on for most of my client work, mostly because it has an integrated eCommerce portion. But beyond that it has very extensible page models, and a custom admin interface that a client might be willing to use. It also has the best "out of the box" experience i.e. You can have a full fledged site up with one command.
A:
If you do not necessarily want a finished CMS with a fixed feature set, but rather tools on top of Django to build your own CMS I recommend looking into FeinCMS. It follows a toolkit philosophy instead of trying to solve everything and (too) often failing to do so.
http://github.com/matthiask/feincms/tree/master
Disclaimer: It is my brainchild, and the result of too many frustrating experiences trying to customize another CMS for the needs of my customers.
A:
There is also this one that is quite nice as well:
Django CMS page
A:
If you need some more features then the simple django-page-cms just checkout django-blocks (http://code.google.com/p/django-blocks/). Has multi-language Menu, Flatpages and even has a simple Shopping Cart!!
A:
There is a very nice overview of Django CMS apps on the Django wiki!
http://code.djangoproject.com/wiki/CMSAppsComparison
A:
See django-plugables website, there are few CMS components for Django listed (and some look really good).
A:
I've had success with integrating django-cms. Just include it at the end of your urlconf and it won't interfere. (You'll just lose the the nice 404 page when DEBUG=True)
Using various combinations of context processors and custom template tags I've been able to do everything I've needed, but if you really need to insert the content into your own view, that should be easy enough. (Perhaps call cms.views.render_page() with a template that lacks all the wrapper html?)
| Best Django 'CMS' component for integration into existing site | So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms.
Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface?
| [
"I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices.\nThe grid comparison at djangopluggables.com certainly can make evaluating each of these easier.\ndjango-cms is the most full-featured and is something you could actually ... | [
26,
7,
5,
4,
3,
2,
1
] | [] | [] | [
"content_management_system",
"django",
"python"
] | stackoverflow_0000302983_content_management_system_django_python.txt |
Q:
Anyone have a favorite Python coding style enforcer?
I'm trying to find a Python coding style enforcer (tool, not person!). Any recommendations?
A:
I only know pylint, but it is not an automatic code formatter, rather a marking tool.
A:
Don't forget PEP8, both the PEP8 style guide (http://www.python.org/dev/peps/pep-0008/) and the tool
Not a lint like tool, but keeps your style in line with the main python community.
yapf (https://pypi.python.org/pypi/yapf) is super cool, reformats your code to be pep8 compliant. Very handy
A:
pyflakes is like pylint but faster.
| Anyone have a favorite Python coding style enforcer? | I'm trying to find a Python coding style enforcer (tool, not person!). Any recommendations?
| [
"I only know pylint, but it is not an automatic code formatter, rather a marking tool.\n",
"Don't forget PEP8, both the PEP8 style guide (http://www.python.org/dev/peps/pep-0008/) and the tool\nNot a lint like tool, but keeps your style in line with the main python community.\nyapf (https://pypi.python.org/pypi/y... | [
2,
1,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0003892656_coding_style_python.txt |
Q:
Which embedded database to use for file indexing applications
I need to develop a file indexing application in python and wanted to know which embedded database is the best one to use for indexing.
Any help on this topic is appreciated.
Thanks,
Rajesh
A:
you could use sqlite :
http://www.sqlite.org/
https://github.com/ghaering/pysqlite
Another one that you could explore is
http://www.equi4.com/metakit/
For file indexing there are tools like pylucene, xapian.
Python file indexing and searching
Other relevant link on SO
File indexing (using Binary trees?) in Python
A:
You can also check Firebird who have for good drivers for Python
You can also use the sphinx add in
Or you can also use lucene and firebird like infovark
| Which embedded database to use for file indexing applications | I need to develop a file indexing application in python and wanted to know which embedded database is the best one to use for indexing.
Any help on this topic is appreciated.
Thanks,
Rajesh
| [
"you could use sqlite : \n\nhttp://www.sqlite.org/ \nhttps://github.com/ghaering/pysqlite\n\nAnother one that you could explore is\n\nhttp://www.equi4.com/metakit/\n\nFor file indexing there are tools like pylucene, xapian.\n\nPython file indexing and searching\n\nOther relevant link on SO\n\nFile indexing (using B... | [
3,
0
] | [] | [] | [
"database",
"embedded_database",
"filesystems",
"indexing",
"python"
] | stackoverflow_0003878617_database_embedded_database_filesystems_indexing_python.txt |
Q:
How to properly iterate over a huge QuerySet in django?
I need to retrieve 5 objects that match a certain complex criteria, and I can't/don't want to pass that criteria to the WHERE clause(filter in django), so I need to iterate over the results, testing each record for the criteria until I get my 5 objects, after that I want to throw the query set away and never see it again.
In most cases, the records I need will be at the beginning of the query set, in the worst case, it will be at its end. The table is huge and I only need 5 records. So my question is: How do I iterate over a query set without having django to cache the results? This must be done in a way that neither the sql engine/django storing/caching the results anywhere.
A:
Why do you worry about caching? Let Django or mysql do what they do.
If you are bent on it. You could disable caching for Django. This is quite simple thing to do in settings.py for your project.
For Mysql, you need to run some querie(s) to disable the query cache -
Try using the SQL_NO_CACHE option in your query. Like so
SELECT SQL_NO_CACHE * FROM TABLE
This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.
One problem with this method is that it seems to only prevent the result of your query from being cached. However, if you're querying a database that is actively being used with the query you want to test, then other clients may cache your query, affecting your results. I am continuing to research ways around this, will edit this post if I figure one out.
OR
You could also do RESET QUERY CACHE
OR
FLUSH QUERY CACHE
Although one point to note is that I would suggest letting the Mysql handle the WHERE clause as it has query optimization layer which would be very effective if you have the right fields indexed. Getting all the results & you doing what the WHERE clause does might slow you down depending on the size of the query set. Just some thing to think about. I guess proper benchmarking should show you the way.
A:
Django does not have a global cache (see ticket #14). This means that as long as you don't hold onto anything, the data will be gone and no longer be cached. At that point, the garbage collector will remove the memory allocation on the next cleanup. Therefore, code such as:
my_objects = [obj for obj in MyModel.objects.all() if my_complex_condition(obj)]
The only caching django would do here is in the particular instance above, and after this line any reference to the cache would be gone. Note that if Django had no cache whatsoever, the memory would still fill up in the same manner, and the GC would collect the rows individually any way.
| How to properly iterate over a huge QuerySet in django? | I need to retrieve 5 objects that match a certain complex criteria, and I can't/don't want to pass that criteria to the WHERE clause(filter in django), so I need to iterate over the results, testing each record for the criteria until I get my 5 objects, after that I want to throw the query set away and never see it again.
In most cases, the records I need will be at the beginning of the query set, in the worst case, it will be at its end. The table is huge and I only need 5 records. So my question is: How do I iterate over a query set without having django to cache the results? This must be done in a way that neither the sql engine/django storing/caching the results anywhere.
| [
"Why do you worry about caching? Let Django or mysql do what they do. \nIf you are bent on it. You could disable caching for Django. This is quite simple thing to do in settings.py for your project.\nFor Mysql, you need to run some querie(s) to disable the query cache -\nTry using the SQL_NO_CACHE option in your qu... | [
1,
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0003893006_django_django_queryset_python.txt |
Q:
C++ and Embedded Python - NUL Terminated Strings
I'm working on embedding Python 2.6 into an existing c++ application. So far I have the Libraries linked in and am able to successfully initialize the Python Interpreter and can also transfer data to Python. I'm having trouble retrieving it, and hope someone can steer me the right direction. I'm working with this:
Py_Initialize();
pModule = PyImport_ImportModule("cBuffers"); // This crashes after 1st call.
pDict = PyModule_GetDict(pModule);
pClass = PyDict_GetItemString(pDict, "rf_pdf");
pMeth = PyString_FromString("main");
if (PyCallable_Check(pClass) && PyClass_Check(pClass)) {
pInstance = PyInstance_New(pClass, NULL, NULL);
pOutput = PyObject_CallMethodObjArgs(pInstance, pMeth, pOpts, pInput, NULL);
}
if (pOutput != NULL) {
string pPdf = PyString_AsString(pOutput);
Py_DECREF(pOutput);
} else {
PyErr_Print();
}
// Cleanup
Py_DECREF(pModule);
Py_DECREF(pModule); // Has an extra reference, not positive why.
Py_DECREF(pMeth);
Py_DECREF(pInstance);
Py_DECREF(pOpts);
Py_DECREF(pInput);
Py_Finalize();
pOpts and pInput are both generated using PyString_FromString earlier in the code. The trouble I'm having is that when I attempt to retrieve the output using PyString_AsString the return value is NUL Terminated. Unfortunately, because I'm generating PDF Documents, NULs are not only allowed, they're almost guaranteed. Can anyone tell me how I return String Data from Python back to C++ without ending at the first NUL it encounters?
As an additional question, This code can be called multiple times as a part of a background service that's creating PDF Documents from incoming Print Data. The first time this code is called into it works as expected. Any subsequent calls fail at the indicated line just after Py_Initialize(). Help on how to determine what's going on there would be most appreciated as well. Thanks in advance,
A:
A few points:
Don't use strings. You might even be
able to make them work here with some
contortions on *_StringAndSize()
functions, but it won't be what you
want. You should store your data in
a custom data structure (or a buffer) that is just
a sequence of bytes (do you really
want clients performing string
operations on this data in Python?). If your object really is a buffer object, you should use the Buffer API.
Your imported module has a refcount of 2 because it's being held in
sys.modules (for efficiency for the next time you try to import it). Never decref
references you don't own or you'll
crash your program. The Importing
Modules section of the
documentation should really cover
this, but it doesn't.
It's pretty expensive to initialize Python and tear it down every time you do these operations. You should try to reorganize your use case such that you can call Py_Initialize only once when your application starts (or the first time it needs Python), and then only call Py_Finalize when your application is definitely done with Python, or when it quits.
You're being very lazy with error checking - most of the Python C/API functions can return NULL to indicate that an exception has been thrown, and you're almost never checking this value. If something fails you're going to start crashing in very odd places. You can read about this in the Exception Handling section of the C/API manual.
| C++ and Embedded Python - NUL Terminated Strings | I'm working on embedding Python 2.6 into an existing c++ application. So far I have the Libraries linked in and am able to successfully initialize the Python Interpreter and can also transfer data to Python. I'm having trouble retrieving it, and hope someone can steer me the right direction. I'm working with this:
Py_Initialize();
pModule = PyImport_ImportModule("cBuffers"); // This crashes after 1st call.
pDict = PyModule_GetDict(pModule);
pClass = PyDict_GetItemString(pDict, "rf_pdf");
pMeth = PyString_FromString("main");
if (PyCallable_Check(pClass) && PyClass_Check(pClass)) {
pInstance = PyInstance_New(pClass, NULL, NULL);
pOutput = PyObject_CallMethodObjArgs(pInstance, pMeth, pOpts, pInput, NULL);
}
if (pOutput != NULL) {
string pPdf = PyString_AsString(pOutput);
Py_DECREF(pOutput);
} else {
PyErr_Print();
}
// Cleanup
Py_DECREF(pModule);
Py_DECREF(pModule); // Has an extra reference, not positive why.
Py_DECREF(pMeth);
Py_DECREF(pInstance);
Py_DECREF(pOpts);
Py_DECREF(pInput);
Py_Finalize();
pOpts and pInput are both generated using PyString_FromString earlier in the code. The trouble I'm having is that when I attempt to retrieve the output using PyString_AsString the return value is NUL Terminated. Unfortunately, because I'm generating PDF Documents, NULs are not only allowed, they're almost guaranteed. Can anyone tell me how I return String Data from Python back to C++ without ending at the first NUL it encounters?
As an additional question, This code can be called multiple times as a part of a background service that's creating PDF Documents from incoming Print Data. The first time this code is called into it works as expected. Any subsequent calls fail at the indicated line just after Py_Initialize(). Help on how to determine what's going on there would be most appreciated as well. Thanks in advance,
| [
"A few points:\n\nDon't use strings. You might even be\nable to make them work here with some\ncontortions on *_StringAndSize()\nfunctions, but it won't be what you\nwant. You should store your data in\na custom data structure (or a buffer) that is just\na sequence of bytes (do you really\nwant clients performing... | [
1
] | [] | [] | [
"c++",
"embedded_language",
"python",
"string",
"termination"
] | stackoverflow_0003892961_c++_embedded_language_python_string_termination.txt |
Q:
Problem sorting IntegerProperty in Google App Engine
http://code.google.com/appengine/articles/update_schema.html
Trying to work this out for a nice little updater across my web application. The only difference is rather than sorting on a StringProperty as shown in the example I am using an IntegerProperty.
No matter which way round I turn the query I cannot get it to respond correctly to my filters.
bfid = self.request.get("bfid", None)
if bfid == None:
q = Course.all()
q.order("-bfid")
result = q.get()
bfid = result.bfid
q = Course.all()
q.filter("bfid <=", bfid)
q.order("-bfid")
results = q.fetch(limit=2)
for result in results:
print result.bfid
No matter what the bfid is, say 10, the two results it returns are 61, 62 which are the largest numbers in the set.
What have I done wrong???
A:
You need to convert bfid to int; self.request.get() returns a string.
You also have a problem with your logic; if bfid is None the query will be done twice, the second time with all results less than or equal to None. (This isn't what's causing your problem here, though.)
| Problem sorting IntegerProperty in Google App Engine | http://code.google.com/appengine/articles/update_schema.html
Trying to work this out for a nice little updater across my web application. The only difference is rather than sorting on a StringProperty as shown in the example I am using an IntegerProperty.
No matter which way round I turn the query I cannot get it to respond correctly to my filters.
bfid = self.request.get("bfid", None)
if bfid == None:
q = Course.all()
q.order("-bfid")
result = q.get()
bfid = result.bfid
q = Course.all()
q.filter("bfid <=", bfid)
q.order("-bfid")
results = q.fetch(limit=2)
for result in results:
print result.bfid
No matter what the bfid is, say 10, the two results it returns are 61, 62 which are the largest numbers in the set.
What have I done wrong???
| [
"You need to convert bfid to int; self.request.get() returns a string.\nYou also have a problem with your logic; if bfid is None the query will be done twice, the second time with all results less than or equal to None. (This isn't what's causing your problem here, though.)\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003893137_google_app_engine_python.txt |
Q:
Switch-case in Python doesn't work; need another pattern
I need a help with some code here. I wanted to implement the switch case pattern in Python, so like some tutorial said, I can use a dictionary for that, but here is my problem:
# Type can be either create or update or ..
message = { 'create':msg(some_data),
'update':msg(other_data)
# can have more
}
return message(type)
but it's not working for me because some_data or other_data can be None (it raises an error if it's none) and the msg function need to be simple (I don't want to put some condition in it).
The problem here is that the function msg() is executed in each time for filling the dict.
Unlike the switch case pattern which usually in other programming language don't execute the code in the case unless it's a match.
Is there another way to do this or do I just need to do if elif?
Actually, it's more like this:
message = { 'create': "blabla %s" % msg(some_data),
'update': "blabla %s" % msg(other_data)
'delete': "blabla %s" % diff(other_data, some_data)
}
So lambda don't work here and not the same function is called, so it's more like a real switch case that I need, and maybe I have to think about another pattern.
A:
message = { 'create':msg(some_data or ''),
'update':msg(other_data or '')
# can have more
}
Better yet, to prevent msg from being executed just to fill the dict:
message = { 'create':(msg,some_data),
'update':(msg,other_data),
# can have more
}
func,data=message[msg_type]
func(data)
and now you are free to define a more sensible msg function which can deal with an argument equal to None:
def msg(data):
if data is None: data=''
...
A:
It sounds like you're complicating this more than you need to. If you want it simple, use:
if mytype == 'create':
return msg(some_data)
elif mytype == 'update':
return msg(other_data)
else:
return msg(default_data)
You don't have to use dicts and function references just because you can. Sometimes a boring, explicit if/else block is exactly what you need. It's clear to even the newest programmers on your team and won't call msg() unnecessarily, ever. I'm also willing to bet that this will be faster than the other solution you were working on unless the number of cases grows large and msg() is lightning fast.
A:
Turns out the jokes on me and I was pwned in the switch inventing game five years before I even learned Python: Readable switch construction without lambdas or dictionaries. Oh well. Read below for another way to do it.
Here. Have a switch statement (with some nice cleanups by @martineau):
with switch(foo):
@case(1)
def _():
print "1"
@case(2)
def _():
print "2"
@case(3)
def _():
print "3"
@case(5)
@case(6)
def _():
print '5 and 6'
@case.default
def _():
print 'default'
I'll toss in the (moderately) hacked stack, abused decorators and questionable context manager for free. It's ugly, but functional (and not in the good way). Essentially, all it does is wrap the dictionary logic up in an ugly wrapper.
import inspect
class switch(object):
def __init__(self, var):
self.cases = {}
self.var = var
def __enter__(self):
def case(value):
def decorator(f):
if value not in self.cases:
self.cases[value] = f
return f
return decorator
def default(f):
self.default = f
return f
case.default = default
f_locals = inspect.currentframe().f_back.f_locals
self.f_locals = f_locals.copy()
f_locals['case'] = case
def __exit__(self, *args, **kwargs):
new_locals = inspect.currentframe().f_back.f_locals
new_items = [key for key in new_locals if key not in self.f_locals]
for key in new_items:
del new_locals[key] # clean up
new_locals.update(self.f_locals) # this reverts all variables to their
try: # previous values
self.cases[self.var]()
except KeyError:
try:
getattr(self, 'default')()
except AttributeError:
pass
Note that the hacked stack isn't actually necessary. We just use it to create a scope so that definitions that occur in the switch statement don't leak out into the enclosing scope and to get case into the namespace. If you don't mind leaks (loops leak for instance), then you can remove the stack hack and return the case decorator from __enter__, using the as clause on the with statement to receive it in the enclosing scope.
A:
Here's something a little different (although somewhat similar to @Tumbleweed's) and arguably more "object-oriented". Instead of explicitly using a dictionary to handle the various cases, you could use a Python class (which contains a dictionary).
This approach provides a fairly natural looking translation of C/C++ switch statements into Python code. Like the latter it defers execution of the code that handles each case and allows a default one to be provided.
The code for each switch class method that corresponds to a case can consist of more than one line of code instead of the single return <expression> ones shown here and are all compiled only once. One difference or limitation though, is that the handling in one method won't and can't be made to automatically "fall-though" into the code of the following one (which isn't an issue in the example, but would be nice).
class switch:
def create(self): return "blabla %s" % msg(some_data)
def update(self): return "blabla %s" % msg(other_data)
def delete(self): return "blabla %s" % diff(other_data, some_data)
def _default(self): return "unknown type_"
def __call__(self, type_): return getattr(self, type_, self._default)()
switch = switch() # only needed once
return switch(type_)
A:
You could hide the evaluation inside a lambda:
message = { 'create': lambda: msg(some_data),
'update': lambda: msg(other_data),
}
return message[type]()
As long as the names are all defined (so you don’t get a NameError), you could also structure it like this:
message = { 'create': (msg, some_data),
'update': (other_func, other_data),
}
func, arg = message[type]
return func(arg)
A:
You can delay execution of the match using lambda:
return {
'create': lambda: msg(some_data),
'update': lambda: msg(other_data),
# ...
}[type]()
If all the cases are just calling msg with different arguments, you can simplify this to:
return msg({
'create': some_data,
'update': other_data,
# ...
}[type])
A:
Create a new class and wrap the data/arguments in an object - so instead of binding data by passing arguments - you could just let a function decide which parameters it needs...
class MyObj(object):
def __init__(self, data, other_data):
self.data = data
self.other_data = other_data
def switch(self, method_type):
return {
"create": self.msg,
"update": self.msg,
"delete": self.delete_func,
}[method_type]()
def msg(self):
# Process self.data
return "Hello, World!!"
def delete_func(self):
# Process other data self.other_data or anything else....
return True
if "__main__" == __name__:
m1 = MyObj(1,2)
print m1.switch('create')
print m1.switch('delete')
A:
Ah never mind, this explained it. I was thinking of elif - Switch-case statement in Python
A:
Since the code you want to execute in each case is from a safe source, you could store each snippet in a separate string expression in a dictionary and do something along these lines:
message = { 'create': '"blabla %s" % msg(some_data)',
'update': '"blabla %s" % msg(other_data)',
'delete': '"blabla %s" % diff(other_data, some_data)'
}
return eval(message[type_])
The expression on the last line could also be eval(message.get(type_, '"unknown type_"')) to provide a default. Either way, to keep things readable the ugly details could be hidden:
switch = lambda type_: eval(message.get(type_, '"unknown type_"'))
return switch(type_)
The code snippets can even be precompiled for a little more speed:
from compiler import compile # deprecated since version 2.6: Removed in Python 3
for k in message:
message[k] = compile(message[k], 'message case', 'eval')
| Switch-case in Python doesn't work; need another pattern | I need a help with some code here. I wanted to implement the switch case pattern in Python, so like some tutorial said, I can use a dictionary for that, but here is my problem:
# Type can be either create or update or ..
message = { 'create':msg(some_data),
'update':msg(other_data)
# can have more
}
return message(type)
but it's not working for me because some_data or other_data can be None (it raises an error if it's none) and the msg function need to be simple (I don't want to put some condition in it).
The problem here is that the function msg() is executed in each time for filling the dict.
Unlike the switch case pattern which usually in other programming language don't execute the code in the case unless it's a match.
Is there another way to do this or do I just need to do if elif?
Actually, it's more like this:
message = { 'create': "blabla %s" % msg(some_data),
'update': "blabla %s" % msg(other_data)
'delete': "blabla %s" % diff(other_data, some_data)
}
So lambda don't work here and not the same function is called, so it's more like a real switch case that I need, and maybe I have to think about another pattern.
| [
"message = { 'create':msg(some_data or ''),\n 'update':msg(other_data or '')\n # can have more\n }\n\nBetter yet, to prevent msg from being executed just to fill the dict:\nmessage = { 'create':(msg,some_data),\n 'update':(msg,other_data),\n # can have more\n ... | [
9,
9,
4,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0003886641_design_patterns_python.txt |
Q:
Saving a deep copy of an object, then modifying it and saving another copy?
I have a 'GameBoard' class and am doing a search on it. I want to save the current gameboard in a list, change the state of the gameboard, save THAT one in a list, and so on (so I would have incremental versions of the gameboard as a game progresses).
I'm currently doing this with copy.deepcopy, but it doesn't seem to be saving and moving on. Here is a sample of my code:
moves = [] # just for reference. this has at least one value in it by the time the while loop hits.
while winner is False and len(moves) > 0:
g_string = gb.to_string()
if g_string == win_string:
winner = True
break
possibilities = gb.legal_moves(visited) # returns a list of possible moves to take
if len(possibilities) > 0:
moves.append(copy.deepcopy(gb))
gb.perform(possibilities[0]) # this modifies gb, according to the gameplay move.
# snipped, for brevity.
If after 100 iterations, I were to print moves, I would get 100 identical objects. If I print the object each time before appending it, they are definitely different at the time of appending.
To clarify, I would like copies of these objects (for use in things like a graph, to perform DFS and BFS on)
Here is more of my GameBoard class
class GameBoard:
number_of_rows = 3
rows = []
global random_puzzle
def __init__(self, setup):
#some code. fills in the rows. adds some things to that list. etcetc..
# more code
A:
Your code is valid for a simple dictionary object:
seq = 1
a_dict = {}
moves = []
while seq < 4:
a_dict['key' + str(seq)] = 'value' + str(seq)
moves.append(copy.deepcopy(a_dict))
seq = seq + 1
print moves
Somehow for your object, deepcopy does not reach the contents of your gameboard.
Is your gameboard data somehow stored outside of the object in which case only a pointer to it is copied? Which state of the board is saved, the first or the last one? Can you post more details about the structure of your object?
EDIT: Try adding your own getstate/setstate methods in order to tell deepcopy what data needs to copied between instances. For example if your rows array contains the gameboard:
def __getstate__(self):
return self.rows
def __setstate__(self, rows):
self.rows = rows
| Saving a deep copy of an object, then modifying it and saving another copy? | I have a 'GameBoard' class and am doing a search on it. I want to save the current gameboard in a list, change the state of the gameboard, save THAT one in a list, and so on (so I would have incremental versions of the gameboard as a game progresses).
I'm currently doing this with copy.deepcopy, but it doesn't seem to be saving and moving on. Here is a sample of my code:
moves = [] # just for reference. this has at least one value in it by the time the while loop hits.
while winner is False and len(moves) > 0:
g_string = gb.to_string()
if g_string == win_string:
winner = True
break
possibilities = gb.legal_moves(visited) # returns a list of possible moves to take
if len(possibilities) > 0:
moves.append(copy.deepcopy(gb))
gb.perform(possibilities[0]) # this modifies gb, according to the gameplay move.
# snipped, for brevity.
If after 100 iterations, I were to print moves, I would get 100 identical objects. If I print the object each time before appending it, they are definitely different at the time of appending.
To clarify, I would like copies of these objects (for use in things like a graph, to perform DFS and BFS on)
Here is more of my GameBoard class
class GameBoard:
number_of_rows = 3
rows = []
global random_puzzle
def __init__(self, setup):
#some code. fills in the rows. adds some things to that list. etcetc..
# more code
| [
"Your code is valid for a simple dictionary object:\nseq = 1\na_dict = {}\nmoves = []\nwhile seq < 4:\n a_dict['key' + str(seq)] = 'value' + str(seq)\n moves.append(copy.deepcopy(a_dict))\n seq = seq + 1\n\nprint moves\n\nSomehow for your object, deepcopy does not reach the contents of your gameboard. \nIs your gam... | [
0
] | [] | [] | [
"copy",
"python"
] | stackoverflow_0003891757_copy_python.txt |
Q:
python: retrieve names of all builtins
How can I retrieve names of all builtins for my current python distribution during runtime?
A:
I am not sure if this suffices, but you can fire up the interpreter and do the following
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
And you can see the dir value
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'atexit']
And from the modules, you can import builtin as module
http://effbot.org/librarybook/builtin.htm
| python: retrieve names of all builtins | How can I retrieve names of all builtins for my current python distribution during runtime?
| [
"I am not sure if this suffices, but you can fire up the interpreter and do the following\n>>> dir(__builtins__)\n['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingP... | [
4
] | [] | [] | [
"built_in",
"python"
] | stackoverflow_0003893287_built_in_python.txt |
Q:
What python html generator module should I use in a non-web application?
I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to output some html tags).
I found two alternatives on my first goolge search:
markup.py - http://markup.sourceforge.net/
HTML.py - http://www.decalage.info/en/python/html
Also, I feel that using a templating engine would be over-kill, but if you differ please say it and why.
Any other recommendation?
A:
Maybe you could try Markdown instead, and convert it to HTML on the fly?
A:
You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:
http://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py
(Full disclosure, I work with the person who originally wrote that version, and I also use it myself.)
A:
Why would a templating engine necessarily be overkill? You don't need the whole web framework just to use the templating engine (at least, for most templating engines). Mako for example can be used stand-alone just fine, and I often use it to generate html files (reports from a db and such)
A:
If you have just some simple static HTML files. Then why not use string templates like so.
import string
TEMPLATE_FORMAT = """
<html>
<head><title>Trial</title></head>
<body>
<div class="myclass">$my_div_data</div>
</body>
"""
my_div_data = "some_data_to_display_in_HTML"
TEMPLATE = string.Template(TEMPLATE_FORMAT)
html_data = TEMPLATE.safe_substitute(my_div_data)
open("out.html", "w").write(html_data)
Give this a shot if you don't have too big HTML files to generate. Saves you on the learning you need to do if you decide to use libraries.
A:
ElementTree can produce html with some limitations. I'd write it like this:
from xml.etree.ElementTree import ElementTree, Element, SubElement
import sys
html = Element('html')
head = SubElement(html, 'head')
style = SubElement(head, 'link')
style.attrib = {'rel': 'stylesheet', 'href': 'style.css', 'type': 'text/css'}
body = SubElement(html, 'body')
para = SubElement(body, 'p')
para.text = 'Lorem ipsum sit amet'
doc = ElementTree(html)
doc.write(sys.stdout)
In case of moderately complex html I'd stick with some templating engine: Jinja2, Mako, Cheetah, just to name a few.
A:
i recommend having a look at shpaml
| What python html generator module should I use in a non-web application? | I'm hacking a quick and dirty python script to generate some reports as static html files.
What would be a good module to easily build static html files outside the context of a web application?
My goals are simplicity (the HTML will not be very complex) and ease of use (I don't want to write a lot of code just to output some html tags).
I found two alternatives on my first goolge search:
markup.py - http://markup.sourceforge.net/
HTML.py - http://www.decalage.info/en/python/html
Also, I feel that using a templating engine would be over-kill, but if you differ please say it and why.
Any other recommendation?
| [
"Maybe you could try Markdown instead, and convert it to HTML on the fly?\n",
"You don't necessarily need something complex - for instance, here's a ~150 line library to generate HTML in a functional manner:\nhttp://github.com/Yelp/PushmasterApp/blob/master/pushmaster/taglib.py\n(Full disclosure, I work with the ... | [
6,
4,
3,
2,
2,
1
] | [] | [] | [
"html_generation",
"python"
] | stackoverflow_0003887393_html_generation_python.txt |
Q:
Read multiple lines from subprocess.Popen.stdout
I modified the source code from Fred Lundh's Python Standard Library.
The original source uses popen2 to communicate to subprocess, but I changed it to use subprocess.Popen() as follows.
import subprocess
import string
class Chess:
"Interface class for chesstool-compatible programs"
def __init__(self, engine = "/opt/local/bin/gnuchess"):
proc=subprocess.Popen([engine],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
self.fin, self.fout = proc.stdin, proc.stdout
s = self.fout.readline() <--
print s
if not s.startswith("GNU Chess"):
raise IOError, "incompatible chess program"
def move(self, move):
...
my = self.fout.readline() <--
...
def quit(self):
self.fin.write("quit\n")
self.fin.flush()
g = Chess()
print g.move("a2a4")
print g.move("b2b3")
g.quit()
It seems to run OK, but the gnuchess prints out multiple lines of messages as follows, but with self.fout.readline() it only shows one line.
Thinking...
...
R N B Q K B N R
How do I get multiple lines of message? readlines() method doesn't seem to work.
ADDED
I tested the code from movieyoda, but it doesn't work.
I think it's just correct that only readline() should work, not readlines() and read(), as one doesn't know when to stop reading except for the readline().
A:
To interact with gnuchess, I'd use pexpect.
import pexpect
import sys
game = pexpect.spawn('/usr/games/gnuchess')
# Echo output to stdout
game.logfile = sys.stdout
game.expect('White')
game.sendline('a2a4')
game.expect('White')
game.sendline('b2b3')
game.expect('White')
game.sendline('quit')
A:
I would just read it's output as it arrives. When the process dies, the subprocess module will take care of cleaning things up for you. You could do something like this -
l = list()
while True:
data = proc.stdout.read(4096)
if not data:
break
l.append(data)
file_data = ''.join(l)
All of this is a replacement for self.fout.readline(). Have not tried it. But should handle multiple lines.
| Read multiple lines from subprocess.Popen.stdout | I modified the source code from Fred Lundh's Python Standard Library.
The original source uses popen2 to communicate to subprocess, but I changed it to use subprocess.Popen() as follows.
import subprocess
import string
class Chess:
"Interface class for chesstool-compatible programs"
def __init__(self, engine = "/opt/local/bin/gnuchess"):
proc=subprocess.Popen([engine],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
self.fin, self.fout = proc.stdin, proc.stdout
s = self.fout.readline() <--
print s
if not s.startswith("GNU Chess"):
raise IOError, "incompatible chess program"
def move(self, move):
...
my = self.fout.readline() <--
...
def quit(self):
self.fin.write("quit\n")
self.fin.flush()
g = Chess()
print g.move("a2a4")
print g.move("b2b3")
g.quit()
It seems to run OK, but the gnuchess prints out multiple lines of messages as follows, but with self.fout.readline() it only shows one line.
Thinking...
...
R N B Q K B N R
How do I get multiple lines of message? readlines() method doesn't seem to work.
ADDED
I tested the code from movieyoda, but it doesn't work.
I think it's just correct that only readline() should work, not readlines() and read(), as one doesn't know when to stop reading except for the readline().
| [
"To interact with gnuchess, I'd use pexpect.\nimport pexpect\nimport sys\ngame = pexpect.spawn('/usr/games/gnuchess')\n# Echo output to stdout\ngame.logfile = sys.stdout\ngame.expect('White')\ngame.sendline('a2a4')\ngame.expect('White')\ngame.sendline('b2b3')\ngame.expect('White')\ngame.sendline('quit')\n\n",
"I ... | [
2,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003893473_python_subprocess.txt |
Q:
what's the quickest way to simple-merge files and what's the quickest way to split an array?
what's the quickest way to take a list of files and a name of an output file and merge them into a single file while removing duplicate lines?
something like
cat file1 file2 file3 | sort -u > out.file
in python.
prefer not to use system calls.
AND:
what's the quickest way to split a list in python into X chunks (list of lists) as equal as possible? (given a list and X.)
A:
First:
lines = set()
for filename in filenames:
with open(filename) as inF:
lines.update(inF)
with open(outfile, 'w') as outF:
outF.write(''.join(lines))
Second:
def chunk(bigList, x):
chunklen = len(bigList) / x
for i in xrange(0, len(bigList), chunklen):
yield bigList[i:i+chunklen]
listOfLists = list(chunk(bigList, x))
| what's the quickest way to simple-merge files and what's the quickest way to split an array? | what's the quickest way to take a list of files and a name of an output file and merge them into a single file while removing duplicate lines?
something like
cat file1 file2 file3 | sort -u > out.file
in python.
prefer not to use system calls.
AND:
what's the quickest way to split a list in python into X chunks (list of lists) as equal as possible? (given a list and X.)
| [
"First:\nlines = set()\nfor filename in filenames:\n with open(filename) as inF:\n lines.update(inF)\nwith open(outfile, 'w') as outF:\n outF.write(''.join(lines))\n\nSecond: \ndef chunk(bigList, x):\n chunklen = len(bigList) / x\n for i in xrange(0, len(bigList), chunklen):\n yield bigLis... | [
2
] | [
"For the first:\nlines = []\nfor filename in filenames:\n f = open(filename)\n lines.extend(f.read().split('\\n')\n f.close()\nlines = list(set(lines)) #remove duplicates\nf = open(outfile_name, 'w')\nf.write(''.join(lines))\n\nassuming that the files are a reasonable length as all the data from the files ... | [
-1
] | [
"python"
] | stackoverflow_0003893696_python.txt |
Q:
Getting implicit property names on a db.Model in Google App Engine?
How can I get access to the implicit property names of a db.Model in Google App Engine? In particular, assume I have the following:
class Foo(db.Model):
specific = db.IntegerProperty()
class Bar(db.Model):
foo = db.ReferenceProperty(Foo, collection_name = "bars")
if I attempt to get the property names on Foo, like so:
my_foo = Foo(specific = 42)
for key, prop in my_foo.properties().iteritems()
print "HERE bars won't show up"
then the my_foo.bars property doesn't show up. Or am I totally mistaken?
Any help greatly appreciated
edited model to be Python, not ruby
A:
(That model definition looks like a strange hybrid of Python and Ruby.)
I'm not clear on what you're trying to achieve here, but you can get a list of model property members using introspection:
[x for x in dir(Foo) if isinstance(getattr(Foo,x), db.Property)]
If you're just trying to add instances of Bar to Foo, you should create new Bar instances with their foo fields pointing at the Foo instance:
foo = Foo(specific=42)
foo.put()
Bar(foo=foo).put()
Bar(foo=foo).put()
logging.info("Foo bars: %r" % list(foo.bars))
| Getting implicit property names on a db.Model in Google App Engine? | How can I get access to the implicit property names of a db.Model in Google App Engine? In particular, assume I have the following:
class Foo(db.Model):
specific = db.IntegerProperty()
class Bar(db.Model):
foo = db.ReferenceProperty(Foo, collection_name = "bars")
if I attempt to get the property names on Foo, like so:
my_foo = Foo(specific = 42)
for key, prop in my_foo.properties().iteritems()
print "HERE bars won't show up"
then the my_foo.bars property doesn't show up. Or am I totally mistaken?
Any help greatly appreciated
edited model to be Python, not ruby
| [
"(That model definition looks like a strange hybrid of Python and Ruby.)\nI'm not clear on what you're trying to achieve here, but you can get a list of model property members using introspection: \n[x for x in dir(Foo) if isinstance(getattr(Foo,x), db.Property)]\n\nIf you're just trying to add instances of Bar to ... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003893405_google_app_engine_google_cloud_datastore_python.txt |
Q:
what can cause pdb.set_trace() to be ignored?
I'm trying to debug a Python program and I inserted a classic 'import pdb;pdb.set_trace()' line in a function, just before a call which generates a stack trace. However that call seems to be ignored, i.e. nothing happens and I don't get a pdb prompt.
At that point of the program, there is only one active thread. No monkey patching of the pdb module was detected.
Any help on what could cause the call to set_trace to be ignored is welcome. Thanks.
Platform info: Debian squeeze + python 2.6.5
Code extract:
import threading
print threading.active_count()
import pdb
print pdb
pdb.set_trace()
print "*****"
root_resource.init_publisher() # before changing uid
output:
<lots of stuff>
1
<module 'pdb' from '/usr/lib/python2.6/pdb.pyc'>
*****
<stack trace in init_publisher>
A:
Perhaps you've got some tricky code that manipulates the trace function in a complicated way? Or are you using an accelerator like psyco?
A:
This is going to waste the time of a number Python developers. Tonight I added myself to their ranks. I wish I had found this post before I spent 2 hours discovering a similar problem with a large library I am using. Subsequent Google searches hardly shed much light on the issue of pdb and pysco incompatability. The problem should be more visible to users starting out with pdb.
Deep within the guts of a library I was importing was a file which contained the following code:
try:
import psyco
psyco.bind(bdecode)
psyco.bind(bencode)
except ImportError:
pass
What a lovely gesture of the author, who obviously assumed no one using their code, and who had also installed psyco, would ever like to use a tool such as pdb to debug it ;-) Mind you, you could ask how were they mean't to know anyway?
Whilst exploring the problem I found that usage of:
import pdb; pdb.set_trace()
after the import of psyco, is just passed over; for neither rythme nor reason. Very frustrating indeed.
The problem does not effect debugging with PyDev or, I presume, other more advanced debuggers, which is I guess why it falls outside the radar of initial Google searches.
A:
You are probably not running that statement, either because:
the stacktrace is not where you
thought it was
you inserted the set_trace call in a
similar but wrong place
you are running a different .py file
than the one you edited
you have your own local pdb.py file
that is getting imported instead of
the one from the stdlib
| what can cause pdb.set_trace() to be ignored? | I'm trying to debug a Python program and I inserted a classic 'import pdb;pdb.set_trace()' line in a function, just before a call which generates a stack trace. However that call seems to be ignored, i.e. nothing happens and I don't get a pdb prompt.
At that point of the program, there is only one active thread. No monkey patching of the pdb module was detected.
Any help on what could cause the call to set_trace to be ignored is welcome. Thanks.
Platform info: Debian squeeze + python 2.6.5
Code extract:
import threading
print threading.active_count()
import pdb
print pdb
pdb.set_trace()
print "*****"
root_resource.init_publisher() # before changing uid
output:
<lots of stuff>
1
<module 'pdb' from '/usr/lib/python2.6/pdb.pyc'>
*****
<stack trace in init_publisher>
| [
"Perhaps you've got some tricky code that manipulates the trace function in a complicated way? Or are you using an accelerator like psyco?\n",
"This is going to waste the time of a number Python developers. Tonight I added myself to their ranks. I wish I had found this post before I spent 2 hours discovering a s... | [
7,
5,
1
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0003466552_debugging_python.txt |
Q:
Terminate subprocess in Windows, access denied
-
import time
import subprocess
from os.path import expanduser
chrome_path = expanduser('~\Local Settings\Application Data\Google\Chrome\Application\chrome.exe')
proc = subprocess.Popen(chrome_path)
time.sleep(4)
proc.terminate()
Output: WindowsError: [Error 5] Access is denied
How can I kill the Chrome process?
Python 2.6 on Windows XP.
A:
I don't know about Windows, but have noticed on Linux that Google Chrome "protects" itself from operating system control signals in a way that few programs do:
$ ps -lp 2345
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
4 S 1000 2345 1 0 80 0 - 17699 skb_re ? 00:00:00 chrome
$ kill -TERM 2345
$ kill -HUP 2345
$ kill -SEGV 2345
$ ps -lp 2345
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
4 S 1000 2345 1 0 80 0 - 17699 skb_re ? 00:00:00 chrome
I suspect this may be the root cause of your troubles. Incidentally, I'm posting this note from process 2345.
A:
what happens if you use TASKKILL /F /PID [number of process ID] ? Give it a try. Launch it through import OS
A:
I think the best bet is to find and close the window at the os level: http://python.net/crew/skippy/win32/Downloads.html.
| Terminate subprocess in Windows, access denied | -
import time
import subprocess
from os.path import expanduser
chrome_path = expanduser('~\Local Settings\Application Data\Google\Chrome\Application\chrome.exe')
proc = subprocess.Popen(chrome_path)
time.sleep(4)
proc.terminate()
Output: WindowsError: [Error 5] Access is denied
How can I kill the Chrome process?
Python 2.6 on Windows XP.
| [
"I don't know about Windows, but have noticed on Linux that Google Chrome \"protects\" itself from operating system control signals in a way that few programs do:\n$ ps -lp 2345\nF S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD\n4 S 1000 2345 1 0 80 0 - 17699 skb_re ? 00:00:00 ... | [
2,
0,
0
] | [] | [] | [
"python",
"subprocess",
"terminate",
"windows"
] | stackoverflow_0002868129_python_subprocess_terminate_windows.txt |
Q:
python - strtotime equivalent?
I'm using this to convert date time strings to a unix timestamp:
str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z"))))
However often the date structure isn't the same so I keep getting the following error message:
time data did not match format: data=Tue, 26 May 2009 19:58:20 -0500 fmt=%d %b %Y %H:%M:%S %Z
Does anyone know of any simply function to convert a string representation of a date/time to a unix timestamp in python? I really don't want to have to open a process to call a php script to echo the timestamp everytime time in a loop :)
A:
from dateutil.parser import parse
parse('Tue, 26 May 2009 19:58:20 -0500').strftime('%s')
# returns '1243364300'
| python - strtotime equivalent? | I'm using this to convert date time strings to a unix timestamp:
str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z"))))
However often the date structure isn't the same so I keep getting the following error message:
time data did not match format: data=Tue, 26 May 2009 19:58:20 -0500 fmt=%d %b %Y %H:%M:%S %Z
Does anyone know of any simply function to convert a string representation of a date/time to a unix timestamp in python? I really don't want to have to open a process to call a php script to echo the timestamp everytime time in a loop :)
| [
"from dateutil.parser import parse\n\nparse('Tue, 26 May 2009 19:58:20 -0500').strftime('%s')\n\n# returns '1243364300'\n\n"
] | [
27
] | [] | [] | [
"python"
] | stackoverflow_0003894010_python.txt |
Q:
Python to javascript communication
OK so im using websockets to let javascript talk to python and that works very well BUT the data i need to send often has several parts like an array, (username,time,text) but how could i send it ? I originally though to encode each one in base64 or urlencode then use a character like | which those encoding methods will never use and then split the information. Unfortunately i cant find a method which both python and javascript can both do.
So the question, is there a encoding method which bath can do OR is there a different better way i can send the data because i havent really done anything like this before. (I have but AJAX requests and i send that data URL encoded). Also im not sending miles of text, about 100bytes at a time if that.
thankyou !
edit
Most comments point to JSON,so, Whats the best convert to use for javascript because javascript stupidly cant convert string to JSON,or the other way round.
Finished
Well jaascript does have a native way to convert javascript to string, its just hidden form the world. JSON.stringify(obj, [replacer], [space]) to convert it to a string and JSON.parse(string, [reviver]) to convert it back
A:
JSON is definitely the way to go. It has a very small overhead and is capable of storing almost any kind of data. I am not a python expert, but i am sure that there is some kind of en/decoder available.
A:
Use json module (or simplejson prior to Python 2.6).
You'd only need to remember two functions: json.dumps and json.loads.
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> json.loads('["foo", {"bar": ["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
| Python to javascript communication | OK so im using websockets to let javascript talk to python and that works very well BUT the data i need to send often has several parts like an array, (username,time,text) but how could i send it ? I originally though to encode each one in base64 or urlencode then use a character like | which those encoding methods will never use and then split the information. Unfortunately i cant find a method which both python and javascript can both do.
So the question, is there a encoding method which bath can do OR is there a different better way i can send the data because i havent really done anything like this before. (I have but AJAX requests and i send that data URL encoded). Also im not sending miles of text, about 100bytes at a time if that.
thankyou !
edit
Most comments point to JSON,so, Whats the best convert to use for javascript because javascript stupidly cant convert string to JSON,or the other way round.
Finished
Well jaascript does have a native way to convert javascript to string, its just hidden form the world. JSON.stringify(obj, [replacer], [space]) to convert it to a string and JSON.parse(string, [reviver]) to convert it back
| [
"JSON is definitely the way to go. It has a very small overhead and is capable of storing almost any kind of data. I am not a python expert, but i am sure that there is some kind of en/decoder available.\n",
"Use json module (or simplejson prior to Python 2.6).\nYou'd only need to remember two functions: json.dum... | [
7,
1
] | [] | [] | [
"encoding",
"javascript",
"python",
"sockets"
] | stackoverflow_0003890390_encoding_javascript_python_sockets.txt |
Q:
SpringPython error following the book: AttributeError: 'module' object has no attribute 'ObjBase'
Well, I bought the book Spring Python 1.1 and I have been facing some problems that I cannot solve. I am going to write the code of each file in order to make sure everything is clear. If some of you know what is the problem, please let me know because I am desperate.
simple_service.py
class Service(object):
def happy_birthday(self, name):
results = []
for i in range(4):
if i <= 2:
results.append("Happy birthday dear %s!" % name)
else:
results.append("Happy birthday to you!")
return results
simple_service_server_ctx.py
from springpython.config import *
from springpython.remoting.pyro import *
from simple_service import *
class HappyBirthdayContext(PythonConfig):
def __init__(self):
PythonConfig.__init__(self)
@Object
def target_service(self):
return Service()
@Object
def service_exporter(self):
exporter = PyroServiceExporter()
exporter.service = self.target_service()
exporter.service_name = "service"
exporter.service_host = "127.0.0.1"
exporter.service_port = "7766"
exporter.after_properties_set()
return exporter
simple_server.py
from springpython.context import *
from simple_service_server_ctx import *
if __name__ == "__main__":
ctx = ApplicationContext(HappyBirthdayContext())
ctx.get_object("service_exporter")
I run on a terminal: python simple_server
and then I got the following error:
(spring)kiko@kiko-laptop:~/examples/spring$ python simple_server.py
Traceback (most recent call last):
File "simple_server.py", line 6, in <module>
ctx = ApplicationContext(HappyBirthdayContext())
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/context/__init__.py", line 45, in __init__
self.get_object(object_def.id, ignore_abstract=True)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/container/__init__.py", line 80, in get_object
comp = self._create_object(object_def)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/container/__init__.py", line 129, in _create_object
self._get_constructors_kw(object_def.named_constr))
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/factory/__init__.py", line 62, in create_object
return self.method()
File "<string>", line 2, in service_exporter
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1370, in object_wrapper
return _object_wrapper(f, theScope, parent, log_func_name, *args, **kwargs)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1350, in _object_wrapper
return _deco(f, scope, parent, log_func_name, *args, **kwargs)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1345, in _deco
results = f(*args, **kwargs)
File "/home/kiko/examples/spring/simple_service_server_ctx.py", line 22, in service_exporter
exporter.after_properties_set()
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/remoting/pyro/__init__.py", line 58, in after_properties_set
pyro_obj = Pyro.core.ObjBase()
AttributeError: 'module' object has no attribute 'ObjBase'
I have added on my own the line (file:simple_service_server_ctx.py):
exporter.after_properties_set()
since I read that it must be declared (line 19, link to source code).
Thanks in advance.
A:
I wonder what your Pyro version is. Here using Pyro 3.9.1-1 from Ubuntu 10.04 I have no problems with running your code. Could it be that you're using Pyro 4.x which if I recall correctly was released after the book had been published?
| SpringPython error following the book: AttributeError: 'module' object has no attribute 'ObjBase' | Well, I bought the book Spring Python 1.1 and I have been facing some problems that I cannot solve. I am going to write the code of each file in order to make sure everything is clear. If some of you know what is the problem, please let me know because I am desperate.
simple_service.py
class Service(object):
def happy_birthday(self, name):
results = []
for i in range(4):
if i <= 2:
results.append("Happy birthday dear %s!" % name)
else:
results.append("Happy birthday to you!")
return results
simple_service_server_ctx.py
from springpython.config import *
from springpython.remoting.pyro import *
from simple_service import *
class HappyBirthdayContext(PythonConfig):
def __init__(self):
PythonConfig.__init__(self)
@Object
def target_service(self):
return Service()
@Object
def service_exporter(self):
exporter = PyroServiceExporter()
exporter.service = self.target_service()
exporter.service_name = "service"
exporter.service_host = "127.0.0.1"
exporter.service_port = "7766"
exporter.after_properties_set()
return exporter
simple_server.py
from springpython.context import *
from simple_service_server_ctx import *
if __name__ == "__main__":
ctx = ApplicationContext(HappyBirthdayContext())
ctx.get_object("service_exporter")
I run on a terminal: python simple_server
and then I got the following error:
(spring)kiko@kiko-laptop:~/examples/spring$ python simple_server.py
Traceback (most recent call last):
File "simple_server.py", line 6, in <module>
ctx = ApplicationContext(HappyBirthdayContext())
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/context/__init__.py", line 45, in __init__
self.get_object(object_def.id, ignore_abstract=True)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/container/__init__.py", line 80, in get_object
comp = self._create_object(object_def)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/container/__init__.py", line 129, in _create_object
self._get_constructors_kw(object_def.named_constr))
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/factory/__init__.py", line 62, in create_object
return self.method()
File "<string>", line 2, in service_exporter
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1370, in object_wrapper
return _object_wrapper(f, theScope, parent, log_func_name, *args, **kwargs)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1350, in _object_wrapper
return _deco(f, scope, parent, log_func_name, *args, **kwargs)
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/config/__init__.py", line 1345, in _deco
results = f(*args, **kwargs)
File "/home/kiko/examples/spring/simple_service_server_ctx.py", line 22, in service_exporter
exporter.after_properties_set()
File "/home/kiko/.virtualenvs/spring/lib/python2.6/site-packages/springpython/remoting/pyro/__init__.py", line 58, in after_properties_set
pyro_obj = Pyro.core.ObjBase()
AttributeError: 'module' object has no attribute 'ObjBase'
I have added on my own the line (file:simple_service_server_ctx.py):
exporter.after_properties_set()
since I read that it must be declared (line 19, link to source code).
Thanks in advance.
| [
"I wonder what your Pyro version is. Here using Pyro 3.9.1-1 from Ubuntu 10.04 I have no problems with running your code. Could it be that you're using Pyro 4.x which if I recall correctly was released after the book had been published?\n"
] | [
1
] | [] | [] | [
"python",
"spring"
] | stackoverflow_0003889684_python_spring.txt |
Q:
Clustering problem
I've been tasked to find N clusters containing the most points for a certain data set given that the clusters are bounded by a certain size. Currently, I am attempting to do this by plugging in my data into a kd-tree, iterating over the data and finding its nearest neighbor, and then merging the points if the cluster they make does not exceed a limit. I'm not sure this approach will give me a global solution so I'm looking for ways to tweak it. If you can tell me what type of problem this would go under, that'd be great too.
A:
Check out scipy.clustering for a start. Key word searches can then give a lot of info on the different algorithms that are used there. Clustering is a big field, with a lot of research and practical applications, and a number of simple approaches that have been found to work fairly well, so you may not want to start by rolling your own.
This said, clustering algorithms are generally fairly easy to program, and if you do want to program your own, k-means and agglomerative clustering are some of the favorites that are quick to do.
Finally, I'm not sure that your idea of exactly N clusters that are bounded by a certain size is self-consistent, but it depends on exactly what you mean by "size" and "cluster" (are single points a cluster?).
Update:
Following the OP's comments below, I think that the standard clustering methods won't give an optimal solution to this problem because there's not a continuous metric for the "distance" between points that can be optimized. Although they may give a good solution or approximation in some cases. For a clustering approach I'd try k-means since the premise of this method is having a fixed N.
But instead of clustering, this seems more like a covering problem (i.e., you have N rectangles of fixed size and you're trying to cover all of the points with them), but I don't know much about these, so I'll leave it to someone else.
A:
If your number of clusters is fixed and you only want to maximize the number of points that are in these clusters then I think a greedy solution would be good :
find the rectangle that can contains the maximum number of points,
remove these points,
find the next rectangle
...
So how to find the rectangle of maximum area A (in fact each rectangle will have this area) that contains the maximum number of points ?
A rectangle is not really common for euclidean distance, before trying to solve this, could you precise if you really need rectangle or just some king of limit on the cluster size ? Would a circle/ellipse work ?
EDIT :
greedy will not work (see comment below) and it really need to be rectangles...
A:
link textActually, I think this is really pretty easy with two key assumptions.
1) Assume the by "a certain size" we can say "any cluster must be contained completely within a circle with radius, r".
2) All your points are candidate "seed" points at the center of the cluster.
First calculate all the distances less than r among all points. Now solve a set covering problem using only the feasible edges that are less than r. If any point has a nearest neighbor greater than r distance away, it forms its own cluster.
| Clustering problem | I've been tasked to find N clusters containing the most points for a certain data set given that the clusters are bounded by a certain size. Currently, I am attempting to do this by plugging in my data into a kd-tree, iterating over the data and finding its nearest neighbor, and then merging the points if the cluster they make does not exceed a limit. I'm not sure this approach will give me a global solution so I'm looking for ways to tweak it. If you can tell me what type of problem this would go under, that'd be great too.
| [
"Check out scipy.clustering for a start. Key word searches can then give a lot of info on the different algorithms that are used there. Clustering is a big field, with a lot of research and practical applications, and a number of simple approaches that have been found to work fairly well, so you may not want to s... | [
7,
0,
0
] | [] | [] | [
"algorithm",
"classification",
"cluster_analysis",
"nearest_neighbor",
"python"
] | stackoverflow_0003891645_algorithm_classification_cluster_analysis_nearest_neighbor_python.txt |
Q:
How to access a specific class instance by attribute in python?
Say I have a class Box with two attributes, self.contents and self.number. I have instances of box in a list called Boxes. Is there anyway to access/modify a specific instance by its attribute rather than iterating through Boxes? For example, if I want a box with box.number = 40 (and the list is not sorted) what would be the best way to modify its contents.
A:
If you need to do it more frequently and you have unique numbers, then create a dictionary:
numberedBox = dict((b.number, b) for b in Boxes)
you can then access your boxes directly with numbers:
numberedBox[40]
but if you want to change their number, you will have to modify the numberedBox dictionary too...
Otherwise yes, you have to iterate over the list.
A:
The most straightforward way is to use a list comprehension:
answer=[box for box in boxes if box.number==40]
Be warned though. This actually does iterate over the whole list. Since the list is not sorted, there is no faster method than to iterate over it (and thus do a linear search), unless you want to copy all the data into some other data structure (e.g. dict, set or sort the list).
A:
Use the filter builtin:
wanted_boxes = filter(lambda box: box.number == 40, boxes)
A:
Although not as flexible as using a dictionary, you might be able to get by using a simple lookup table to the map box numbers to a particular box in boxes. For example if you knew the box numbers could range 0...MAX_BOX_NUMBER, then the following would be very fast. It requires only one full scan of the Boxes list to setup the table.
MAX_BOX_NUMBER = ...
# setup lookup table
box_number = [None for i in xrange(MAX_BOX_NUMBER+1)]
for i in xrange(len(Boxes)):
box_number[Boxes[i].number] = Boxes[i]
box_number[42] # box in Boxes with given number (or None)
If the box numbers are in some other arbitrary range, some minor arithmetic would have to be applied to them before their use as indices. If the range is very large, but sparsely populated, dictionaries would be the way to go to save memory but would require more computation -- the usual trade-off.
| How to access a specific class instance by attribute in python? | Say I have a class Box with two attributes, self.contents and self.number. I have instances of box in a list called Boxes. Is there anyway to access/modify a specific instance by its attribute rather than iterating through Boxes? For example, if I want a box with box.number = 40 (and the list is not sorted) what would be the best way to modify its contents.
| [
"If you need to do it more frequently and you have unique numbers, then create a dictionary:\nnumberedBox = dict((b.number, b) for b in Boxes)\n\nyou can then access your boxes directly with numbers:\nnumberedBox[40]\n\nbut if you want to change their number, you will have to modify the numberedBox dictionary too..... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003893495_python.txt |
Q:
Filtering of an Object's property's property in google app engine
In an App Engine app, I store registered members in a table that looks like this:
class Member(db.Model):
user = db.UserProperty(required=True)
#other stuff
The problem starts when I need to check if a User is already in my Member table. GAE documentation says user value is not guaranteed not to change in time since it is composed by the user object+email. So it will change if the user changes the e-mail on that account.
I am using OpenID. So I though about using User.federated_identity() as a stable identifier.
However to check for this I'd have to do a Query like this:
u = users.get_current_user()
rm = Member.all().filter('user_federated_identity =',u.federated_identity()).get()
This is a valid query in Django, but apparenty not in GAE. What can I do here, other that loading all my members to memory and checking their federated_identity?
A:
You should be able to do this:
u = users.get_current_user()
rm = Member.all().filter('user =', u).get()
A:
Maybe you can identify your user by a unique key_name:
key_name = "member/%s" % users.get_current_user ().user_id
user_ref = Member.get_or_insert (key_name)
| Filtering of an Object's property's property in google app engine | In an App Engine app, I store registered members in a table that looks like this:
class Member(db.Model):
user = db.UserProperty(required=True)
#other stuff
The problem starts when I need to check if a User is already in my Member table. GAE documentation says user value is not guaranteed not to change in time since it is composed by the user object+email. So it will change if the user changes the e-mail on that account.
I am using OpenID. So I though about using User.federated_identity() as a stable identifier.
However to check for this I'd have to do a Query like this:
u = users.get_current_user()
rm = Member.all().filter('user_federated_identity =',u.federated_identity()).get()
This is a valid query in Django, but apparenty not in GAE. What can I do here, other that loading all my members to memory and checking their federated_identity?
| [
"You should be able to do this:\nu = users.get_current_user()\nrm = Member.all().filter('user =', u).get()\n\n",
"Maybe you can identify your user by a unique key_name:\nkey_name = \"member/%s\" % users.get_current_user ().user_id\nuser_ref = Member.get_or_insert (key_name)\n\n"
] | [
1,
0
] | [
"GAE User API explicitly mentions user_id() as a permanent identifier that persists across e-mail changes. You can store it in separate field in model.\nNote that it is only supported for Google Accounts.\n"
] | [
-1
] | [
"google_app_engine",
"python"
] | stackoverflow_0003890285_google_app_engine_python.txt |
Q:
Background Running Python Script keeps stopping
I made a .pyw python script that I want to have running in the background of my computer.
Right now I have it set to launch by putting it in the Startup folder of my Windows 7 computer, which should trigger it to launch whenever it starts up.
The problem is that the script seems to stop running at some point for some reason. I think it simply stops when my computer goes to sleep and doesn't start running again afterwards.
Is there a "more correct" way to have a background task running that wouldn't have it die every time the computer goes to sleep?
A:
If there really is need for a continuously running background process, you should look into making a service.
pywin32 helps in creating NT services with python
If you're into .NET, you can try also IronPython, but I don't know whether that is more easy.
| Background Running Python Script keeps stopping | I made a .pyw python script that I want to have running in the background of my computer.
Right now I have it set to launch by putting it in the Startup folder of my Windows 7 computer, which should trigger it to launch whenever it starts up.
The problem is that the script seems to stop running at some point for some reason. I think it simply stops when my computer goes to sleep and doesn't start running again afterwards.
Is there a "more correct" way to have a background task running that wouldn't have it die every time the computer goes to sleep?
| [
"If there really is need for a continuously running background process, you should look into making a service.\npywin32 helps in creating NT services with python\nIf you're into .NET, you can try also IronPython, but I don't know whether that is more easy.\n"
] | [
0
] | [] | [] | [
"background_process",
"python",
"sleep"
] | stackoverflow_0003894360_background_process_python_sleep.txt |
Q:
Python web programming with standard library
I want to write a simple python web application to provide a gui to a command line program (think of hg serve, for example). It would run locally only. I don't want it to have any external dependencies for an easier deployment, so python web programming in general wouldn't apply here
How can it be done with a minimal hassle? Any pointer how to do it easily with cgi or wsgi, string.Template or string.Formatter? I'd prefer a Python 2.6 solution, but even a Python 3.x one is OK. I'd also prefer using a few html templates to manually assembling html together.
UPDATE:
The ideal solution would include ways
to process a form
to upload/download a file
to output html
to start a webserver
A:
The wsgiref package from the standard library has a simple server to serve wsgi applications. You can use it to run your own framework-less wsgi application, a minimal wsgi application isn't terribly difficult (see the hello world example at the end of the wsgiref documentation page)
You might want to relax the "standard library" requirement a little. You're going to have "dependencies" on your own modules anyway, is it really that bad to use something where someone else has already done the work? Some of the so-called "microframeworks" shouldn't be too much of a problem for deployment. Bottle for example, comes as a single file module and has no dependencies other than stdlib (haven't used Bottle yet myself, but I picked that one as an example mainly because of the single file/no dependencies)
A:
Are you looking for something like SimpleHTTPServer?
http://docs.python.org/library/simplehttpserver.html#module-SimpleHTTPServer
A:
Maybe twisted is the way to go? Or do you consider this to be too much of an external dependency?
| Python web programming with standard library | I want to write a simple python web application to provide a gui to a command line program (think of hg serve, for example). It would run locally only. I don't want it to have any external dependencies for an easier deployment, so python web programming in general wouldn't apply here
How can it be done with a minimal hassle? Any pointer how to do it easily with cgi or wsgi, string.Template or string.Formatter? I'd prefer a Python 2.6 solution, but even a Python 3.x one is OK. I'd also prefer using a few html templates to manually assembling html together.
UPDATE:
The ideal solution would include ways
to process a form
to upload/download a file
to output html
to start a webserver
| [
"The wsgiref package from the standard library has a simple server to serve wsgi applications. You can use it to run your own framework-less wsgi application, a minimal wsgi application isn't terribly difficult (see the hello world example at the end of the wsgiref documentation page)\nYou might want to relax the \... | [
4,
0,
0
] | [] | [] | [
"cgi",
"python",
"standard_library"
] | stackoverflow_0003893774_cgi_python_standard_library.txt |
Q:
PyQt and QSignalMapper/lambdas - multiple signals, single slot
I have a list of actions on a menu in PyQt, one for each different feed I want to display. So I have a Y that sets the active feed to Y, Z sets it to Z, etc. (For a webcomic reading program).
I have each on the menu, and felt that an automated approach might be better; rather than typing out each time. Something like a function that adds it to a dictionary, then connects it up with a signal for each to a single slot.
However, I want that slot function, say it's called Foo, to take a parameter to decide what has been clicked. So if X was clicked, then X, Y passes Y, etc.
Looked around, and one SO question said to use a lambda, which didn't look...right somehow.
The other way was with QSignalMapper. I tried looking for this, but couldn't find an example of how to use it.
Can anyone help?
Thanks!
A:
You can use functools.partial (link to the documentation):
import functools
...
# note that these are the 'new style' slot connections (not necessarily needed)
self.menu_entry_x.triggered.connect(functools.partial(myfunc, x))
self.menu_entry_y.triggered.connect(functools.partial(myfunc, y))
The example is above is very basic, but I could elaborate if you have more questions.
| PyQt and QSignalMapper/lambdas - multiple signals, single slot | I have a list of actions on a menu in PyQt, one for each different feed I want to display. So I have a Y that sets the active feed to Y, Z sets it to Z, etc. (For a webcomic reading program).
I have each on the menu, and felt that an automated approach might be better; rather than typing out each time. Something like a function that adds it to a dictionary, then connects it up with a signal for each to a single slot.
However, I want that slot function, say it's called Foo, to take a parameter to decide what has been clicked. So if X was clicked, then X, Y passes Y, etc.
Looked around, and one SO question said to use a lambda, which didn't look...right somehow.
The other way was with QSignalMapper. I tried looking for this, but couldn't find an example of how to use it.
Can anyone help?
Thanks!
| [
"You can use functools.partial (link to the documentation):\nimport functools\n...\n\n# note that these are the 'new style' slot connections (not necessarily needed)\nself.menu_entry_x.triggered.connect(functools.partial(myfunc, x))\nself.menu_entry_y.triggered.connect(functools.partial(myfunc, y))\n\nThe example i... | [
5
] | [] | [] | [
"pyqt",
"python",
"qt",
"signals",
"signals_slots"
] | stackoverflow_0003893876_pyqt_python_qt_signals_signals_slots.txt |
Q:
example function in Python: counting words
I'm a bit rusty in Python and am just looking for help implementing an example function to count words (this is just a sample target for a scons script that doesn't do anything "real"):
def countWords(target, source, env):
if (len(target) == 1 and len(source) == 1):
fin = open(str(source[0]), 'r')
# do something with "f.read()"
fin.close()
fout = open(str(target[0]), 'w')
# fout.write(something)
fout.close()
return None
Could you help me fill in the details? The usual way to count words is to read each line, break up into words, and for each word in the line increment a counter in a dictionary; then for the output, sort the words by decreasing count.
edit: I'm using Python 2.6 (Python 2.6.5 to be exact)
A:
from collections import defaultdict
def countWords(target, source, env):
words = defaultdict(int)
if (len(target) == 1 and len(source) == 1):
with open(str(source[0]), 'r') as fin:
for line in fin:
for word in line.split():
words[word] += 1
with open(str(target[0]), 'w') as fout:
for word in sorted(words, key=words.__getitem__, reverse=True):
fout.write('%s\n' % word)
return None
A:
Without knowing why env exists, I can only do the following:
def countWords(target, source, env):
wordCount = {}
if len(target) == 1 and len(source) == 1:
with fin as open(source[0], 'r'):
for line in f
for word in line.split():
if word in wordCount.keys():
wordCount[word] += 1
else:
wordCount[word] = 0
rev = {}
for v in wordCount.values():
rev[v] = []
for w in wordCount.keys():
rev[wordCOunt[w]].append(w)
with open(target[0], 'w') as f:
for v in rev.keys():
f.write("%d: %s\n" %(v, " ".join(rev[v])))
A:
There is a helpful example here. It works roughly as you describe and also counts sentences.
A:
Not too efficient but it is concise!
with open(fname) as f:
res = {}
for word in f.read().split():
res[word] = res.get(word, 0)+1
with open(dest, 'w') as f:
f.write("\n".join(sorted(res, key=lambda w: -res[w])))
A:
Here my version:
import string
import itertools as it
drop = string.punctuation+string.digits
def countWords(target, source, env=''):
inputstring=open(source).read()
words = sorted(word.strip(drop)
for word in inputstring.lower().replace('--',' ').split())
wordlist = sorted([(word, len(list(occurances)))
for word, occurances in it.groupby(words, lambda x: x)],
key = lambda x: x[1],
reverse = True)
with open(target,'w') as results:
results.write('\n'.join('%16s : %s' % word for word in wordlist))
| example function in Python: counting words | I'm a bit rusty in Python and am just looking for help implementing an example function to count words (this is just a sample target for a scons script that doesn't do anything "real"):
def countWords(target, source, env):
if (len(target) == 1 and len(source) == 1):
fin = open(str(source[0]), 'r')
# do something with "f.read()"
fin.close()
fout = open(str(target[0]), 'w')
# fout.write(something)
fout.close()
return None
Could you help me fill in the details? The usual way to count words is to read each line, break up into words, and for each word in the line increment a counter in a dictionary; then for the output, sort the words by decreasing count.
edit: I'm using Python 2.6 (Python 2.6.5 to be exact)
| [
"from collections import defaultdict\n\ndef countWords(target, source, env):\n words = defaultdict(int)\n if (len(target) == 1 and len(source) == 1):\n with open(str(source[0]), 'r') as fin:\n for line in fin:\n for word in line.split():\n words[word] += 1\n... | [
7,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0003894265_python_python_2.6.txt |
Q:
python + mongo issue
I'm playing around with mongodb (documentation isn't very complete):
tmpQuery = collection.find({"title_full": "kdsljfklsadfklj"})
print tmpQuery[0]['title_full']
That just echo's "no such item for Cursor instance", what is an if statement to determine if the variable tmpQuery has a valid result set and not empty?
A:
oh geez, issue solved with:
tmpQuery.count()
| python + mongo issue | I'm playing around with mongodb (documentation isn't very complete):
tmpQuery = collection.find({"title_full": "kdsljfklsadfklj"})
print tmpQuery[0]['title_full']
That just echo's "no such item for Cursor instance", what is an if statement to determine if the variable tmpQuery has a valid result set and not empty?
| [
"oh geez, issue solved with:\ntmpQuery.count()\n\n"
] | [
4
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0003894419_mongodb_python.txt |
Q:
String to datetime
I saved a datetime.datetime.now() as a string.
Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
A:
from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7],
'%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')
A:
You don't need to create an intermediate string.
You can go directly from a datetime to a string with strftime():
>>> datetime.now().strftime('%b %d %Y')
'Oct 08 2010'
A:
There's no one-liner way, because of your apparent requirement of the grammatical ordinal.
It appears you're using a 2.6 release of Python, or perhaps later. In such a case,
datetime.datetime.strptime("2010-10-08 14:26:01.220000", "%Y-%m-%d %H:%M:%S.%f").strftime("%b %d %Y")
comes close, yielding
Oct 08 2010
To insist on '8th' rather than '08' involves calculating the %b and %Y parts as above, and writing a decimal-to-ordinal function to intercalate between them.
| String to datetime | I saved a datetime.datetime.now() as a string.
Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
| [
"\nfrom datetime import datetime\ndatetime.strptime('2010-10-08 14:26:01.220000'[:-7], \n '%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')\n\n",
"You don't need to create an intermediate string.\nYou can go directly from a datetime to a string with strftime():\n>>> datetime.now().strftime('%b %d %Y')\n'Oc... | [
6,
2,
0
] | [] | [] | [
"date_format",
"datetime",
"python"
] | stackoverflow_0003894462_date_format_datetime_python.txt |
Q:
Replace numeric character references in XML document using Python
I am struggling with the following issue: I have an XML string that contains the following tag and I want to convert this, using cElementTree, to a valid XML document:
<tag>#55296;#57136;#55296;#57149;#55296;#57139;#55296;#57136;#55296;#57151;#55296;
#57154;#55296;#57136;</tag>
but each # sign is preceded by a & sign and hence the output looks like: 𐌰𐌽𐌳𐌰𐌿𐍂𐌰
This is a unicode string and the encoding is UTF-8. I want to discard these numeric character references because they are not legal XML in a valid XML document (see Parser error using Perl XML::DOM module, "reference to invalid character number")
I have tried different regular expression to match these numeric character references. For example, I have tried the following (Python) regex:
RE_NUMERIC_CHARACTER = re.compile('&#[\d{1,5}]+;')
This does work in regular python session but as soon as I use the same regex in my code then it doesn't work, presumably because those numeric characters have been interpreted (and are shown as boxes or question marks).
I have also tried the unescape function from http://effbot.org/zone/re-sub.htm but that does not work either.
Thus: how can I match, using a regular expression in Python, these numeric character references and create a valid XML document?
A:
Eurgh. You've got surrogates (UTF-16 code units in the range D800-DFFF), which some fool has incorrectly encoded individually instead of using a pair of code units for a single character. It would be ideal to replace this mess with what it should look like:
<tag>𐌰𐌽𐌳𐌰𐌿𐍂𐌰</tag>
Or, just as valid, in literal characters (if you've got a font that can display the Gothic alphabet):
<tag></tag>
Usually, it would be best to do replacement operations like this on parsed text nodes, to avoid messing up non-character-reference sequences in other places like comments or PIs. However of course that's not possible in this case since this isn't really XML at all. You could try to fix it up with a crude regex, though it would be better to find out where the invalid input is coming from and kick the person responsible until they fix it.
>>> def lenient_deccharref(m):
... return unichr(int(m.group(1)))
...
>>> tag= '<tag>��������������</tag>'
>>> re.sub('&#(\d+);', lenient_deccharref, tag).encode('utf-8')
'<tag>\xf0\x90\x8c\xb0\xf0\x90\x8c\xbd\xf0\x90\x8c\xb3\xf0\x90\x8c\xb0\xf0\x90\x8c\xbf\xf0\x90\x8d\x82\xf0\x90\x8c\xb0</tag>'
This is the correct UTF-8 encoding of . The utf-8 codec allows you to encode a sequence of surrogates to correct UTF-8 even on a wide-Unicode platform where the surrogates should not have appeared in the string in the first place.
>>> _.decode('utf-8')
u'<tag>\U00010330\U0001033d\U00010333\U00010330\U0001033f\U00010342\U00010330</tag>'
| Replace numeric character references in XML document using Python | I am struggling with the following issue: I have an XML string that contains the following tag and I want to convert this, using cElementTree, to a valid XML document:
<tag>#55296;#57136;#55296;#57149;#55296;#57139;#55296;#57136;#55296;#57151;#55296;
#57154;#55296;#57136;</tag>
but each # sign is preceded by a & sign and hence the output looks like: 𐌰𐌽𐌳𐌰𐌿𐍂𐌰
This is a unicode string and the encoding is UTF-8. I want to discard these numeric character references because they are not legal XML in a valid XML document (see Parser error using Perl XML::DOM module, "reference to invalid character number")
I have tried different regular expression to match these numeric character references. For example, I have tried the following (Python) regex:
RE_NUMERIC_CHARACTER = re.compile('&#[\d{1,5}]+;')
This does work in regular python session but as soon as I use the same regex in my code then it doesn't work, presumably because those numeric characters have been interpreted (and are shown as boxes or question marks).
I have also tried the unescape function from http://effbot.org/zone/re-sub.htm but that does not work either.
Thus: how can I match, using a regular expression in Python, these numeric character references and create a valid XML document?
| [
"Eurgh. You've got surrogates (UTF-16 code units in the range D800-DFFF), which some fool has incorrectly encoded individually instead of using a pair of code units for a single character. It would be ideal to replace this mess with what it should look like:\n<tag>𐌰𐌽𐌳𐌰𐌿𐍂... | [
4
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0003894564_python_xml.txt |
Q:
Timed out after 30000ms
When I use SeleniumRC,sometimes I meet a error, but sometimes not. I guess it's related to the time of wait_for_page_to_load(), but I don't know how long will it need?
The error information:
Exception: Timed out after 30000ms
File "C:\Users\Herta\Desktop\test\newtest.py", line 9, in <module>
sel.open(url)
File "C:\Users\Herta\Desktop\test\selenium.py", line 764, in open
self.do_command("open", [url,])
File "C:\Users\Herta\Desktop\test\selenium.py", line 215, in do_command
raise Exception, data
This is my program:
from selenium import selenium
url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp?Param=4502931&ProtId=1&ProtType=Receptor#'
sel = selenium('localhost', 4444, '*firefox', url)
sel.start()
sel.open(url)
sel.wait_for_page_to_load(1000)
f = sel.get_html_source()
sav = open('test.html','w')
sav.write(f)
sav.close()
sel.stop()
A:
Timing is a big issue when automating UI pages. You want to make sure you use timeouts when needed and provide the needed time for certain events. I see that you have
sel.open(url)
sel.wait_for_page_to_load(1000)
The sel.wait_for_page_to_load command after a sel.open call is redundant. All sel.open commands have a built in wait. This may be the cause of your problem because selenium waits as a part of the built in process of the sel.open command. Then selenium is told to wait again for the page to load. Since no page is loaded. It throws an error.
However, this is unlikely since it is throwing the trace on the sel.open command. Wawa's response above may be your best bet.
A:
The "Timed out after 30000ms" message is coming from the sel.open(url) call which uses the selenium default timeout. Try increasing this time using sel.set_timeout("timeout"). I would suggest 60 seconds as a good starting point, if 60 seconds doesn't work, try increasing the timeout. Also make sure that you can get to the page normally.
from selenium import selenium
url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp?Param=4502931&ProtId=1&ProtType=Receptor#'
sel = selenium('localhost', 4444, '*firefox', url)
sel.set_timeout('60000')
sel.start()
sel.open(url)
sel.wait_for_page_to_load(1000)
f = sel.get_html_source()
sav = open('test.html','w')
sav.write(f)
sav.close()
sel.stop()
A:
I had this problem and it was windows firewall blocking selenium server. Have you tried adding an exception to your firewall?
| Timed out after 30000ms | When I use SeleniumRC,sometimes I meet a error, but sometimes not. I guess it's related to the time of wait_for_page_to_load(), but I don't know how long will it need?
The error information:
Exception: Timed out after 30000ms
File "C:\Users\Herta\Desktop\test\newtest.py", line 9, in <module>
sel.open(url)
File "C:\Users\Herta\Desktop\test\selenium.py", line 764, in open
self.do_command("open", [url,])
File "C:\Users\Herta\Desktop\test\selenium.py", line 215, in do_command
raise Exception, data
This is my program:
from selenium import selenium
url = 'http://receptome.stanford.edu/hpmr/SearchDB/getGenePage.asp?Param=4502931&ProtId=1&ProtType=Receptor#'
sel = selenium('localhost', 4444, '*firefox', url)
sel.start()
sel.open(url)
sel.wait_for_page_to_load(1000)
f = sel.get_html_source()
sav = open('test.html','w')
sav.write(f)
sav.close()
sel.stop()
| [
"Timing is a big issue when automating UI pages. You want to make sure you use timeouts when needed and provide the needed time for certain events. I see that you have\nsel.open(url)\nsel.wait_for_page_to_load(1000)\n\nThe sel.wait_for_page_to_load command after a sel.open call is redundant. All sel.open commands h... | [
1,
0,
0
] | [] | [] | [
"python",
"selenium_rc"
] | stackoverflow_0003458830_python_selenium_rc.txt |
Q:
figuring out how to get all of the public ips of a machine
I am running my code on multiple VPSes (with more than one IP, which are set up as aliases to the network interfaces) and I am trying to figure out a way such that my code acquires the IP addresses from the network interfaces on the fly and bind to it. Any ideas on how to do it in python without adding a 3rd party library ?
Edit I know about socket.gethostbyaddr(socket.gethostname()) and about the 3rd party package netifaces, but I am looking for something more elegant from the standard library ... and parsing the output of the ifconfig command is not something elegant :)
A:
The IP addresses are assigned to your VPSes, no possibility to change them on the fly.
You have to open a SSH tunnel to or install a proxy on your VPSes.
I think a SSH tunnel would be the best way how to do it, and then use it as SOCKS5 proxy from Python.
A:
This is how to get all IP addresses of the server the script is running on:
(this is as much elegant as possible and it only needs the standard library)
import socket
import fcntl
import struct
import array
def all_interfaces():
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * bytes)
outbytes = struct.unpack('iL', fcntl.ioctl(
s.fileno(),
0x8912, # SIOCGIFCONF
struct.pack('iL', bytes, names.buffer_info()[0])
))[0]
namestr = names.tostring()
return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)]
| figuring out how to get all of the public ips of a machine | I am running my code on multiple VPSes (with more than one IP, which are set up as aliases to the network interfaces) and I am trying to figure out a way such that my code acquires the IP addresses from the network interfaces on the fly and bind to it. Any ideas on how to do it in python without adding a 3rd party library ?
Edit I know about socket.gethostbyaddr(socket.gethostname()) and about the 3rd party package netifaces, but I am looking for something more elegant from the standard library ... and parsing the output of the ifconfig command is not something elegant :)
| [
"The IP addresses are assigned to your VPSes, no possibility to change them on the fly.\nYou have to open a SSH tunnel to or install a proxy on your VPSes.\nI think a SSH tunnel would be the best way how to do it, and then use it as SOCKS5 proxy from Python.\n",
"This is how to get all IP addresses of the server ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003881951_python.txt |
Q:
json.dumps(pickle.dumps(u'å')) raises UnicodeDecodeError
Is this a bug?
>>> import json
>>> import cPickle
>>> json.dumps(cPickle.dumps(u'å'))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/encoder.py", line 361, in encode
return encode_basestring_ascii(o)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-3: invalid data
A:
The json module is expecting strings to encode text. Pickled data isn't text, it's 8-bit binary.
One simple workaround, if you really need to send pickled data over JSON, is to use base64:
j = json.dumps(base64.b64encode(cPickle.dumps(u'å')))
cPickle.loads(base64.b64decode(json.loads(j)))
Note that this is very clearly a Python bug. Protocol version 0 is explicitly documented as ASCII, yet å is sent as the non-ASCII byte \xe5 instead of encoding it as "\u00E5". This bug was reported upstream--and the ticket was closed without the bug being fixed. http://bugs.python.org/issue2980
A:
Could be a bug in pickle. My python documentation says (for used pickle format): Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python. [...] If a protocol is not specified, protocol 0 is used.
>>> cPickle.dumps(u'å').decode('ascii')
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1: ordinal not in range(128)
that aint no ASCII
and, don't know whether its relevant, or even a problem:
>>> cPickle.dumps(u'å') == pickle.dumps(u'å')
False
A:
I'm using Python2.6 and your code runs without any error.
In [1]: import json
In [2]: import cPickle
In [3]: json.dumps(cPickle.dumps(u'å'))
Out[3]: '"V\\u00e5\\np1\\n."'
BTW, what's your system default encoding, in my case, it's
In [6]: sys.getdefaultencoding()
Out[6]: 'ascii'
| json.dumps(pickle.dumps(u'å')) raises UnicodeDecodeError | Is this a bug?
>>> import json
>>> import cPickle
>>> json.dumps(cPickle.dumps(u'å'))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/encoder.py", line 361, in encode
return encode_basestring_ascii(o)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-3: invalid data
| [
"The json module is expecting strings to encode text. Pickled data isn't text, it's 8-bit binary.\nOne simple workaround, if you really need to send pickled data over JSON, is to use base64:\nj = json.dumps(base64.b64encode(cPickle.dumps(u'å')))\ncPickle.loads(base64.b64decode(json.loads(j)))\n\nNote that this is ... | [
7,
1,
0
] | [] | [] | [
"json",
"pickle",
"python"
] | stackoverflow_0003895036_json_pickle_python.txt |
Q:
Open file into array, search for string and return value
Alright, I've been working on this for a while and cannot get it.
I'm making a method that accepts a filename, and a pattern.
E.g findPattern(fname, pat)
Then the goal is to look for that pattern, say the string "apple" within the text file that is opened, and return it's location by [line, beginning character index]
I'm new to python and have been told numerous ways, but they are either too complicated or we aren't allowed to use them such as index; we are specifically supposed to use arrays.
My thoughts were two nested for loops, the outside goes through each index of the textfile array, and the inner for loop compares the first letter of the desired pattern. If found, the inner loop will inrement so now it's checking the p in apple vs the text file.
One major problem is I cannot get the file into an array, I've only been able to do an entire line.
Here's something I have, although doesn't quite work. I was just experimenting with .tell to show me where it's at but it's always at 141, which I believe is the EOF but I haven't checked.
#.....Id #
#.....Name
#########################
#my intent was for you to write HW3 code as iteration or
#nested iterations that explicitly index the character
#string as an array; i.e, the Python index() also known as
#string.index() function is not allowed for this homework.
########################
print
fname = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
f = open(fname, "r")
for line in f:
if pat in line:
print "Found it @ " +(str( f.tell()))
break
else:
print "No esta..."
print findPattern(fname, pattern)
EDIT:
fname = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
arr = array.array('c', open(fname, 'rb').read())
for i in xrange(len(arr)):
if ''.join(arr[i:i+len(pat)]) == pat:
print 'Found @ %d' % i
print
findPattern(fname, pattern)
So from the new code replaced above, I'm getting what's below. I know it's something dumb like the array not being declared but I'm not exactly sure the python syntax for that, doesn't an array need to have a set size when you declare it?
lynx:desktop $ python hw3.py
Enter filename: declaration.txt
Enter pattern: become
Traceback (most recent call last):
File "hw3.py", line 25, in <module>
findPattern(fname, pattern)
File "hw3.py", line 17, in findPattern
arr = array.array('c', open(fname, 'rb').read())
NameError: global name 'array' is not defined
EDIT:
And, completed! Thanks guys.
This is how I finagled it..
#Iterate through
for i in xrange(len(arr)):
#Check for endline to increment linePos
if arr[i] == '\n':
linePos = linePos + 1
colPos = i
#Compare a chunk of array the same size
#as pat with pat itself
if ''.join(arr[i:i+len(pat)]) == pat:
#Account for newline with absolute position
resultPos = i - colPos
print 'Found @ %d on line %d' % (resultPos, linePos)
A:
The only way to get text data into an array is as chars:
a = array.array('c', open(filename, 'rb').read())
From there, you can simply iterate over it and convert each subarray with the same length as your substring to a string to compare:
for i in xrange(len(a)):
if ''.join(a[i:i+len(substring)]) == substring:
print 'Found @ %d!' % i
This is however deeply un-pythonic and painfully slow.
If by array you mean a list (the two terms have very different meanings in Python):
pos = 0
for line in open(filename):
for i in xrange(len(line)):
if line[i:i+len(substring)] == substring:
print 'Found @ %d!' % (pos + i)
pos += len(line) + 2 # 1 if on Linux
This is also slow and un-pythonic, but vaguely less so than the previous option. If any of these really is what you've been asked to do, your teacher probably shouldn't be teaching Python. :p
| Open file into array, search for string and return value | Alright, I've been working on this for a while and cannot get it.
I'm making a method that accepts a filename, and a pattern.
E.g findPattern(fname, pat)
Then the goal is to look for that pattern, say the string "apple" within the text file that is opened, and return it's location by [line, beginning character index]
I'm new to python and have been told numerous ways, but they are either too complicated or we aren't allowed to use them such as index; we are specifically supposed to use arrays.
My thoughts were two nested for loops, the outside goes through each index of the textfile array, and the inner for loop compares the first letter of the desired pattern. If found, the inner loop will inrement so now it's checking the p in apple vs the text file.
One major problem is I cannot get the file into an array, I've only been able to do an entire line.
Here's something I have, although doesn't quite work. I was just experimenting with .tell to show me where it's at but it's always at 141, which I believe is the EOF but I haven't checked.
#.....Id #
#.....Name
#########################
#my intent was for you to write HW3 code as iteration or
#nested iterations that explicitly index the character
#string as an array; i.e, the Python index() also known as
#string.index() function is not allowed for this homework.
########################
print
fname = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
f = open(fname, "r")
for line in f:
if pat in line:
print "Found it @ " +(str( f.tell()))
break
else:
print "No esta..."
print findPattern(fname, pattern)
EDIT:
fname = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
arr = array.array('c', open(fname, 'rb').read())
for i in xrange(len(arr)):
if ''.join(arr[i:i+len(pat)]) == pat:
print 'Found @ %d' % i
print
findPattern(fname, pattern)
So from the new code replaced above, I'm getting what's below. I know it's something dumb like the array not being declared but I'm not exactly sure the python syntax for that, doesn't an array need to have a set size when you declare it?
lynx:desktop $ python hw3.py
Enter filename: declaration.txt
Enter pattern: become
Traceback (most recent call last):
File "hw3.py", line 25, in <module>
findPattern(fname, pattern)
File "hw3.py", line 17, in findPattern
arr = array.array('c', open(fname, 'rb').read())
NameError: global name 'array' is not defined
EDIT:
And, completed! Thanks guys.
This is how I finagled it..
#Iterate through
for i in xrange(len(arr)):
#Check for endline to increment linePos
if arr[i] == '\n':
linePos = linePos + 1
colPos = i
#Compare a chunk of array the same size
#as pat with pat itself
if ''.join(arr[i:i+len(pat)]) == pat:
#Account for newline with absolute position
resultPos = i - colPos
print 'Found @ %d on line %d' % (resultPos, linePos)
| [
"The only way to get text data into an array is as chars:\na = array.array('c', open(filename, 'rb').read())\n\nFrom there, you can simply iterate over it and convert each subarray with the same length as your substring to a string to compare:\nfor i in xrange(len(a)):\n if ''.join(a[i:i+len(substring)]) == subst... | [
1
] | [] | [] | [
"arrays",
"file",
"python",
"search",
"string"
] | stackoverflow_0003894572_arrays_file_python_search_string.txt |
Q:
Python: Changing process name with setproctitle
I have a python script which launches a number of C++ programs, each program is passed a command line parameter as shown below
process_path "~/test/"
process_name "test"
num_process = 10
for p in range(1, num_processes, 1):
subprocess.Popen([process_path + process_name, str(p)], shell = False)
Is it possible to us setproctitle to rename each of these process so that I could include the command line parameter as part of the process name, if so , how would you do it?
A:
setproctitle can only change it's "own" process title as I would presume a safety element, but the technique of rewriting the process table is an ancient rootkit technique -- so clearly it is possible.
Furthermore, setproctitle has support for multiple operating systems, so the method in which you change the process information may vary, but for the sake of explanation I'll presume you're using this under Linux and lets see what we have.
Linux uses prctl(), which looks like you use prctl(PR_SET_NAME, "my_new_name");, and this only works on the calling process. So it doesn't look like there's an 'easy' way to do this using the setproctitle module -- you can only modify yourself.
Your best bet is to modify your C++ code so that it uses prctl.
If you're not using Linux, post what you are using as other operating systems provide other opportunities and methods that differ greatly from the limitations of prctl.
A:
If you pass an kwarg executable to subprocess.Popen, you can use the first argument in the argument list:
subprocess.Popen(['some string you choose', str(p)],
executable=process_path+process_name, shell=False)
The docs say: "On Unix, it becomes the display name for the executing program in utilities such as ps."
A:
Windows-only: the process name usually means the actual executable image which is running (e.g. calc.exe). The process title on the other hand (it's the text that shows up on your taskbar) can easily be changed for console (CUI) apps using the start command instead of running the app directly (give the title as the first argument; use start /? for details):
for p in range(1, num_processes, 1):
subprocess.Popen(['start', str(p), process_path + process_name, str(p)], shell = False)
# ^ this is the title
For GUI apps it's slightly more difficult, and much less likely to be necessary.
| Python: Changing process name with setproctitle | I have a python script which launches a number of C++ programs, each program is passed a command line parameter as shown below
process_path "~/test/"
process_name "test"
num_process = 10
for p in range(1, num_processes, 1):
subprocess.Popen([process_path + process_name, str(p)], shell = False)
Is it possible to us setproctitle to rename each of these process so that I could include the command line parameter as part of the process name, if so , how would you do it?
| [
"setproctitle can only change it's \"own\" process title as I would presume a safety element, but the technique of rewriting the process table is an ancient rootkit technique -- so clearly it is possible. \nFurthermore, setproctitle has support for multiple operating systems, so the method in which you change the p... | [
2,
1,
0
] | [] | [] | [
"process",
"python"
] | stackoverflow_0003548294_process_python.txt |
Q:
python global object cache
Little question concerning app architecture:
I have a python script, running as a daemon.
Inside i have many objects, all inheriting from one class (let's name it 'entity')
I have also one main object, let it be 'topsys'
Entities are identified by pair (id, type (= class, roughly)), and they are connected in many wicked ways. They are also created and deleted all the time, and they are need to access other entities.
So, i need a kind of storage, basically dictionary of dictionaries (one for each type), holding all entities.
And the question is, what is better: attach this dictionary to 'topsys' as a object property or to class entity, as a property of the class? I would opt for the second (so entities does not need to know of existence of 'topsys'), but i am not feeling good about using properties directly in classes. Or maybe there is another way?
A:
There's not enough detail here to be certain of what's best, but in general I'd store the actual object registry as a module-level (global) variable in the top class, and have a method in the base class to access it.
_entities = []
class entity(object):
@staticmethod
def get_entity_registry():
return _entities
Alternatively, hide _entites entirely and expose a few methods, eg. get_object_by_id, register_object, so you can change the storage of _entities itself more easily later on.
By the way, a tip in case you're not there already: you'll probably want to look into weakrefs when creating object registries like this.
A:
There is no problem with using properties on classes. Classes are just objects, too.
In your case, with this little information available, I would go for a class property, too, because not creating dependencies ist great and will be one worry less sometimes later.
| python global object cache | Little question concerning app architecture:
I have a python script, running as a daemon.
Inside i have many objects, all inheriting from one class (let's name it 'entity')
I have also one main object, let it be 'topsys'
Entities are identified by pair (id, type (= class, roughly)), and they are connected in many wicked ways. They are also created and deleted all the time, and they are need to access other entities.
So, i need a kind of storage, basically dictionary of dictionaries (one for each type), holding all entities.
And the question is, what is better: attach this dictionary to 'topsys' as a object property or to class entity, as a property of the class? I would opt for the second (so entities does not need to know of existence of 'topsys'), but i am not feeling good about using properties directly in classes. Or maybe there is another way?
| [
"There's not enough detail here to be certain of what's best, but in general I'd store the actual object registry as a module-level (global) variable in the top class, and have a method in the base class to access it.\n_entities = []\nclass entity(object):\n @staticmethod\n def get_entity_registry(): \n ... | [
6,
0
] | [] | [] | [
"class_design",
"design_patterns",
"global_variables",
"python"
] | stackoverflow_0003895359_class_design_design_patterns_global_variables_python.txt |
Q:
python RSA module how to use java decrypt
I use python rsa module(http://stuvel.eu/rsa) get private_key and public_key.
How can I use these private_key and public_key to encrypt or decrypt in java?
A:
Thank you all. I think I have got the method.
The python's Rsa module can generate (n,p,q,e,d).I can use follow method in Java
KeyFactory s=KeyFactory.getInstance("RSA");
Key pri_k=s.generatePrivate(new RSAPrivateKeySpec(new BigInteger(n=p*q),new BigInteger(e));
Key pub_k=s.generatePublic(new RSAPublicKeySpec(new BigInteger(n=p*q),new BigInteger(d));
The second method is I run a .py in command(not jython). such as:
Runtime.getRuntime().exec("python C:\test.py")
A:
I'm assuming you want to use the methods and classes in the Java standard library to actually encrypt and decrypt messages with the keys you created in Python. The best solution to this problem is Jython, which is an implementation of Python that runs on the Java Virtual Machine.
Jython is good for you in this case because it will give you access to all the stuff contained in the Java standard library. Here's a simple example of how you can use Jython to use packages in the Java standard library:
from java.lang.Math import *
# use some methods from java.lang.math
hypotenuse = sqrt(a**2 + b**2)
You can do the same thing for all the java.security methods and classes you'll want to use.
| python RSA module how to use java decrypt | I use python rsa module(http://stuvel.eu/rsa) get private_key and public_key.
How can I use these private_key and public_key to encrypt or decrypt in java?
| [
"Thank you all. I think I have got the method.\nThe python's Rsa module can generate (n,p,q,e,d).I can use follow method in Java\nKeyFactory s=KeyFactory.getInstance(\"RSA\");\nKey pri_k=s.generatePrivate(new RSAPrivateKeySpec(new BigInteger(n=p*q),new BigInteger(e));\nKey pub_k=s.generatePublic(new RSAPublicKeyS... | [
2,
0
] | [] | [] | [
"java",
"python",
"rsa"
] | stackoverflow_0003889416_java_python_rsa.txt |
Q:
How importing works. Why imported modules not inheriting other imported modules
I just "thought" I understood how importing and modules work but obviously I need more schooling.
Here is an example program (just a test case of somerthing I'm doing that is much bigger in scope and scale) and a module:
quick.py
import gtk
from quick_window import *
w.show_all()
gtk.main()
quick_window.py
w = gtk.Window()
w.connect('destroy', lambda w: gtk.main_quit())
l=gtk.Label('Hello')
w.add(l)
running I get
$ python quick.py
Traceback (most recent call last):
File "quick.py", line 2, in <module>
from quick_window import *
File "/home/woodnt/Dropbox/python/weather_project/plugins/quick_window.py", line 3, in <module>
w = gtk.Window()
NameError: name 'gtk' is not defined
To get it to work, I have to also import (er, reimport) gtk in the module like so:
import gtk
w = gtk.Window()
w.connect('destroy', lambda w: gtk.main_quit())
l=gtk.Label('Hello')
w.add(l)
Why should I have to import gtk more than once? Does that mean that I have 2 "gtk's" in memory?
Do I have to import everything within each module that I need within that module?
I know each module has it's own namespace, but I thought it also inherited the "globals" including imported module from the calling program.
I had been under the impression the from module import * is like cutting and pasting the code right into that location. Is there another way to do that?
Help is greatly appreciated.
Narnie
A:
The details of importing get very complicated, but conceptually it is very simple.
When you write:
import some_module
It is equivalent to this:
some_module = import_module("some_module")
where import_module is kind of like:
def import_module(modname):
if modname in sys.modules:
module = sys.modules[modname]
else:
filename = find_file_for_module(modname)
python_code = open(filename).read()
module = create_module_from_code(python_code)
sys.modules[modname] = module
return module
Two things to note here: the assignment of some_module is specific: an import statement really does nothing in the current module except assign a module object to the name you specify. That's why you don't automatically get the names from the imported module, and why it isn't like copying the imported code into the current module.
Also, in the import_module pseudo-function, if the name has already been imported somewhere, it will be in the global list of all modules (sys.modules), and so will simply be reused. The file won't be opened again, it won't be executed again, the globals in that modules won't get new values again, and so on. Importing the same module into many places is not wasteful or extra work, it is very fast.
A:
import is required to bring the contents of the py file into the namespace of that module - if you don't import, the names in it cannot be referenced.
Some more info: http://effbot.org/zone/import-confusion.htm
When Python imports a module, it first
checks the module registry
(sys.modules) to see if the module is
already imported. If that’s the case,
Python uses the existing module object
as is.
| How importing works. Why imported modules not inheriting other imported modules | I just "thought" I understood how importing and modules work but obviously I need more schooling.
Here is an example program (just a test case of somerthing I'm doing that is much bigger in scope and scale) and a module:
quick.py
import gtk
from quick_window import *
w.show_all()
gtk.main()
quick_window.py
w = gtk.Window()
w.connect('destroy', lambda w: gtk.main_quit())
l=gtk.Label('Hello')
w.add(l)
running I get
$ python quick.py
Traceback (most recent call last):
File "quick.py", line 2, in <module>
from quick_window import *
File "/home/woodnt/Dropbox/python/weather_project/plugins/quick_window.py", line 3, in <module>
w = gtk.Window()
NameError: name 'gtk' is not defined
To get it to work, I have to also import (er, reimport) gtk in the module like so:
import gtk
w = gtk.Window()
w.connect('destroy', lambda w: gtk.main_quit())
l=gtk.Label('Hello')
w.add(l)
Why should I have to import gtk more than once? Does that mean that I have 2 "gtk's" in memory?
Do I have to import everything within each module that I need within that module?
I know each module has it's own namespace, but I thought it also inherited the "globals" including imported module from the calling program.
I had been under the impression the from module import * is like cutting and pasting the code right into that location. Is there another way to do that?
Help is greatly appreciated.
Narnie
| [
"The details of importing get very complicated, but conceptually it is very simple.\nWhen you write:\nimport some_module\n\nIt is equivalent to this:\nsome_module = import_module(\"some_module\")\n\nwhere import_module is kind of like:\ndef import_module(modname):\n if modname in sys.modules:\n module = s... | [
13,
6
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003895346_import_module_python.txt |
Q:
transforming an image into an array of lines to draw
How do I generate a list of lines to draw if I have pixel data for an image, so I don't have to draw every pixel? Any language will do, although I listed what I have a working knowledge for. C is ok as well. There was a limit to how many tags I could choose. Also, you can just point me toward an algorithm.
A:
In general, bitmaps are stored in sequential memory, ideal for 'blitting' to the display; your GUI framework of choice will have a function for drawing bitmaps, and this function will be very carefully optimised.
On the other hand, decomposing an image into lines - vectorizing the image - is the domain of specialist programs and ongoing research. In all cases, its going to be slower to computer and slower to draw than just blitting the bitmap.
A:
You are looking for a "raster to vector" algorithm. The term comes from early graphics display systems, that used a CRT (cathode ray tube) for the display itself. There were 2 approaches to displaying graphics: "raster" was the scan of a series of lines left to right, top to bottom, each line made up of on/off pixels. The controller of the CRT's electron gun simply scanned the same pattern over and over, just varying the intensity of the electron beam. On a "vector" display, the electron gun could draw a straight line between any two points - no aliasing, no pixelation, just a pure straight line. Vector displays were capable of higher resolution, but were limited by the number of lines they could draw - if a drawing had too many lines, then the display would begin to flicker as the time it would take to redraw the picture (to refresh the phosphors of the CRT) would take longer than the persistence of the CRT's phosphor surface. Raster displays were simpler to control, had much less flicker, but lower resolution.
A:
If you want to extract lines from an image, try the Hough transform.
,
Check out also Reversible Straight Line Edge Reconstruction, which appeared in Graphics Gems V. The code is online at http://tog.acm.org/resources/GraphicsGems/gemsv/ch6-5/
A:
How can you achieve with lines what you have to do with pixels? You need to draw each pixel individually I'd say.
A:
Opencv has functions named like "cvHoughLines2" to detect lines.
| transforming an image into an array of lines to draw | How do I generate a list of lines to draw if I have pixel data for an image, so I don't have to draw every pixel? Any language will do, although I listed what I have a working knowledge for. C is ok as well. There was a limit to how many tags I could choose. Also, you can just point me toward an algorithm.
| [
"In general, bitmaps are stored in sequential memory, ideal for 'blitting' to the display; your GUI framework of choice will have a function for drawing bitmaps, and this function will be very carefully optimised.\nOn the other hand, decomposing an image into lines - vectorizing the image - is the domain of special... | [
1,
1,
1,
0,
0
] | [] | [] | [
"c#",
"c++",
"image",
"lua",
"python"
] | stackoverflow_0003878873_c#_c++_image_lua_python.txt |
Q:
Why the connect failed for ipv6 at python?
Why the connect failed for ipv6 ??
# python
>>> import socket
>>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
>>> sa = ('2000::1',2000,0,0)
>>> s.connect(sa)
>>> sa = ('fe80::21b:78ff:fe30:7c6', 2000, 0, 0)
>>> s.connect(sa)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1, in connect
socket.error: (22, 'Invalid argument')
A:
Link-local addresses (e.g. fe80::whatever) typically require a scope id to be specified in order to work. Try
sa = ('fe80::21b:78ff:fe30:7c6%en0', 2000, 0, 0)
instead. (If the computer you're trying to connect() to is accessible via a network interface other than en0, substitute in the name of the interface where en0 is now)
| Why the connect failed for ipv6 at python? | Why the connect failed for ipv6 ??
# python
>>> import socket
>>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
>>> sa = ('2000::1',2000,0,0)
>>> s.connect(sa)
>>> sa = ('fe80::21b:78ff:fe30:7c6', 2000, 0, 0)
>>> s.connect(sa)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1, in connect
socket.error: (22, 'Invalid argument')
| [
"Link-local addresses (e.g. fe80::whatever) typically require a scope id to be specified in order to work. Try\nsa = ('fe80::21b:78ff:fe30:7c6%en0', 2000, 0, 0) \n\ninstead. (If the computer you're trying to connect() to is accessible via a network interface other than en0, substitute in the name of the interfac... | [
6
] | [] | [] | [
"connect",
"ipv6",
"python",
"sockets"
] | stackoverflow_0003895570_connect_ipv6_python_sockets.txt |
Q:
This code for creating a QPolygon in Pyqt is stopping my application! Help?
HI all,
The following code:
self.painter = QtGui.QPainter(self)
self.painter.setRenderHint(QPainter.Antialiasing)
self.painter.translate(482,395)
self.painter.scale(300,300)
self.painter.save()
needle = Qt.QPolygon([QPoint(30, 0), QPoint(-30, 0), QPoint(0, 200)])
self.painter.setBrush(Qt.cyan)
self.painter.setPen(Qt.black)
self.painter.drawPolygon(needle)
self.painter.restore()
is causing my Pyqt application to crash. Does anyone have any idea why? It is part of my ui_form.py file which was automatically spat out by pyuic4. Removing / commenting it out fixes the problem. Yes, I wrote this myself instead of the compiler doing it.
Many thanks!
A:
Save the list which you pass the the constructor of QPolygon in a local variable. I guess that the elements get garbage collected as soon as the call returns so when you draw the polygon, they are no longer around.
points = [QPoint(30, 0), QPoint(-30, 0), QPoint(0, 200)]
needle = Qt.QPolygon(points)
A:
Because you are not creating your QPolygon correctly.
QPolygon ()
QPolygon ( int size )
QPolygon ( const QPolygon & polygon )
QPolygon ( const QVector & points )
QPolygon ( const QRect & rectangle, bool closed = false )
You can create a polygon with on integer, an already created QPolygon, a QVector, or a QRect which also passes true or false to close the polygon.
| This code for creating a QPolygon in Pyqt is stopping my application! Help? | HI all,
The following code:
self.painter = QtGui.QPainter(self)
self.painter.setRenderHint(QPainter.Antialiasing)
self.painter.translate(482,395)
self.painter.scale(300,300)
self.painter.save()
needle = Qt.QPolygon([QPoint(30, 0), QPoint(-30, 0), QPoint(0, 200)])
self.painter.setBrush(Qt.cyan)
self.painter.setPen(Qt.black)
self.painter.drawPolygon(needle)
self.painter.restore()
is causing my Pyqt application to crash. Does anyone have any idea why? It is part of my ui_form.py file which was automatically spat out by pyuic4. Removing / commenting it out fixes the problem. Yes, I wrote this myself instead of the compiler doing it.
Many thanks!
| [
"Save the list which you pass the the constructor of QPolygon in a local variable. I guess that the elements get garbage collected as soon as the call returns so when you draw the polygon, they are no longer around.\npoints = [QPoint(30, 0), QPoint(-30, 0), QPoint(0, 200)]\nneedle = Qt.QPolygon(points)\n\n",
"Bec... | [
2,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"windows"
] | stackoverflow_0003828489_pyqt_pyqt4_python_qt_windows.txt |
Q:
Accessing session variable in Django template with Google App Engine (Webapp) - Python
I have a Django template as my front-end. At the back-end, I used the sessions provided from Gaeutilities to store a variable (email).
Front-end:
{% if session.Email %}
<div id="entersite">WELCOME <em>{{session.Email}}</em></div>
{% else %}
<div id= "entersite"><a href="/login/" id= "entersite">Enter the Site</a></div>
{% endif %}
Back-end:
self.session = Session()
self.session['email'] = email
temp = os.path.join(os.path.dirname(__file__),'templates/index.htm')
outstr = template.render(temp, {})
self.response.out.write(outstr)
Problem: How do I access the stored session on the server side and use it on the Django template (front-end)?
Anybody can give an update on this qns?
A:
You need to set your session object in a django template context, no?
template.render(temp, {'session':self.session})
A:
By doing so, you are just rendering the template with the session value. What happens is that when I click on a link to another page, and from that page return back to the same template, the session value are not being displayed. This is because I did not render the session value to the template from the page. What I wanted to do is to create a session at the back-end and traverse several pages and when I go back to the template, the session value can still be retrieved. Any ideas?
| Accessing session variable in Django template with Google App Engine (Webapp) - Python | I have a Django template as my front-end. At the back-end, I used the sessions provided from Gaeutilities to store a variable (email).
Front-end:
{% if session.Email %}
<div id="entersite">WELCOME <em>{{session.Email}}</em></div>
{% else %}
<div id= "entersite"><a href="/login/" id= "entersite">Enter the Site</a></div>
{% endif %}
Back-end:
self.session = Session()
self.session['email'] = email
temp = os.path.join(os.path.dirname(__file__),'templates/index.htm')
outstr = template.render(temp, {})
self.response.out.write(outstr)
Problem: How do I access the stored session on the server side and use it on the Django template (front-end)?
Anybody can give an update on this qns?
| [
"You need to set your session object in a django template context, no?\ntemplate.render(temp, {'session':self.session})\n\n",
"By doing so, you are just rendering the template with the session value. What happens is that when I click on a link to another page, and from that page return back to the same template, ... | [
2,
1
] | [] | [] | [
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0003887664_django_templates_google_app_engine_python.txt |
Q:
How to make a light query for a many to many relationship in Google Apps Engine?
How to make a light query for a many to many relationship?
Users has many Lists
the ListUser is the model that links them
Currently I'm doing like this but there are a lot of get queries to get all this data.
lists = []
for list in user.lists:
lists.append(list.list)
Now I got this:
list_users = user.lists.fetch(1000)
# problem is here: "list.list" will retrive data from database, but I just want that list's key, how to do?
list_keys = [list.list for list in list_users]
lists = List.get_by_key_name(list_keys)
A:
You should use get_value_for_datastore.
list_keys = [ListUser.list.get_value_for_datastore(list_user)
for list_user in list_users]
lists = db.get(list_keys)
If you have not already, you might want to take a look at some of the 'mastering the datastore' articles. Specifically the one on modeling relationships. Perhaps you can accomplish what you need using a list of List keys instead, maybe it will save you a query.
| How to make a light query for a many to many relationship in Google Apps Engine? | How to make a light query for a many to many relationship?
Users has many Lists
the ListUser is the model that links them
Currently I'm doing like this but there are a lot of get queries to get all this data.
lists = []
for list in user.lists:
lists.append(list.list)
Now I got this:
list_users = user.lists.fetch(1000)
# problem is here: "list.list" will retrive data from database, but I just want that list's key, how to do?
list_keys = [list.list for list in list_users]
lists = List.get_by_key_name(list_keys)
| [
"You should use get_value_for_datastore.\nlist_keys = [ListUser.list.get_value_for_datastore(list_user)\n for list_user in list_users]\nlists = db.get(list_keys)\n\nIf you have not already, you might want to take a look at some of the 'mastering the datastore' articles. Specifically the one on modelin... | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003895304_google_app_engine_google_cloud_datastore_python.txt |
Q:
Call python script from AIR application?
How can we invoke a python script using AIR 1.5?
A:
You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives.
If it's really really (that's two reallys) important to run an executable from AIR lookup the CommandProxy demo.
A:
For example through AMF: http://pyamf.org/
A:
Air 2.0 has a native process API.
| Call python script from AIR application? | How can we invoke a python script using AIR 1.5?
| [
"You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives. \nIf it's really really (that's two reallys) important to run an executable from AIR lookup the CommandP... | [
1,
0,
0
] | [
"Hypothetically, Adobe Alchemy technology may allow you to port Python interpreter to Flash.\nThough I seriously doubt that's the approach you want to use. Depending on task there should be easier solutions.\n"
] | [
-1
] | [
"air",
"flex3",
"python"
] | stackoverflow_0000771738_air_flex3_python.txt |
Q:
Installed python3, getting command not found error in terminal
I installed python3, I can open idle and it says it is running python3.0.1, but when I enter python3 in the terminal (on OSX) I get an error saying 'command not found'. Entering python gets me the 2.x version that came on the computer. Any advice on how I can access python3 from the terminal?
Thanks
A:
First, don't use Python 3.0.1. It has many problems and was officially retired upon the release of Python 3.1 (currently 3.1.2). You can find the python.org Mac OS X installer for 3.1.2 here. Once it is installed, then you need to ensure that the bin directory from the 3.1.2 framework (/Library/Frameworks/Python.framework/Versions/3.1/bin) is on your shell search path. You can manually modify an appropriate shell startup file, like .bash_profile. Or just double-click the Update Shell Profile.command found in /Applications/Python 3.1. In either case, you will need to open a new terminal window or re-login. Another approach is to install Python 3.1 from MacPorts or another distributor. Also, alpha releases of Python 3.2 are now available from python.org and elsewhere.
| Installed python3, getting command not found error in terminal | I installed python3, I can open idle and it says it is running python3.0.1, but when I enter python3 in the terminal (on OSX) I get an error saying 'command not found'. Entering python gets me the 2.x version that came on the computer. Any advice on how I can access python3 from the terminal?
Thanks
| [
"First, don't use Python 3.0.1. It has many problems and was officially retired upon the release of Python 3.1 (currently 3.1.2). You can find the python.org Mac OS X installer for 3.1.2 here. Once it is installed, then you need to ensure that the bin directory from the 3.1.2 framework (/Library/Frameworks/Pytho... | [
16
] | [] | [] | [
"macos",
"path",
"python"
] | stackoverflow_0003895756_macos_path_python.txt |
Q:
Selecting area of the screen with Python
I'm developing a screen shot utility in Python. At the moment it is specifically for Linux. So far I have the ability to take a screen shot of the full desktop, and have it upload to Imgur, then copy the link to clipboard. Now I want to expand into functions such as screen shots of the active window, or of a specific selection. If anyone could help, I'd love to know what kind of module would work best for this, and how to implement such a module.
A:
The functionality will depend on what you are using for image grabbing.
With PIL
http://effbot.org/imagingbook/imagegrab.htm
With GTK
To take a screenshot of active window :
http://faq.pygtk.org/index.py?req=show&file=faq23.039.htp
Also look at the pixbuf api
http://library.gnome.org/devel/gdk-pixbuf/
http://developer.gimp.org/api/2.0/gdk-pixbuf/gdk-pixbuf-gdk-pixbuf.html
Off topic
There are some screen cast tools: http://pypi.python.org/pypi/castro/1.0.4
| Selecting area of the screen with Python | I'm developing a screen shot utility in Python. At the moment it is specifically for Linux. So far I have the ability to take a screen shot of the full desktop, and have it upload to Imgur, then copy the link to clipboard. Now I want to expand into functions such as screen shots of the active window, or of a specific selection. If anyone could help, I'd love to know what kind of module would work best for this, and how to implement such a module.
| [
"The functionality will depend on what you are using for image grabbing.\n\nWith PIL\n\n\nhttp://effbot.org/imagingbook/imagegrab.htm\n\n\nWith GTK\n\nTo take a screenshot of active window : \n\nhttp://faq.pygtk.org/index.py?req=show&file=faq23.039.htp\n\nAlso look at the pixbuf api\n\nhttp://library.gnome.org/deve... | [
2
] | [] | [] | [
"python",
"screenshot"
] | stackoverflow_0003895732_python_screenshot.txt |
Q:
Python's print function that flushes the buffer when it's called?
Possible Duplicates:
How to flush output of Python print?
unbuffered stdout in python (as in python -u) from within the program
I have the following code to flushing out the output buffer.
print 'return 1'
sys.stdout.flush()
Can I setup the print function so that it automatically flushes the buffer when it's called?
A:
You can start python in unbuffered mode using the -u flag, e.g.
python -u script.py
or
#!/usr/bin/env python -u
as "shebang" header for your script.
| Python's print function that flushes the buffer when it's called? |
Possible Duplicates:
How to flush output of Python print?
unbuffered stdout in python (as in python -u) from within the program
I have the following code to flushing out the output buffer.
print 'return 1'
sys.stdout.flush()
Can I setup the print function so that it automatically flushes the buffer when it's called?
| [
"You can start python in unbuffered mode using the -u flag, e.g.\npython -u script.py\n\nor\n#!/usr/bin/env python -u\n\nas \"shebang\" header for your script.\n"
] | [
15
] | [] | [] | [
"flush",
"python"
] | stackoverflow_0003895481_flush_python.txt |
Q:
SHA256 hash in Python 2.4
Is there a way I can calculate a SHA256 hash in Python 2.4? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in this question, but using Python 2.4.
A:
Yes you can. With Python 2.4, there was SHA-1 module which does exactly this. See the documentation.
However, bear in mind that code importing from this module will cause DeprecationWarnings when run with newer Python.
Ok, as the requirement was tightened to be SHA-256, using the SHA-1 module in standard library isn't enough. I'd suggest checking out pycrypto, it has a SHA-256 implementation. There are also windows binary releases to match older Pythons, follow the links from Andrew Kuchlings old PyCrypto page.
A:
You can use the sha module, if you want to stay compatible, you can import it like this:
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
A:
There is a backported version of hashlib at http://pypi.python.org/pypi/hashlib and I just backported the newer hmac version and put it up at http://pypi.python.org/pypi/hmac
| SHA256 hash in Python 2.4 | Is there a way I can calculate a SHA256 hash in Python 2.4? (I emphasize: Python 2.4) I know how to do it in Python 2.5 but unfortunately it's not available on my server and an upgrade will not be made. I have the same problem as the guy in this question, but using Python 2.4.
| [
"Yes you can. With Python 2.4, there was SHA-1 module which does exactly this. See the documentation.\nHowever, bear in mind that code importing from this module will cause DeprecationWarnings when run with newer Python.\nOk, as the requirement was tightened to be SHA-256, using the SHA-1 module in standard library... | [
10,
8,
4
] | [] | [] | [
"python",
"python_2.4",
"sha256"
] | stackoverflow_0001328155_python_python_2.4_sha256.txt |
Q:
use sqlalchemy entity isolately
i just want to use an entity modify it to show something,but don't want to change to the db,
but after i use it ,and in some other place do the session.commit()
it will add this entity to db,i don't want this happen,
any one could help me?
A:
You can expunge it from session before modifying object, then this changes won't be accounted on next commits unless you add the object back to session. Just call session.expunge(obj).
| use sqlalchemy entity isolately | i just want to use an entity modify it to show something,but don't want to change to the db,
but after i use it ,and in some other place do the session.commit()
it will add this entity to db,i don't want this happen,
any one could help me?
| [
"You can expunge it from session before modifying object, then this changes won't be accounted on next commits unless you add the object back to session. Just call session.expunge(obj).\n"
] | [
1
] | [] | [] | [
"entity",
"python",
"sqlalchemy"
] | stackoverflow_0003881364_entity_python_sqlalchemy.txt |
Q:
Using sqlchemy in Pyqt, is it possible?
Hi i am new to Pyqt and i am wondering if it is possible to have goodness of sqlalchemy e.g. connection pooling and managing, abstracting away all the menial low level details?
A:
Have a look at Camelot. http://www.python-camelot.com/
| Using sqlchemy in Pyqt, is it possible? | Hi i am new to Pyqt and i am wondering if it is possible to have goodness of sqlalchemy e.g. connection pooling and managing, abstracting away all the menial low level details?
| [
"Have a look at Camelot. http://www.python-camelot.com/\n"
] | [
1
] | [] | [] | [
"pyqt",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0003892071_pyqt_python_sql_sqlalchemy.txt |
Q:
Why is this python operation returning a tuple?
from datetime import date
from datetime import timedelta
a = date.today() - timedelta(1)
# a above is a tuple and not datetime
# Since I am a C programmer, I would expect python to cast back to datetime
# but it is casting it to a tuple
Can you please tell me why this is happening? and also how I can see that the operation above results in a datetime?
I am a python newbie, sorry if this is a trivial thing, but I am stuck here for a while!
Thanks
A:
Perhaps the repr of a confuses you:
>>> a
datetime.date(2010, 10, 8)
this is not a tuple, it's what datetime uses as repr(). Print it to get its string() representation:
>>> print a
2010-10-08
Either str() a yourself explicitly or use a.strftime() to do you own formatting.
A:
Having looked at your image:
I think you are assuming it's a string, because print outputs a string - but that's exactly what its job is! The object is a datetime. You cannot convert it to a date by passing it to the date() constructor, either - instead you should call a.date()
A:
use type built-in function:
>>> from datetime import date
>>> from datetime import timedelta
>>>
>>> a = date.today() - timedelta(1)
>>> a
datetime.date(2010, 10, 8)
>>> type(a)
<type 'datetime.date'>
>>>
A:
Your statement
date.today() - timedelta(1)
returns a date object.
This object have two string representations:
The most common readable format is by calling str() function (the same called using print), in this case str(a) gives you '2010-10-08'
A second representation, the object nature, is by using repr() function. In this case repr(a) returns 'datetime.date(2010, 10, 8)'.
| Why is this python operation returning a tuple? | from datetime import date
from datetime import timedelta
a = date.today() - timedelta(1)
# a above is a tuple and not datetime
# Since I am a C programmer, I would expect python to cast back to datetime
# but it is casting it to a tuple
Can you please tell me why this is happening? and also how I can see that the operation above results in a datetime?
I am a python newbie, sorry if this is a trivial thing, but I am stuck here for a while!
Thanks
| [
"Perhaps the repr of a confuses you:\n>>> a\ndatetime.date(2010, 10, 8)\n\nthis is not a tuple, it's what datetime uses as repr(). Print it to get its string() representation:\n>>> print a\n2010-10-08\n\nEither str() a yourself explicitly or use a.strftime() to do you own formatting.\n",
"Having looked at your im... | [
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003896408_python.txt |
Q:
Is there a way to move many files quickly in Python?
I have a little script that moves files around in my photo collection, but it runs a bit slow.
I think it's because I'm doing one file move at a time. I'm guessing I can speed this up if I do all file moves from one dir to another at the same time. Is there a way to do that?
If that's not the reason for my slowness, how else can I speed this up?
Update:
I don't think my problem is being understood. Perhaps, listing my source code will help explain:
# ORF is the file extension of the files I want to move;
# These files live in dirs shared by JPEG files,
# which I do not want to move.
import os
import re
from glob import glob
import shutil
DIGITAL_NEGATIVES_DIR = ...
DATE_PATTERN = re.compile('\d{4}-\d\d-\d\d')
# Move a single ORF.
def move_orf(src):
dir, fn = os.path.split(src)
shutil.move(src, os.path.join('raw', dir))
# Move all ORFs in a single directory.
def move_orfs_from_dir(src):
orfs = glob(os.path.join(src, '*.ORF'))
if not orfs:
return
os.mkdir(os.path.join('raw', src))
print 'Moving %3d ORF files from %s to raw dir.' % (len(orfs), src)
for orf in orfs:
move_orf(orf)
# Scan for dirs that contain ORFs that need to be moved, and move them.
def main():
os.chdir(DIGITAL_NEGATIVES_DIR)
src_dirs = filter(DATE_PATTERN.match, os.listdir(os.curdir))
for dir in src_dirs:
move_orfs_from_dir(dir)
if __name__ == '__main__':
main()
A:
What platform are you on? And does it really have to be Python? If not, you can simply use system tools like mv (*nix) , or move (windows).
$ stat -c "%s" file
382849574
$ time python -c 'import shutil;shutil.move("file","/tmp")'
real 0m29.698s
user 0m0.349s
sys 0m1.862s
$ time mv file /tmp
real 0m29.149s
user 0m0.011s
sys 0m1.607s
$ time python -c 'import shutil;shutil.move("file","/tmp")'
real 0m30.349s
user 0m0.349s
sys 0m2.015s
$ time mv file /tmp
real 0m28.292s
user 0m0.015s
sys 0m1.702s
$ cat test.py
#!/usr/bin/env python
import shutil
shutil.move("file","/tmp")
shutil.move("/tmp/file",".")
$ cat test.sh
#!/bin/bash
mv file /tmp
mv /tmp/file .
# time python test.py
real 1m1.175s
user 0m0.641s
sys 0m4.110s
$ time bash test.sh
real 1m1.040s
user 0m0.026s
sys 0m3.242s
$ time python test.py
real 1m3.348s
user 0m0.659s
sys 0m4.024s
$ time bash test.sh
real 1m1.740s
user 0m0.017s
sys 0m3.276s
A:
Edit:
In my own state of confusion (which JoshD helpfully remedied), I forgot that shutil.move accepts directories, so you can (and should) just use that to move your directory as a batch.
A:
If you just want to move the directory, you can use shutil.move. It'll be pretty freakin' quick (if it's on the same filesystem) because it's just a rename operation.
| Is there a way to move many files quickly in Python? | I have a little script that moves files around in my photo collection, but it runs a bit slow.
I think it's because I'm doing one file move at a time. I'm guessing I can speed this up if I do all file moves from one dir to another at the same time. Is there a way to do that?
If that's not the reason for my slowness, how else can I speed this up?
Update:
I don't think my problem is being understood. Perhaps, listing my source code will help explain:
# ORF is the file extension of the files I want to move;
# These files live in dirs shared by JPEG files,
# which I do not want to move.
import os
import re
from glob import glob
import shutil
DIGITAL_NEGATIVES_DIR = ...
DATE_PATTERN = re.compile('\d{4}-\d\d-\d\d')
# Move a single ORF.
def move_orf(src):
dir, fn = os.path.split(src)
shutil.move(src, os.path.join('raw', dir))
# Move all ORFs in a single directory.
def move_orfs_from_dir(src):
orfs = glob(os.path.join(src, '*.ORF'))
if not orfs:
return
os.mkdir(os.path.join('raw', src))
print 'Moving %3d ORF files from %s to raw dir.' % (len(orfs), src)
for orf in orfs:
move_orf(orf)
# Scan for dirs that contain ORFs that need to be moved, and move them.
def main():
os.chdir(DIGITAL_NEGATIVES_DIR)
src_dirs = filter(DATE_PATTERN.match, os.listdir(os.curdir))
for dir in src_dirs:
move_orfs_from_dir(dir)
if __name__ == '__main__':
main()
| [
"What platform are you on? And does it really have to be Python? If not, you can simply use system tools like mv (*nix) , or move (windows). \n$ stat -c \"%s\" file\n382849574\n\n$ time python -c 'import shutil;shutil.move(\"file\",\"/tmp\")'\n\nreal 0m29.698s\nuser 0m0.349s \nsys 0m1.862s \n\n$ time mv f... | [
4,
3,
2
] | [] | [] | [
"file",
"move",
"performance",
"python",
"shutil"
] | stackoverflow_0003896451_file_move_performance_python_shutil.txt |
Q:
Extract content from a file with mime multipart
I have a file that contain a tiff image and a document xml in a multipart mime document.
I would extract the image from this file.
How I can get it?
I have this code, but it requires an infinite time to extract it, if I have a big file (for example 30Mb), so this is unuseful.
f=open("content_file.txt","rb")
msg = email.message_from_file(f)
j=0
image=False
for i in msg.walk():
if i.is_multipart():
#print "MULTIPART: "
continue
if i.get_content_maintype() == 'text':
j=j+1
continue
if i.get_content_maintype() == 'image':
image=True
j=j+1
pl = i.get_payload(decode=True)
localFile = open("map.out.tiff", 'wb')
localFile.write(pl)
continue
f.close()
if (image==False):
sys.exit(0);
Thank you so much.
A:
Solved:
def extract_mime_part_matching(stream, mimetype):
"""Return the first element in a multipart MIME message on stream
matching mimetype."""
msg = mimetools.Message(stream)
msgtype = msg.gettype()
params = msg.getplist()
data = StringIO.StringIO()
if msgtype[:10] == "multipart/":
file = multifile.MultiFile(stream)
file.push(msg.getparam("boundary"))
while file.next():
submsg = mimetools.Message(file)
try:
data = StringIO.StringIO()
mimetools.decode(file, data, submsg.getencoding())
except ValueError:
continue
if submsg.gettype() == mimetype:
break
file.pop()
return data.getvalue()
From:
http://docs.python.org/release/2.6.6/library/multifile.html
Thank you for the support.
A:
It is not quite clear to me, why your code hangs. The indentation looks a bit wrong and opened files are not properly closed. You may also be low on memory.
This version works fine for me:
import email
import mimetypes
with open('email.txt') as fp:
message = email.message_from_file(fp)
for i, part in enumerate(message.walk()):
if part.get_content_maintype() == 'image':
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
filename = 'image-%02d%s' % (i, ext or '.tiff')
with open(filename, 'wb') as fp:
fp.write(part.get_payload(decode=True))
(Partly taken from http://docs.python.org/library/email-examples.html#email-examples)
| Extract content from a file with mime multipart | I have a file that contain a tiff image and a document xml in a multipart mime document.
I would extract the image from this file.
How I can get it?
I have this code, but it requires an infinite time to extract it, if I have a big file (for example 30Mb), so this is unuseful.
f=open("content_file.txt","rb")
msg = email.message_from_file(f)
j=0
image=False
for i in msg.walk():
if i.is_multipart():
#print "MULTIPART: "
continue
if i.get_content_maintype() == 'text':
j=j+1
continue
if i.get_content_maintype() == 'image':
image=True
j=j+1
pl = i.get_payload(decode=True)
localFile = open("map.out.tiff", 'wb')
localFile.write(pl)
continue
f.close()
if (image==False):
sys.exit(0);
Thank you so much.
| [
"Solved:\ndef extract_mime_part_matching(stream, mimetype):\n\"\"\"Return the first element in a multipart MIME message on stream\nmatching mimetype.\"\"\"\n\nmsg = mimetools.Message(stream)\nmsgtype = msg.gettype()\nparams = msg.getplist()\n\ndata = StringIO.StringIO()\nif msgtype[:10] == \"multipart/\":\n\n fi... | [
4,
0
] | [] | [] | [
"mime",
"mime_types",
"python"
] | stackoverflow_0003894923_mime_mime_types_python.txt |
Q:
How to bulk insert data to mysql with python
Currently i'm using Alchemy as a ORM, and I look for a way to speed up my insert operation, I have bundle of XML files to import
for name in names:
p=Product()
p.name="xxx"
session.commit()
i use above code to insert my data paser from batch xml file to mysql,it's very slow
also i tried to
for name in names:
p=Product()
p.name="xxx"
session.commit()
but it seems didn't change anything
A:
You could bypass the ORM for the insertion operation and use the SQL Expression generator instead.
Something like:
conn.execute(Product.insert(), [dict(name=name) for name in names])
That should create a single statement to do your inserting.
That example was taken from lower down the same page.
(I'd be interested to know what speedup you got from that)
| How to bulk insert data to mysql with python | Currently i'm using Alchemy as a ORM, and I look for a way to speed up my insert operation, I have bundle of XML files to import
for name in names:
p=Product()
p.name="xxx"
session.commit()
i use above code to insert my data paser from batch xml file to mysql,it's very slow
also i tried to
for name in names:
p=Product()
p.name="xxx"
session.commit()
but it seems didn't change anything
| [
"You could bypass the ORM for the insertion operation and use the SQL Expression generator instead.\nSomething like:\nconn.execute(Product.insert(), [dict(name=name) for name in names])\n\nThat should create a single statement to do your inserting.\nThat example was taken from lower down the same page.\n(I'd be int... | [
1
] | [] | [] | [
"bulkinsert",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0003874320_bulkinsert_mysql_python_sqlalchemy.txt |
Q:
Python nested loop with condition
my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7
My goal is to be able to see if my_var is larger than all of the positions at my_list[0][1] and my_list[1][1] and my_list[2][1] and so on.
my_list can vary in length and my_var can also vary so I am thinking a loop is the best bet?
*very new to python
A:
all(variable > element for element in list)
or for element i of lists within a list
all(variable > sublist[i] for sublist in list)
This has the advantage of kicking out early if any of the elements is too large. This works because the ... for ... in list is an instance of Python's powerful and multifarious generator expressions. They are similar to list comprehensions but only generate values as needed.
all itself just checks to see if all of the values in the iterable it's passed are true. Generator expressions, list comprehensions, lists, tuples, and other sorts of sequences are all iterables.
So the first statement ends up being equivalent to calling a function like
def all_are_greater_than_value(list, value):
for element in list:
if element <= value:
return False
return True
with all_are_greater_than_value(list, variable)...
or simply
all_greater = True
for element in list:
if element <= value:
all_greater = False
break
However, the generator expression is generally preferred, being more concise and "idiomatic".
A:
You can do it like this also:
my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7
print all(all(x < my_var for x in sublist) for sublist in my_list)
| Python nested loop with condition | my_list = [[1,2],[1,3],[1,3],[1,3]]
my_var = 7
My goal is to be able to see if my_var is larger than all of the positions at my_list[0][1] and my_list[1][1] and my_list[2][1] and so on.
my_list can vary in length and my_var can also vary so I am thinking a loop is the best bet?
*very new to python
| [
"all(variable > element for element in list)\n\nor for element i of lists within a list\nall(variable > sublist[i] for sublist in list)\n\nThis has the advantage of kicking out early if any of the elements is too large. This works because the ... for ... in list is an instance of Python's powerful and multifarious... | [
4,
1
] | [] | [] | [
"conditional_statements",
"list",
"loops",
"python"
] | stackoverflow_0003895713_conditional_statements_list_loops_python.txt |
Q:
How do I extract certain digits from raw input in Python?
Let's say I ask a users for some random letters and numbers. let's say they gave me 1254jf4h. How would I take the letters jfh and convert them inter a separate variable and then take the numbers 12544 and make them in a separate variable?
A:
>>> s="1254jf4h"
>>> num=[]
>>> alpah=[]
>>> for n,i in enumerate(s):
... if i.isdigit():
... num.append(i)
... else:
... alpah.append(i)
...
>>> alpah
['j', 'f', 'h']
>>> num
['1', '2', '5', '4', '4']
A:
A for loop is simple enough. Personally, I would use filter().
s = "1254jf4h"
nums = filter(lambda x: x.isdigit(), s)
chars = filter(lambda x: x.isalpha(), s)
print nums # 12544
print chars # jfh
A:
edit: oh well, you already got your answer. Ignore.
NUMBERS = "0123456789"
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def numalpha(string):
return string.translate(None, NUMBERS), string.translate(None, LETTERS)
print numalpha("14asdf129h53")
The function numalpha returns a 2-tuple with two strings, the first containing all the alphabetic characters in the original string, the second containing the numbers.
Note this is highly inefficient, as it traverses the string twice and it doesn't take into account the fact that numbers and letters have consecutive ASCII codes, though it does have the advantage of being easily modifiable to work with other codifications.
Note also that I only extracted lower-case letters. Yeah, It's not the best code snippet I've ever written xD. Hope it helps anyway.
| How do I extract certain digits from raw input in Python? | Let's say I ask a users for some random letters and numbers. let's say they gave me 1254jf4h. How would I take the letters jfh and convert them inter a separate variable and then take the numbers 12544 and make them in a separate variable?
| [
">>> s=\"1254jf4h\"\n>>> num=[]\n>>> alpah=[]\n>>> for n,i in enumerate(s):\n... if i.isdigit():\n... num.append(i)\n... else:\n... alpah.append(i)\n...\n>>> alpah\n['j', 'f', 'h']\n>>> num\n['1', '2', '5', '4', '4']\n\n",
"A for loop is simple enough. Personally, I would use filter().\ns = \"1254jf... | [
2,
2,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003896368_python_regex_string.txt |
Q:
Python - Fastest way to find the average value over entire dict each time it gets modified?
I'm trying to find the fastest/most efficient way to extract the average value from a dict. The task I'm working on requires that it do this thousands of times, so simply iterating over all the values in the dict each time to find the average would be entirely inefficient. Hundreds and hundreds of new key,value pairs get added to the dict and we need to find the average value each time this occurs. We also need to find the new average value each time a value gets updated, which occurs thousands of times.
Thanks in advance--this is such an awesome place.
A:
Create your own dict subclass that tracks the count and total, and then can quickly return the average:
class AvgDict(dict):
def __init__(self):
self._total = 0.0
self._count = 0
def __setitem__(self, k, v):
if k in self:
self._total -= self[k]
self._count -= 1
dict.__setitem__(self, k, v)
self._total += v
self._count += 1
def __delitem__(self, k):
v = self[k]
dict.__delitem__(self, k)
self._total -= v
self._count -= 1
def average(self):
if self._count:
return self._total/self._count
a = AvgDict()
assert a.average() is None
a[1] = 1
assert a.average() == 1
a[2] = 10
assert a.average() == 5.5
assert a[2] == 10
a[1] = 5
assert a.average() == 7.5
del a[1]
assert a.average() == 10
A:
The following is based on running average, so if you know the previous average:
At = (A0 * N + E) / (N + 1)
At is the average after addition of the new element
A0 is the average before addition of the new element
N is the number of element before addition of the new element
E is the new element's value
Its simpler brother works if you keep tab of the sum of the elements:
At = (T + E) / (N + 1)
T is the total of all elements
A0 is the average before addition of the new element
N is the number of element before addition of the new element
E is the new element's value
When a value is deleted, you can do a similar thing:
At = (A0 * N - E) / (N - 1)
And when a value is updated:
At = (A0 * N - E0 + E1) / (N)
E0 is value before updating, E1 is value after updating.
A:
Inherit from dict and calculate the average value each time __setitem__ is called.
Since you can store the previous average in your dictionary class and only average this and the new value that is added, that should be pretty fast - the first time a new item is added, the average value is simply that of this value.
| Python - Fastest way to find the average value over entire dict each time it gets modified? | I'm trying to find the fastest/most efficient way to extract the average value from a dict. The task I'm working on requires that it do this thousands of times, so simply iterating over all the values in the dict each time to find the average would be entirely inefficient. Hundreds and hundreds of new key,value pairs get added to the dict and we need to find the average value each time this occurs. We also need to find the new average value each time a value gets updated, which occurs thousands of times.
Thanks in advance--this is such an awesome place.
| [
"Create your own dict subclass that tracks the count and total, and then can quickly return the average:\nclass AvgDict(dict):\n def __init__(self):\n self._total = 0.0\n self._count = 0\n\n def __setitem__(self, k, v):\n if k in self:\n self._total -= self[k]\n self... | [
11,
2,
1
] | [] | [] | [
"average",
"dictionary",
"iteration",
"python"
] | stackoverflow_0003897040_average_dictionary_iteration_python.txt |
Q:
GUI development package
I am new to GUI development. What is the best GUI development package for python on linux (ubuntu being more specific)?
A:
There are numerous decent GUI toolkits, the most popular being PyQt, PyGTK, wxPython and Tkinter. Personally, I prefer Qt, but that's really subjective.
A:
This is much more a matter of personal taste.
I use GTK+ with Glade.
| GUI development package | I am new to GUI development. What is the best GUI development package for python on linux (ubuntu being more specific)?
| [
"There are numerous decent GUI toolkits, the most popular being PyQt, PyGTK, wxPython and Tkinter. Personally, I prefer Qt, but that's really subjective.\n",
"This is much more a matter of personal taste.\nI use GTK+ with Glade.\n"
] | [
3,
1
] | [] | [] | [
"linux",
"python",
"user_interface"
] | stackoverflow_0003897101_linux_python_user_interface.txt |
Q:
Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc
Hey there, I love regular expressions, but I'm just not good at them at all.
I have a list of some 400 shortened words such as lol, omg, lmao...etc. Whenever someone types one of these shortened words, it is replaced with its English counterpart ([laughter], or something to that effect). Anyway, people are annoying and type these short-hand words with the last letter(s) repeated x number of times.
examples:
omg -> omgggg, lol -> lollll, haha -> hahahaha, lol -> lololol
I was wondering if anyone could hand me the regex (in Python, preferably) to deal with this?
Thanks all.
(It's a Twitter-related project for topic identification if anyone's curious. If someone tweets "Let's go shoot some hoops", how do you know the tweet is about basketball, etc)
A:
FIRST APPROACH -
Well, using regular expression(s) you could do like so -
import re
re.sub('g+', 'g', 'omgggg')
re.sub('l+', 'l', 'lollll')
etc.
Let me point out that using regular expressions is a very fragile & basic approach to dealing with this problem. You could so easily get strings from users which will break the above regular expressions. What I am trying to say is that this approach requires lot of maintenance in terms of observing the patterns of mistakes the users make & then creating case specific regular expressions for them.
SECOND APPROACH -
Instead have you considered using difflib module? It's a module with helpers for computing deltas between objects. Of particular importance here for you is SequenceMatcher. To paraphrase from official documentation-
SequenceMatcher is a flexible class
for comparing pairs of sequences of
any type, so long as the sequence
elements are hashable. SequenceMatcher
tries to compute a "human-friendly
diff" between two sequences. The
fundamental notion is the longest
contiguous & junk-free matching subsequence.
import difflib as dl
x = dl.SequenceMatcher(lambda x : x == ' ', "omg", "omgggg")
y = dl.SequenceMatcher(lambda x : x == ' ', "omgggg","omg")
avg = (x.ratio()+y.ratio())/2.0
if avg>= 0.6:
print 'Match!'
else:
print 'Sorry!'
According to documentation, any ratio() over 0.6 is a close match. You might need to explore tweak the ratio for your data needs. If you need more stricter matching I found any value over 0.8 serves well.
A:
How about
\b(?=lol)\S*(\S+)(?<=\blol)\1*\b
(replace lol with omg, haha etc.)
This will match lol, lololol, lollll, lollollol etc. but fail lolo, lollllo, lolly and so on.
The rules:
Match the word lol completely.
Then allow any repetition of one or more characters at the end of the word (i. e. l, ol or lol)
So \b(?=zomg)\S*(\S+)(?<=\bzomg)\1*\b will match zomg, zomggg, zomgmgmg, zomgomgomg etc.
In Python, with comments:
result = re.sub(
r"""(?ix)\b # assert position at a word boundary
(?=lol) # assert that "lol" can be matched here
\S* # match any number of characters except whitespace
(\S+) # match at least one character (to be repeated later)
(?<=\blol) # until we have reached exactly the position after the 1st "lol"
\1* # then repeat the preceding character(s) any number of times
\b # and ensure that we end up at another word boundary""",
"lol", subject)
This will also match the "unadorned" version (i. e. lol without any repetition). If you don't want this, use \1+ instead of \1*.
| Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc | Hey there, I love regular expressions, but I'm just not good at them at all.
I have a list of some 400 shortened words such as lol, omg, lmao...etc. Whenever someone types one of these shortened words, it is replaced with its English counterpart ([laughter], or something to that effect). Anyway, people are annoying and type these short-hand words with the last letter(s) repeated x number of times.
examples:
omg -> omgggg, lol -> lollll, haha -> hahahaha, lol -> lololol
I was wondering if anyone could hand me the regex (in Python, preferably) to deal with this?
Thanks all.
(It's a Twitter-related project for topic identification if anyone's curious. If someone tweets "Let's go shoot some hoops", how do you know the tweet is about basketball, etc)
| [
"FIRST APPROACH -\nWell, using regular expression(s) you could do like so - \nimport re\nre.sub('g+', 'g', 'omgggg')\nre.sub('l+', 'l', 'lollll')\n\netc.\nLet me point out that using regular expressions is a very fragile & basic approach to dealing with this problem. You could so easily get strings from users which... | [
7,
4
] | [] | [] | [
"python",
"regex",
"string_matching"
] | stackoverflow_0003895874_python_regex_string_matching.txt |
Q:
Python threads and global vars
Say I have the following function in a module called "firstModule.py":
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
Now I have a different module called "secondModule.py":
def calculate():
# addCount value here too should be used from the mainModule
a=random.randint(10,20) + addCount
I am running a module called "mainModule.py" which has the following (notice the global "addCount" var):
import firstModule
import secondModule
addCount=0
Class MyThread(Thread):
def __init__(self,name):
Thread.__init__(self)
self.name=name
def run(self):
global addCount
if self.name=="firstModule":
firstModule.calculate()
if self.name=="secondModule":
secondModule.calculate()
def main():
the1=MyThread("firstModule");
the2=MyThread("secondModule");
the1.start()
the2.start()
the1.join()
the2.join()
# This part doesn't work:
print firstModule.a
print secondModule.a
Basically I want the "addCount" value in both modules to be the one from "mainModule". After that, when the threads are finished, I want to print the value
of "a" in both of them. The example above doesn't work. I was wondering how can I fix it.
A:
Pass 'addCount' to the function 'calculate', return the value of 'a' in 'calculate', and assign it to a new attribute in MyThread instance.
def calculate(addCount):
a = random.randint(0, 5) + addCount
return a
A:
Modules in python are singletons, so you can put your global variables in module globalModule.py and have both firstModule, secondModule, and mainModule import globalModule and they will all access the same addCount.
However, in general it's a bad practice for threads to have a global state.
This will never work:
print firstModule.a
print secondModule.a
because in here:
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
a is a local variable to the function calculate.
If you really want to write a as a module-level variable, add global declaration:
def calculate():
# addCount value here should be used from the mainModule
global a
a=random.randint(0,5) + addCount
| Python threads and global vars | Say I have the following function in a module called "firstModule.py":
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
Now I have a different module called "secondModule.py":
def calculate():
# addCount value here too should be used from the mainModule
a=random.randint(10,20) + addCount
I am running a module called "mainModule.py" which has the following (notice the global "addCount" var):
import firstModule
import secondModule
addCount=0
Class MyThread(Thread):
def __init__(self,name):
Thread.__init__(self)
self.name=name
def run(self):
global addCount
if self.name=="firstModule":
firstModule.calculate()
if self.name=="secondModule":
secondModule.calculate()
def main():
the1=MyThread("firstModule");
the2=MyThread("secondModule");
the1.start()
the2.start()
the1.join()
the2.join()
# This part doesn't work:
print firstModule.a
print secondModule.a
Basically I want the "addCount" value in both modules to be the one from "mainModule". After that, when the threads are finished, I want to print the value
of "a" in both of them. The example above doesn't work. I was wondering how can I fix it.
| [
"Pass 'addCount' to the function 'calculate', return the value of 'a' in 'calculate', and assign it to a new attribute in MyThread instance.\ndef calculate(addCount):\n a = random.randint(0, 5) + addCount\n return a\n\n",
"Modules in python are singletons, so you can put your global variables in module glob... | [
4,
2
] | [] | [] | [
"global_variables",
"multithreading",
"python"
] | stackoverflow_0003896210_global_variables_multithreading_python.txt |
Q:
How to get windows user id in web2py for an intranet application?
I'm using web2py for an intranet site and need to get current login windows user id in my controller. Whether any function is available?
A:
You need to install an NTLM authentication module on your web server such as mod_sspi or mod_ntlm then check the REMOTE_USER environment variable of the request. Here is something similar in Django:
http://brandonkonkle.com/blog/2008/sep/13/django-apache-and-mod_auth_sspi/
A:
If you mean you need code at the server to know the windows id of the current browser user, web2py isn't going to be able to tell you that. Windows authentication has nothing to do with web protocols.
| How to get windows user id in web2py for an intranet application? | I'm using web2py for an intranet site and need to get current login windows user id in my controller. Whether any function is available?
| [
"You need to install an NTLM authentication module on your web server such as mod_sspi or mod_ntlm then check the REMOTE_USER environment variable of the request. Here is something similar in Django:\nhttp://brandonkonkle.com/blog/2008/sep/13/django-apache-and-mod_auth_sspi/\n",
"If you mean you need code at the ... | [
4,
1
] | [
"I don't know if that works but try psutil module, which is supposed to work on both Windows and Unix.\nimport os, psutil\n\nownPid = os.getpid() #This one works in Windows, but os.getuid() does not...\nownUid = [p.uid for p in psutil.process_iter() \n if p.pid == ownPid][0]\n\n"
] | [
-1
] | [
"python",
"web2py",
"windows"
] | stackoverflow_0003798606_python_web2py_windows.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.