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:
A class subclass of itself. Why mutual subclassing is forbidden?
Complex question I assume, but studying OWL opened a new perspective to live, the universe and everything. I'm going philosophical here.
I am trying to achieve a class C which is subclass of B which in turn is subclass of C. Just for fun, you know...
So here it is
>>> class A(object): pass
...
>>> class B(A): pass
...
>>> class C(B): pass
...
>>> B.__bases__
(<class '__main__.A'>,)
>>> B.__bases__ = (C,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a __bases__ item causes an inheritance cycle
>>>
clearly, python is smart and forbids this. However, in OWL it is possible to define two classes to be mutual subclasses. The question is: what is the mind boggling explanation why this is allowed in OWL (which is not a programming language) and disallowed in programming languages ?
A:
Python doesn't allow it because there is no sensible way to do it. You could invent arbitrary rules about how to handle such a case (and perhaps some languages do), but since there is no actual gain in doing so, Python refuses to guess. Classes are required to have a stable, predictable method resolution order for a number of reasons, and so weird, unpredictable or surprising MROs are not allowed.
That said, there is a special case in Python: type and object. object is an instance of type, and type is a subclass of object. And of course, type is also an instance of type (since it's a subclass of object). This might be why OWL allows it: you need to start a class/metaclass hierarchy in some singularity, if you want everything to be an object and all objects to have a class.
A:
The MRO scheme implemented in Python (as of 2.3) forbids cyclic subclassing. Valid MRO's are guaranteed to satisfy "local precedence" and "monotonicity". Cyclic subclassing would break monotonicity.
This issue is discussed in the section entitled "Bad Method Resolution Orders"
A:
Part of this "disconnect" is because OWL describes an open world ontology. An Ontology has little or nothing to do with a program, other than a program can manipulate an ontology.
Trying to relate OWL concepts to programming languages is like trying to relate A Pianist and A Piano Sonata.
The sonata doesn't really have a concrete manifestion until someone is playing it -- ideally a Pianist, but not necessarily. Until it's being played, it's just potential relationships among notes manifested as sounds. When it's being played, some of actual relationships will be relevant to you, the listener. Some won't be relevant to the listener.
A:
I think the answer is "When you construct class C ... it must create instance of class B .. which must create instance of class C ... and so on" This will never end. This is forbidden in most languages (in fact i don't know other case).
You can only create an object with a 'reference' to other object that can be initially null.
A:
For a semantic reasoner, if A is a subclass of B, and B is a subclass of A, then the classes can be considered equivalent. They are not the "same", but from a reasoning perspective, if I can reason an individual is (or is not) a member of the class A, I can reason the individual is (or is not) a member of the class B. The classes A and B are semantically equivalent, which is what you were able to express with OWL.
A:
I'm sure someone can up with an example where this makes sense. However, I guess this restriction is easier and not less powerful.
Eg, Let's say class A holds fields a and b. Class C holds b and c. Then the view on things from C would be: A.a, C.b, C.c and the view from A would be: A.a, A.b, C.c.
Just moving b into a common base class is far easier to understand and implement, though.
|
A class subclass of itself. Why mutual subclassing is forbidden?
|
Complex question I assume, but studying OWL opened a new perspective to live, the universe and everything. I'm going philosophical here.
I am trying to achieve a class C which is subclass of B which in turn is subclass of C. Just for fun, you know...
So here it is
>>> class A(object): pass
...
>>> class B(A): pass
...
>>> class C(B): pass
...
>>> B.__bases__
(<class '__main__.A'>,)
>>> B.__bases__ = (C,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a __bases__ item causes an inheritance cycle
>>>
clearly, python is smart and forbids this. However, in OWL it is possible to define two classes to be mutual subclasses. The question is: what is the mind boggling explanation why this is allowed in OWL (which is not a programming language) and disallowed in programming languages ?
|
[
"Python doesn't allow it because there is no sensible way to do it. You could invent arbitrary rules about how to handle such a case (and perhaps some languages do), but since there is no actual gain in doing so, Python refuses to guess. Classes are required to have a stable, predictable method resolution order for a number of reasons, and so weird, unpredictable or surprising MROs are not allowed.\nThat said, there is a special case in Python: type and object. object is an instance of type, and type is a subclass of object. And of course, type is also an instance of type (since it's a subclass of object). This might be why OWL allows it: you need to start a class/metaclass hierarchy in some singularity, if you want everything to be an object and all objects to have a class.\n",
"The MRO scheme implemented in Python (as of 2.3) forbids cyclic subclassing. Valid MRO's are guaranteed to satisfy \"local precedence\" and \"monotonicity\". Cyclic subclassing would break monotonicity. \nThis issue is discussed in the section entitled \"Bad Method Resolution Orders\"\n",
"Part of this \"disconnect\" is because OWL describes an open world ontology. An Ontology has little or nothing to do with a program, other than a program can manipulate an ontology. \nTrying to relate OWL concepts to programming languages is like trying to relate A Pianist and A Piano Sonata. \nThe sonata doesn't really have a concrete manifestion until someone is playing it -- ideally a Pianist, but not necessarily. Until it's being played, it's just potential relationships among notes manifested as sounds. When it's being played, some of actual relationships will be relevant to you, the listener. Some won't be relevant to the listener.\n",
"I think the answer is \"When you construct class C ... it must create instance of class B .. which must create instance of class C ... and so on\" This will never end. This is forbidden in most languages (in fact i don't know other case).\nYou can only create an object with a 'reference' to other object that can be initially null.\n",
"For a semantic reasoner, if A is a subclass of B, and B is a subclass of A, then the classes can be considered equivalent. They are not the \"same\", but from a reasoning perspective, if I can reason an individual is (or is not) a member of the class A, I can reason the individual is (or is not) a member of the class B. The classes A and B are semantically equivalent, which is what you were able to express with OWL.\n",
"I'm sure someone can up with an example where this makes sense. However, I guess this restriction is easier and not less powerful.\nEg, Let's say class A holds fields a and b. Class C holds b and c. Then the view on things from C would be: A.a, C.b, C.c and the view from A would be: A.a, A.b, C.c. \nJust moving b into a common base class is far easier to understand and implement, though.\n"
] |
[
10,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"class",
"owl",
"python"
] |
stackoverflow_0002223300_class_owl_python.txt
|
Q:
How do I use gstreamer to make an audio clip from a segment of a longer source?
I would like to use gstreamer to save an arbitrary clip from one audio file to a new file. For example, a segment from 1 minute to 2 minutes in the original. How do I do it?
A:
You need gnonlin. See http://www.jonobacon.org/2006/12/27/using-gnonlin-with-gstreamer-and-python/
You won't need a gnlcomposition because you only want one segment. Use a gnlfilesource with its start and duration set to 0, 1 minute, and media-start and media-duration set to 1 minute, 1 minute. All times and durations are in nanoseconds.
Take 5 seconds from source.mp3 starting at 10 seconds, write to destination.ogg:
gst-launch-0.10 gnlfilesource location=$PWD/source.mp3 \
start=0 duration=5000000000 media-start=10000000000 media-duration=5000000000 ! \
audioconvert ! vorbisenc ! oggmux ! filesink location=destination.ogg
|
How do I use gstreamer to make an audio clip from a segment of a longer source?
|
I would like to use gstreamer to save an arbitrary clip from one audio file to a new file. For example, a segment from 1 minute to 2 minutes in the original. How do I do it?
|
[
"You need gnonlin. See http://www.jonobacon.org/2006/12/27/using-gnonlin-with-gstreamer-and-python/\nYou won't need a gnlcomposition because you only want one segment. Use a gnlfilesource with its start and duration set to 0, 1 minute, and media-start and media-duration set to 1 minute, 1 minute. All times and durations are in nanoseconds.\nTake 5 seconds from source.mp3 starting at 10 seconds, write to destination.ogg:\ngst-launch-0.10 gnlfilesource location=$PWD/source.mp3 \\\nstart=0 duration=5000000000 media-start=10000000000 media-duration=5000000000 ! \\\naudioconvert ! vorbisenc ! oggmux ! filesink location=destination.ogg\n\n"
] |
[
6
] |
[] |
[] |
[
"audio",
"audio_streaming",
"gstreamer",
"python",
"segment"
] |
stackoverflow_0002215683_audio_audio_streaming_gstreamer_python_segment.txt
|
Q:
Convert dict to array in NumPy
I'd like to take a dictionary of a dictionary containing floats, indexed by ints and convert it into a numpy.array for use with the numpy library. Currently I'm manually converting the values into two arrays, one for the original indexes and the other for the values. While I've looked at numpy.asarray my conclusion has been that I must be doing something wrong with it. Could anyone show an example of how to properly convert such a creation? Don't have to use numpy.asarray, anything will do.
from collections import defaultdict
foo = defaultdict( lambda: defaultdict(float) )
#Then "foo" is populated by several
#routines reading results from a DB
#
#As an example
foo[ 7104 ][ 3 ] = 4.5
foo[ 203 ][ 1 ] = 3.2
foo[ 2 ][ 1 ] = 2.7
I'd like to have just a multi-dimensional array of floats, not an array of dicts.
Edit:
Sorry for the delay. Here is the code that I was using to create the first array object containing just the values:
storedArray = numpy.asarray( reduce( lambda x,y: x + y, (item.values() for item in storedMapping.values() ) ) )
I was hoping someone might know a magic bullet that could convert a dict of dict into an array.
A:
You can calculate N and M like this
N=max(foo)+1
M=max(max(x) for x in foo.values())+1
fooarray = numpy.zeros((N, M))
for key1, row in foo.iteritems():
for key2, value in row.iteritems():
fooarray[key1, key2] = value
There are various options for sparse arrays. Eg,
import scipy.sparse
foosparse = scipy.sparse.lil_matrix((N, M))
for key1, row in foo.iteritems():
for key2, value in row.iteritems():
foosparse[(key1, key2)] = value
A:
Say you have a NxM array, then I'd do the following:
myarray = numpy.zeros((N, M))
for key1, row in mydict.iteritems():
for key2, value in row.iteritems():
myarray[key1, key2] = value
|
Convert dict to array in NumPy
|
I'd like to take a dictionary of a dictionary containing floats, indexed by ints and convert it into a numpy.array for use with the numpy library. Currently I'm manually converting the values into two arrays, one for the original indexes and the other for the values. While I've looked at numpy.asarray my conclusion has been that I must be doing something wrong with it. Could anyone show an example of how to properly convert such a creation? Don't have to use numpy.asarray, anything will do.
from collections import defaultdict
foo = defaultdict( lambda: defaultdict(float) )
#Then "foo" is populated by several
#routines reading results from a DB
#
#As an example
foo[ 7104 ][ 3 ] = 4.5
foo[ 203 ][ 1 ] = 3.2
foo[ 2 ][ 1 ] = 2.7
I'd like to have just a multi-dimensional array of floats, not an array of dicts.
Edit:
Sorry for the delay. Here is the code that I was using to create the first array object containing just the values:
storedArray = numpy.asarray( reduce( lambda x,y: x + y, (item.values() for item in storedMapping.values() ) ) )
I was hoping someone might know a magic bullet that could convert a dict of dict into an array.
|
[
"You can calculate N and M like this\nN=max(foo)+1\nM=max(max(x) for x in foo.values())+1\nfooarray = numpy.zeros((N, M))\nfor key1, row in foo.iteritems():\n for key2, value in row.iteritems():\n fooarray[key1, key2] = value \n\nThere are various options for sparse arrays. Eg,\nimport scipy.sparse\nfoosparse = scipy.sparse.lil_matrix((N, M))\nfor key1, row in foo.iteritems():\n for key2, value in row.iteritems():\n foosparse[(key1, key2)] = value \n\n",
"Say you have a NxM array, then I'd do the following:\nmyarray = numpy.zeros((N, M))\nfor key1, row in mydict.iteritems():\n for key2, value in row.iteritems():\n myarray[key1, key2] = value \n\n"
] |
[
4,
1
] |
[] |
[] |
[
"arrays",
"dictionary",
"numpy",
"python"
] |
stackoverflow_0002224620_arrays_dictionary_numpy_python.txt
|
Q:
python equivalent of GNU 'cat' that shows unique lines
Has anyone written the GNU cat command in python and would be willing to share? GNU cat actually does quite a bit & I don't really feel like re-inventing the wheel today. Yes, I did do a google search & and after reading too many sad stories of kittens vs snakes I decided to try SO.
Edit: I'd like to modify it so that it only shows unique lines.
A:
Latest:
Thank's Ned for the fileinput tip! Here's the latest:
#!/usr/bin/python
"""cat the file, but only the unique lines
"""
import fileinput
if __name__ == "__main__":
lines=set()
for line in fileinput.input():
if not line in lines:
print line,
lines.add(line)
Previously (2010-02-09):
Here's what I ended up with. It works for my immediate need. Thanks Mike Graham for your help.
#!/usr/bin/python
"""cat the file, but only the unique lines
"""
import optparse
import sys
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.set_usage('%prog [OPTIONS]')
parser.set_description('cat a file, only unique lines')
(options,args) = parser.parse_args()
lines = set()
for file in args:
if file == "-":
f = sys.stdin
else:
f = open(file)
for line in f:
if not line in lines:
print line,
lines.add(line)
A:
That depends which functionalities you want. If you just want to print out a file, you can do
with open('myfile') as f:
for line in f:
print line,
or to concatenate some files, you could do
filenames = ['file1', 'file2', 'file3']
for filename in filenames:
with open(filename) as f:
for line in f:
print line,
There is no general answer. Depending on the functionality you want to replicate, your code will be different. To exactly replicate something odd and special, use the subprocess module and call cat.
If you want to implement the same interface as cat, that seems an odd requirement. You can call cat and you can write the code more naturally. The only reason I can think to completely reimplement cat is for homework, and I would hope you wouldn't ask for the finished product if that is your reason.
|
python equivalent of GNU 'cat' that shows unique lines
|
Has anyone written the GNU cat command in python and would be willing to share? GNU cat actually does quite a bit & I don't really feel like re-inventing the wheel today. Yes, I did do a google search & and after reading too many sad stories of kittens vs snakes I decided to try SO.
Edit: I'd like to modify it so that it only shows unique lines.
|
[
"Latest:\nThank's Ned for the fileinput tip! Here's the latest:\n#!/usr/bin/python\n\n\"\"\"cat the file, but only the unique lines\n\"\"\"\nimport fileinput\n\nif __name__ == \"__main__\":\n lines=set()\n for line in fileinput.input():\n if not line in lines:\n print line,\n lines.add(line)\n\nPreviously (2010-02-09):\nHere's what I ended up with. It works for my immediate need. Thanks Mike Graham for your help.\n#!/usr/bin/python\n\"\"\"cat the file, but only the unique lines\n\"\"\"\nimport optparse\nimport sys\n\nif __name__ == \"__main__\":\n parser = optparse.OptionParser()\n parser.set_usage('%prog [OPTIONS]')\n parser.set_description('cat a file, only unique lines')\n\n (options,args) = parser.parse_args()\n\n lines = set()\n for file in args:\n if file == \"-\":\n f = sys.stdin\n else:\n f = open(file)\n for line in f:\n if not line in lines:\n print line,\n lines.add(line)\n\n",
"That depends which functionalities you want. If you just want to print out a file, you can do\nwith open('myfile') as f:\n for line in f:\n print line,\n\nor to concatenate some files, you could do\nfilenames = ['file1', 'file2', 'file3']\nfor filename in filenames:\n with open(filename) as f:\n for line in f:\n print line,\n\nThere is no general answer. Depending on the functionality you want to replicate, your code will be different. To exactly replicate something odd and special, use the subprocess module and call cat.\nIf you want to implement the same interface as cat, that seems an odd requirement. You can call cat and you can write the code more naturally. The only reason I can think to completely reimplement cat is for homework, and I would hope you wouldn't ask for the finished product if that is your reason.\n"
] |
[
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002224554_python.txt
|
Q:
Is_prime function via regex in python (from perl)
I've read this article where the /^1?$|^(11+?)\1+$/ Perl regex is used to test if a number is prime or not.
Process:
s = '1' * your_number
If s matchs the regex, then it's not prime. If it doesn't, it's prime.
How would you translate that regex to Python's re module?
A:
It works as is (except without the slashes at the edges, which aren't needed in Python):
pattern = r'^1?$|^(11+?)\1+$'
re.match(pattern, '1'*10) #matches
re.match(pattern, '1'*11) #doesn't match
The only nonstandard regex feature needed here is backreferences (\1), and these are supported in both Perl and Python.
|
Is_prime function via regex in python (from perl)
|
I've read this article where the /^1?$|^(11+?)\1+$/ Perl regex is used to test if a number is prime or not.
Process:
s = '1' * your_number
If s matchs the regex, then it's not prime. If it doesn't, it's prime.
How would you translate that regex to Python's re module?
|
[
"It works as is (except without the slashes at the edges, which aren't needed in Python):\npattern = r'^1?$|^(11+?)\\1+$'\nre.match(pattern, '1'*10) #matches\nre.match(pattern, '1'*11) #doesn't match\n\nThe only nonstandard regex feature needed here is backreferences (\\1), and these are supported in both Perl and Python.\n"
] |
[
6
] |
[] |
[] |
[
"perl",
"python",
"regex"
] |
stackoverflow_0002225027_perl_python_regex.txt
|
Q:
Design pattern for ongoing survey anayisis
I'm doing an ongoing survey, every quarter. We get people to sign up (where they give extensive demographic info).
Then we get them to answer six short questions with 5 possible values much worse, worse, same, better, much better.
Of course over time we will not get the same participants,, some will drop out and some new ones will sign up,, so I'm trying to decide how to best build a db and code (hope to use Python, Numpy?) to best allow for ongoing collection and analysis by the various categories defined by the initial demographic data..As of now we have 700 or so participants, so the dataset is not too big.
I.E.;
demographic, UID, North, south, residential. commercial Then answer for 6 questions for Q1
Same for Q2 and so on,, then need able to slice dice and average the values for the quarterly answers by the various demographics to see trends over time.
The averaging, grouping and so forth is modestly complicated by having differing participants each quarter
Any pointers to design patterns for this sort of DB? and analysis? Is this a sparse matrix?
A:
Regarding the survey analysis portion of your question, I would strongly recommend looking at the survey package in R (which includes a number of useful vignettes, including "A survey analysis example"). You can read about it in detail on the webpage "survey analysis in R". In particular, you may want to have a look at the page entitled database-backed survey objects which covers the subject of dealing with very large survey data.
You can integrate this analysis into Python with RPy2 as needed.
A:
This is a Data Warehouse. Small, but a data warehouse.
You have a Star Schema.
You have Facts:
response values are the measures
You have Dimensions:
time period. This has many attributes (year, quarter, month, day, week, etc.) This dimension allows you to accumulate unlimited responses to your survey.
question. This has some attributes. Typically your questions belong to categories or product lines or focus or anything else. You can have lots question "category" columns in this dimension.
participant. Each participant has unique attributes and reference to a Demographic category. Your demographic category can -- very simply -- enumerate your demographic combinations. This dimension allows you to follow respondents or their demographic categories through time.
But Ralph Kimball's The Data Warehouse Toolkit and follow those design patterns. http://www.amazon.com/Data-Warehouse-Toolkit-Complete-Dimensional/dp/0471200247
Buy the book. It's absolutely essential that you fully understand it all before you start down a wrong path.
Also, since you're doing Data Warehousing. Look at all the [Data Warehousing] questions on Stack Overflow. Read every Data Warehousing BLOG you can find.
There's only one relevant design pattern -- the Star Schema. If you understand that, you understand everything.
A:
On the analysis, if your six questions have been posed in a way that would lead you to believe the answers will be correlated, consider conducting a factor analysis on the raw scores first. Often comparing the factors across regions or customer type has more statistical power than comparing across questions alone. Also, the factor scores are more likely to be normally distributed (they are the weighted sum of 6 observations) while the six questions alone would not. This allows you to apply t-tests based on the normal distibution when comparing factor scores.
One watchout, though. If you assign numeric values to answers - 1 = much worse, 2 = worse, etc. you are implying that the distance between much worse and worse is the same as the distance between worse and same. This is generally not true - you might really have to screw up to get a vote of "much worse" while just being a passive screw up might get you a "worse" score. So the assignment of cardinal (numerics) to ordinal (ordering) has a bias of its own.
The unequal number of participants per quarter isn't a problem - there are statistical t-tests that deal with unequal sample sizes.
|
Design pattern for ongoing survey anayisis
|
I'm doing an ongoing survey, every quarter. We get people to sign up (where they give extensive demographic info).
Then we get them to answer six short questions with 5 possible values much worse, worse, same, better, much better.
Of course over time we will not get the same participants,, some will drop out and some new ones will sign up,, so I'm trying to decide how to best build a db and code (hope to use Python, Numpy?) to best allow for ongoing collection and analysis by the various categories defined by the initial demographic data..As of now we have 700 or so participants, so the dataset is not too big.
I.E.;
demographic, UID, North, south, residential. commercial Then answer for 6 questions for Q1
Same for Q2 and so on,, then need able to slice dice and average the values for the quarterly answers by the various demographics to see trends over time.
The averaging, grouping and so forth is modestly complicated by having differing participants each quarter
Any pointers to design patterns for this sort of DB? and analysis? Is this a sparse matrix?
|
[
"Regarding the survey analysis portion of your question, I would strongly recommend looking at the survey package in R (which includes a number of useful vignettes, including \"A survey analysis example\"). You can read about it in detail on the webpage \"survey analysis in R\". In particular, you may want to have a look at the page entitled database-backed survey objects which covers the subject of dealing with very large survey data.\nYou can integrate this analysis into Python with RPy2 as needed.\n",
"This is a Data Warehouse. Small, but a data warehouse.\nYou have a Star Schema.\nYou have Facts:\n\nresponse values are the measures\n\nYou have Dimensions:\n\ntime period. This has many attributes (year, quarter, month, day, week, etc.) This dimension allows you to accumulate unlimited responses to your survey.\nquestion. This has some attributes. Typically your questions belong to categories or product lines or focus or anything else. You can have lots question \"category\" columns in this dimension.\nparticipant. Each participant has unique attributes and reference to a Demographic category. Your demographic category can -- very simply -- enumerate your demographic combinations. This dimension allows you to follow respondents or their demographic categories through time.\n\nBut Ralph Kimball's The Data Warehouse Toolkit and follow those design patterns. http://www.amazon.com/Data-Warehouse-Toolkit-Complete-Dimensional/dp/0471200247\nBuy the book. It's absolutely essential that you fully understand it all before you start down a wrong path.\nAlso, since you're doing Data Warehousing. Look at all the [Data Warehousing] questions on Stack Overflow. Read every Data Warehousing BLOG you can find. \nThere's only one relevant design pattern -- the Star Schema. If you understand that, you understand everything.\n",
"On the analysis, if your six questions have been posed in a way that would lead you to believe the answers will be correlated, consider conducting a factor analysis on the raw scores first. Often comparing the factors across regions or customer type has more statistical power than comparing across questions alone. Also, the factor scores are more likely to be normally distributed (they are the weighted sum of 6 observations) while the six questions alone would not. This allows you to apply t-tests based on the normal distibution when comparing factor scores. \nOne watchout, though. If you assign numeric values to answers - 1 = much worse, 2 = worse, etc. you are implying that the distance between much worse and worse is the same as the distance between worse and same. This is generally not true - you might really have to screw up to get a vote of \"much worse\" while just being a passive screw up might get you a \"worse\" score. So the assignment of cardinal (numerics) to ordinal (ordering) has a bias of its own. \nThe unequal number of participants per quarter isn't a problem - there are statistical t-tests that deal with unequal sample sizes. \n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"design_patterns",
"matrix",
"python",
"statistics",
"survey"
] |
stackoverflow_0002223576_design_patterns_matrix_python_statistics_survey.txt
|
Q:
Is there a way for me to get detailed formatted information on a Python class?
So, I know I can use dir() to get information about class members etc. What I'm looking for is a way to get a nicely formatted report on everything related to a class (the members, docstrings, inheritance hierarchy, etc.).
I want to be able to run this on the command-line so I can explore code and debug better.
A:
Try calling help on your class.
A:
Try this from the command line:
pydoc modulename
A:
Try the help() facility that is built into the interpreter. E.g.
class X(object):
"""Docstring for an example class."""
def __init__(self):
"""Docstring for X.__init__()."""
pass
def method1(self, x):
"""Docstring for method1()."""
print x
>>> help(X)
Help on class X in module __main__:
class X(__builtin__.object)
| Docstring for an example class.
|
| Methods defined here:
|
| __init__(self)
| Docstring for X.__init__().
|
| method1(self, x)
| Docstring for method1().
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'X' objects>
| list of weak references to the object (if defined)
This works for just about anything, e.g.
>>> help(dir):
Help on built-in function dir in module __builtin__:
dir(...)
dir([object]) -> list of strings
Return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it:
No argument: the names in the current scope.
Module object: the module attributes.
Type or class object: its attributes, and recursively the attributes of
its bases.
Otherwise: its attributes, its class's attributes, and recursively the
attributes of its class's base classes.
A:
Not sure exactly what you need, but this chapter from Mark Pilgrim's "Dive into Python" might work.
A:
try ipython
A:
You want introspection. This is a good article about all that: http://www.ibm.com/developerworks/library/l-pyint.html
On the other hand, for debugging, you might just want to use Eclipse with the Python plugin.
|
Is there a way for me to get detailed formatted information on a Python class?
|
So, I know I can use dir() to get information about class members etc. What I'm looking for is a way to get a nicely formatted report on everything related to a class (the members, docstrings, inheritance hierarchy, etc.).
I want to be able to run this on the command-line so I can explore code and debug better.
|
[
"Try calling help on your class.\n",
"Try this from the command line:\npydoc modulename\n\n",
"Try the help() facility that is built into the interpreter. E.g.\nclass X(object):\n \"\"\"Docstring for an example class.\"\"\"\n def __init__(self):\n \"\"\"Docstring for X.__init__().\"\"\"\n pass\n def method1(self, x):\n \"\"\"Docstring for method1().\"\"\"\n print x\n\n>>> help(X)\nHelp on class X in module __main__:\n\nclass X(__builtin__.object)\n | Docstring for an example class.\n | \n | Methods defined here:\n | \n | __init__(self)\n | Docstring for X.__init__().\n | \n | method1(self, x)\n | Docstring for method1().\n | \n | ----------------------------------------------------------------------\n | Data and other attributes defined here:\n | \n | __dict__ = <dictproxy object>\n | dictionary for instance variables (if defined)\n | \n | __weakref__ = <attribute '__weakref__' of 'X' objects>\n | list of weak references to the object (if defined)\n\nThis works for just about anything, e.g.\n>>> help(dir):\nHelp on built-in function dir in module __builtin__:\n\ndir(...)\n dir([object]) -> list of strings\n\n Return an alphabetized list of names comprising (some of) the attributes\n of the given object, and of attributes reachable from it:\n\n No argument: the names in the current scope.\n Module object: the module attributes.\n Type or class object: its attributes, and recursively the attributes of\n its bases.\n Otherwise: its attributes, its class's attributes, and recursively the\n attributes of its class's base classes.\n\n",
"Not sure exactly what you need, but this chapter from Mark Pilgrim's \"Dive into Python\" might work.\n",
"try ipython\n",
"You want introspection. This is a good article about all that: http://www.ibm.com/developerworks/library/l-pyint.html\nOn the other hand, for debugging, you might just want to use Eclipse with the Python plugin.\n"
] |
[
5,
4,
1,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002225456_python.txt
|
Q:
Django Piston: How can I exclude nested fields from handler results? Is it even possible?
I am putting the finishing touches on an API I have written for a Django app utilizing django-piston. The API is able to search by request or IP address which are Request or IPAddress instances respectively. Each request can have 1 or more IPAddress associated with it.
So, for example I have an API call that will show all IPAddress objects matching an activity status of "active", "inactive", or "all" (for either). The Request to which each IPAddress instance is associated is available as IPAddress.request.
The problem I am having is that Request.inputter is a foreign key to the User instance of the person who provisioned the request. When my results are returned from the handler I have created for this API call, all fields from the User instance are displayed, including password.
This is bad; I do not want this.
So here is my handler:
class SearchByIPStatusHandler(BaseHandler):
model = IPAddress
allowed_methods = ('GET',)
anonymous = AnonymousIPHandler
def read(self, request, status):
"""
Returns IP addresses based on activity status.
Status: 'active', 'inactive', 'all'
"""
if status == 'all':
return self.model.objects.all()
else:
active = True if (status=='active') else False
return self.model.objects.filter(active=active)
And here is an example of the results from /api/show/all/:
<response>
<resource>
<updated>2010-02-05 17:08:53.651729</updated>
<expires>2010-02-12 17:08:23</expires>
<created>2010-02-05 17:08:53.625318</created>
<nexthop>255.255.255.255</nexthop>
<netmask>255.255.255.254</netmask>
<address>2.4.6.80/31</address>
<active>True</active>
<id>4</id>
<request>
<updated>2010-02-05 17:08:53.382381</updated>
<created>2010-02-05 17:08:53.382313</created>
<expires>2010-02-12 17:08:23</expires>
<incident>20100212-badthings-01</incident>
<reason>bad things happened</reason>
<inputter>
<username>jathan</username>
<first_name>Jathan</first_name>
<last_name>McCollum</last_name>
<is_active>True</is_active>
<email>email@fake.notreal</email>
<is_superuser>True</is_superuser>
<is_staff>True</is_staff>
<last_login>2010-02-05 18:55:51.877746</last_login>
<password>[ENCRYPTED STRING I REDACTED]</password>
<id>1</id>
<date_joined>2010-01-28 09:56:32</date_joined>
</inputter>
<requester>joeuser</requester>
<active>True</active>
</request>
</resource>
</response>
All I really want in the results is the inputter.username, not all of the other stuff. I have tried various iterations of implementing an exclude attribute on the handler to no avail. If I just skip the entire request field, that works fine, like so:
In handler:
exclude = ('request', )
Which results in:
<response>
<resource>
<updated>2010-02-05 17:08:53.651729</updated>
<expires>2010-02-12 17:08:23</expires>
<created>2010-02-05 17:08:53.625318</created>
<nexthop>255.255.255.255</nexthop>
<netmask>255.255.255.254</netmask>
<address>2.4.6.80/31</address>
<active>True</active>
<id>4</id>
</resource>
</response>
But these results are also not what I want.
So, finally, my question:
How can I exclude nested fields from handler results? Is it even possible?
I have tried various iterations of the following, all of which either have no result, or unintended results:
# try to exclude request.inputter
exclude = ( ('request', ('inputter', ), ) )
# try to exclude request.inputter.password
exclude = ( ('request', ('inputter', ('password', ) ) ) )
I assume that I am misunderstanding or misusing the way field exclusions are done in this context, so any enlightenment on this topic is greatly appreciated.
A:
Can you try using include instead of exclude? E.g.
include = (('request', ('inputter', ('username', 'therestofthefields'))))
I don't remember if I wrote exclude to be as versatile as include.
Also, the django-piston Google group is where we discuss most things, you may have more success asking this question there.
A:
You can get the desired result by specifying the desired fields via the handler's fields = clause.
Model fields coming from foreign keys can be specified like this:
('foreign_model_field', ('nested_field1', 'nested_field2'))
In your case, the following should work (some of your fields left out for brevity):
fields = ('updated', 'expires', 'created',
('request', ('incident', 'reason', ('inputter', ('username',)))))
|
Django Piston: How can I exclude nested fields from handler results? Is it even possible?
|
I am putting the finishing touches on an API I have written for a Django app utilizing django-piston. The API is able to search by request or IP address which are Request or IPAddress instances respectively. Each request can have 1 or more IPAddress associated with it.
So, for example I have an API call that will show all IPAddress objects matching an activity status of "active", "inactive", or "all" (for either). The Request to which each IPAddress instance is associated is available as IPAddress.request.
The problem I am having is that Request.inputter is a foreign key to the User instance of the person who provisioned the request. When my results are returned from the handler I have created for this API call, all fields from the User instance are displayed, including password.
This is bad; I do not want this.
So here is my handler:
class SearchByIPStatusHandler(BaseHandler):
model = IPAddress
allowed_methods = ('GET',)
anonymous = AnonymousIPHandler
def read(self, request, status):
"""
Returns IP addresses based on activity status.
Status: 'active', 'inactive', 'all'
"""
if status == 'all':
return self.model.objects.all()
else:
active = True if (status=='active') else False
return self.model.objects.filter(active=active)
And here is an example of the results from /api/show/all/:
<response>
<resource>
<updated>2010-02-05 17:08:53.651729</updated>
<expires>2010-02-12 17:08:23</expires>
<created>2010-02-05 17:08:53.625318</created>
<nexthop>255.255.255.255</nexthop>
<netmask>255.255.255.254</netmask>
<address>2.4.6.80/31</address>
<active>True</active>
<id>4</id>
<request>
<updated>2010-02-05 17:08:53.382381</updated>
<created>2010-02-05 17:08:53.382313</created>
<expires>2010-02-12 17:08:23</expires>
<incident>20100212-badthings-01</incident>
<reason>bad things happened</reason>
<inputter>
<username>jathan</username>
<first_name>Jathan</first_name>
<last_name>McCollum</last_name>
<is_active>True</is_active>
<email>email@fake.notreal</email>
<is_superuser>True</is_superuser>
<is_staff>True</is_staff>
<last_login>2010-02-05 18:55:51.877746</last_login>
<password>[ENCRYPTED STRING I REDACTED]</password>
<id>1</id>
<date_joined>2010-01-28 09:56:32</date_joined>
</inputter>
<requester>joeuser</requester>
<active>True</active>
</request>
</resource>
</response>
All I really want in the results is the inputter.username, not all of the other stuff. I have tried various iterations of implementing an exclude attribute on the handler to no avail. If I just skip the entire request field, that works fine, like so:
In handler:
exclude = ('request', )
Which results in:
<response>
<resource>
<updated>2010-02-05 17:08:53.651729</updated>
<expires>2010-02-12 17:08:23</expires>
<created>2010-02-05 17:08:53.625318</created>
<nexthop>255.255.255.255</nexthop>
<netmask>255.255.255.254</netmask>
<address>2.4.6.80/31</address>
<active>True</active>
<id>4</id>
</resource>
</response>
But these results are also not what I want.
So, finally, my question:
How can I exclude nested fields from handler results? Is it even possible?
I have tried various iterations of the following, all of which either have no result, or unintended results:
# try to exclude request.inputter
exclude = ( ('request', ('inputter', ), ) )
# try to exclude request.inputter.password
exclude = ( ('request', ('inputter', ('password', ) ) ) )
I assume that I am misunderstanding or misusing the way field exclusions are done in this context, so any enlightenment on this topic is greatly appreciated.
|
[
"Can you try using include instead of exclude? E.g.\ninclude = (('request', ('inputter', ('username', 'therestofthefields'))))\n\nI don't remember if I wrote exclude to be as versatile as include.\nAlso, the django-piston Google group is where we discuss most things, you may have more success asking this question there.\n",
"You can get the desired result by specifying the desired fields via the handler's fields = clause.\nModel fields coming from foreign keys can be specified like this:\n('foreign_model_field', ('nested_field1', 'nested_field2'))\n\nIn your case, the following should work (some of your fields left out for brevity):\nfields = ('updated', 'expires', 'created', \n ('request', ('incident', 'reason', ('inputter', ('username',)))))\n\n"
] |
[
3,
3
] |
[] |
[] |
[
"django",
"django_models",
"django_piston",
"python"
] |
stackoverflow_0002215352_django_django_models_django_piston_python.txt
|
Q:
Python subprocess get child's output
Possible Duplicates:
How to get output from subprocess.Popen()
Retrieving the output of subprocess.call()
Here is my question. I have an executable called device_console. The device_console provides a command line interface to a device. In device_console, four commands can be run: status, list, clear and exit. Each command produces an output. As an example:
[asdfgf@localhost ~]$ device_console
device_console> list
File A
File B
device_console> status
Status: OK
device_console> clear
All files cleared
device_console> list
device_console> exit
[asdfgf@localhost ~]$
As part of testing, I want to get the output of each command. I want to use Python for it. I am looking at Python's subprocess, but somehow I am unable to put them together. Can you please help?
A:
it sounds like you want something more like 'Expect'.
check out Pexpect
"Pexpect is a pure Python module that
makes Python a better tool for
controlling and automating other
programs. Pexpect is similar to the
Don Libes Expect system, but Pexpect
as a different interface that is
easier to understand. Pexpect is
basically a pattern matching system.
It runs programs and watches output.
When output matches a given pattern
Pexpect can respond as if a human were
typing responses."
A:
Use the subprocess module. Example:
import subprocess
# Open the subprocess
proc = subprocess.open('device_console', stdin=subprocess.PIPE, stdout.subprocess.PIPE)
# Write a command
proc.stdin.write('list\n')
# Read the results back -- this will block until a line of input is received
listing = proc.stdout.readline()
# When you're done, close the input stream so the subprocess knows to exit
proc.stdin.close()
# Wait for subprocess to exit (optional) and get its exit status
exit_status = proc.wait()
|
Python subprocess get child's output
|
Possible Duplicates:
How to get output from subprocess.Popen()
Retrieving the output of subprocess.call()
Here is my question. I have an executable called device_console. The device_console provides a command line interface to a device. In device_console, four commands can be run: status, list, clear and exit. Each command produces an output. As an example:
[asdfgf@localhost ~]$ device_console
device_console> list
File A
File B
device_console> status
Status: OK
device_console> clear
All files cleared
device_console> list
device_console> exit
[asdfgf@localhost ~]$
As part of testing, I want to get the output of each command. I want to use Python for it. I am looking at Python's subprocess, but somehow I am unable to put them together. Can you please help?
|
[
"it sounds like you want something more like 'Expect'.\ncheck out Pexpect\n\n\"Pexpect is a pure Python module that\n makes Python a better tool for\n controlling and automating other\n programs. Pexpect is similar to the\n Don Libes Expect system, but Pexpect\n as a different interface that is\n easier to understand. Pexpect is\n basically a pattern matching system.\n It runs programs and watches output.\n When output matches a given pattern\n Pexpect can respond as if a human were\n typing responses.\"\n\n",
"Use the subprocess module. Example:\nimport subprocess\n\n# Open the subprocess\nproc = subprocess.open('device_console', stdin=subprocess.PIPE, stdout.subprocess.PIPE)\n\n# Write a command\nproc.stdin.write('list\\n')\n\n# Read the results back -- this will block until a line of input is received\nlisting = proc.stdout.readline()\n\n# When you're done, close the input stream so the subprocess knows to exit\nproc.stdin.close()\n\n# Wait for subprocess to exit (optional) and get its exit status\nexit_status = proc.wait()\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"multithreading",
"parent",
"python",
"subprocess"
] |
stackoverflow_0002226162_multithreading_parent_python_subprocess.txt
|
Q:
Python: defining functions on the fly
I have the following code:
funcs = []
for i in range(10):
def func():
print i
funcs.append(func)
for f in funcs:
f()
The problem is that func is being overriden. Ie the output of the code is:
9
9
9
...
How would you solve this without defining new functions?
The optimal solution would be to change the name of the function. Ie:
for i in range(10):
def func+i():
...
(or some other weird syntax)
A:
The problem is not that func is being overwritten, it's that the value of i is being evaluated when the function is called, not when it is defined. If you want to evaluate i at definition time, put it in the function declaration, as a default argument to func.
funcs = []
for i in range(10):
def func(value=i):
print value
funcs.append(func)
for f in funcs:
f()
Default arguments are evaluated once, when the function is defined, so the incrementing loop will not affect them. This would work just as well if you used
def func(i=i):
print i
but I used the name value to make it clear which name is being used within the function.
A:
Returning func from another function is safest.
A:
You could try
for i in range(10):
def func(j=i):
print j
funcs.append(func)
for f in funcs:
f()
|
Python: defining functions on the fly
|
I have the following code:
funcs = []
for i in range(10):
def func():
print i
funcs.append(func)
for f in funcs:
f()
The problem is that func is being overriden. Ie the output of the code is:
9
9
9
...
How would you solve this without defining new functions?
The optimal solution would be to change the name of the function. Ie:
for i in range(10):
def func+i():
...
(or some other weird syntax)
|
[
"The problem is not that func is being overwritten, it's that the value of i is being evaluated when the function is called, not when it is defined. If you want to evaluate i at definition time, put it in the function declaration, as a default argument to func. \nfuncs = []\nfor i in range(10):\n def func(value=i):\n print value\n funcs.append(func)\n\nfor f in funcs:\n f()\n\nDefault arguments are evaluated once, when the function is defined, so the incrementing loop will not affect them. This would work just as well if you used\ndef func(i=i):\n print i\n\nbut I used the name value to make it clear which name is being used within the function.\n",
"Returning func from another function is safest.\n",
"You could try \nfor i in range(10):\n def func(j=i):\n print j\n funcs.append(func)\nfor f in funcs:\n f()\n\n"
] |
[
13,
0,
0
] |
[] |
[] |
[
"lambda",
"python"
] |
stackoverflow_0002222466_lambda_python.txt
|
Q:
Python vars() global name error
I'm having a bit of trouble understanding what's going wrong with the following function:
def ness():
pie='yum'
vars()[pie]=4
print vars()[pie]
print yum
So When I run that I get this result:
>>> ness()
4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in ness
NameError: global name 'yum' is not defined
If I don't write it as a function and just type it in on the command line one line at a time it works fine, like so:
>>> pie='yum'
>>> vars()[pie]=4
>>> print vars()[pie]
4
>>> print yum
4
>>>
Edit:
Suppose I wanted to make things a bit more complicated than this and instead of setting yum to a value and printing that value, I define some functions, and want to call one of them based on some input:
def ness(choo):
dic={}
dessert=()
dnum=[10,100]
desserts='pie'
dic[dessert]=str(desserts[bisect(dnum,choo)])
vars()[dic[dessert]]()
def p():
print 'ummmm ummm'
def i():
print 'hooo aaaaa'
def e():
print 'woooo'
So when I call ness I get a key error:
>>> ness(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in ness
KeyError: 'p'
Now I know I can do things like this with some elif statements, but I'm wondering if this would work too, and if using bisect like this would be more efficient (say if i need to check 1000 values of choo) than using elifs.
Thanks much for the assistance.
A:
vars() within a function gives you the local namespace, just like locals() -- see the docs. Outside of a function (e.g. at the prompt) locals() (and vars() of course) gives you the module's global namespace, just like globals(). As the docs say, trying to assign to a function's local variable through locals() (or equivalently, vars() inside a function) is not supported in Python. If you want to assign to a global variable, as you do when you're at the prompt (or otherwise outside of a function), use globals() instead of vars() (maybe not the cleanest approach -- global variables are understandably frowned upon -- but it does work).
A:
There is way to do it with exec
>>> def ness():
... pie='yum'
... exec pie+"=4"
... print vars()[pie]
... print yum
...
>>>
>>> ness()
4
4
But Instead of doing that, using a new dict is better and safe
>>> def ness():
... dic={}
... pie='yum'
... dic[pie]=4
... print dic[pie]
... print dic['yum']
...
>>> ness()
4
4
>>>
A:
It's not safe to modify the dict returned by vars()
vars([object])¶
Without an argument, act like locals().
With a module, class or class instance object as argument (or
anything else that has a dict
attribute), return that attribute.
Note
The returned dictionary should not be modified: the effects on the
corresponding symbol table are
undefined.
Your second example is a special case. vars() is equivalent to globals() in the global namespace, and the dict returned by globals() behaves as you would expect ( but is frowned upon )
>>> id(vars()),id(globals())
(3085426868L, 3085426868L)
A:
vars() is equivalent to locals(), which in the case of the function is the local variables in its scope and at in the interactive interpreter at the scope you have it, vars() is globals(). locals() is for reading only; the effects of trying to change it are undefined (and in practice, just doesn't work). globals() can be modified, but you still should never directly put anything in the dict it returns.
A:
[Edit: I must be wrong here, since the 'exec' example works.]
As everyone points out, it's a bad idea to modify vars(). You can understand the error, though, by realizing that python in some sense doesn't "see" that "yum" is a local. "print yum" is still resolved as a global reference; this happens before any code is executed.
It's the same reason you get an UnboundLocalError from:
>>> y = 100
>>> def foo(x):
... if x == 1:
... y = 10
... print y
...
>>> foo(1)
10
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in foo
UnboundLocalError: local variable 'y' referenced before assignment
|
Python vars() global name error
|
I'm having a bit of trouble understanding what's going wrong with the following function:
def ness():
pie='yum'
vars()[pie]=4
print vars()[pie]
print yum
So When I run that I get this result:
>>> ness()
4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in ness
NameError: global name 'yum' is not defined
If I don't write it as a function and just type it in on the command line one line at a time it works fine, like so:
>>> pie='yum'
>>> vars()[pie]=4
>>> print vars()[pie]
4
>>> print yum
4
>>>
Edit:
Suppose I wanted to make things a bit more complicated than this and instead of setting yum to a value and printing that value, I define some functions, and want to call one of them based on some input:
def ness(choo):
dic={}
dessert=()
dnum=[10,100]
desserts='pie'
dic[dessert]=str(desserts[bisect(dnum,choo)])
vars()[dic[dessert]]()
def p():
print 'ummmm ummm'
def i():
print 'hooo aaaaa'
def e():
print 'woooo'
So when I call ness I get a key error:
>>> ness(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in ness
KeyError: 'p'
Now I know I can do things like this with some elif statements, but I'm wondering if this would work too, and if using bisect like this would be more efficient (say if i need to check 1000 values of choo) than using elifs.
Thanks much for the assistance.
|
[
"vars() within a function gives you the local namespace, just like locals() -- see the docs. Outside of a function (e.g. at the prompt) locals() (and vars() of course) gives you the module's global namespace, just like globals(). As the docs say, trying to assign to a function's local variable through locals() (or equivalently, vars() inside a function) is not supported in Python. If you want to assign to a global variable, as you do when you're at the prompt (or otherwise outside of a function), use globals() instead of vars() (maybe not the cleanest approach -- global variables are understandably frowned upon -- but it does work).\n",
"There is way to do it with exec\n>>> def ness():\n... pie='yum'\n... exec pie+\"=4\"\n... print vars()[pie]\n... print yum\n...\n>>>\n>>> ness()\n4\n4\n\nBut Instead of doing that, using a new dict is better and safe\n>>> def ness():\n... dic={}\n... pie='yum'\n... dic[pie]=4\n... print dic[pie]\n... print dic['yum']\n...\n>>> ness()\n4\n4\n>>>\n\n",
"It's not safe to modify the dict returned by vars()\n\nvars([object])¶\nWithout an argument, act like locals().\nWith a module, class or class instance object as argument (or\n anything else that has a dict\n attribute), return that attribute.\nNote\nThe returned dictionary should not be modified: the effects on the\n corresponding symbol table are\n undefined.\n\nYour second example is a special case. vars() is equivalent to globals() in the global namespace, and the dict returned by globals() behaves as you would expect ( but is frowned upon )\n>>> id(vars()),id(globals())\n(3085426868L, 3085426868L)\n\n",
"vars() is equivalent to locals(), which in the case of the function is the local variables in its scope and at in the interactive interpreter at the scope you have it, vars() is globals(). locals() is for reading only; the effects of trying to change it are undefined (and in practice, just doesn't work). globals() can be modified, but you still should never directly put anything in the dict it returns.\n",
"[Edit: I must be wrong here, since the 'exec' example works.]\nAs everyone points out, it's a bad idea to modify vars(). You can understand the error, though, by realizing that python in some sense doesn't \"see\" that \"yum\" is a local. \"print yum\" is still resolved as a global reference; this happens before any code is executed.\nIt's the same reason you get an UnboundLocalError from:\n>>> y = 100\n>>> def foo(x):\n... if x == 1:\n... y = 10\n... print y\n... \n>>> foo(1)\n10\n>>> foo(2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 4, in foo\nUnboundLocalError: local variable 'y' referenced before assignment\n\n"
] |
[
4,
2,
1,
0,
0
] |
[] |
[] |
[
"global",
"python"
] |
stackoverflow_0002226386_global_python.txt
|
Q:
parsing table with BeautifulSoup and write in text file
I need data from table in text file (output.txt) in this format:
data1;data2;data3;data4;.....
Celkova podlahova plocha bytu;33m;Vytah;Ano;Nadzemne podlazie;Prizemne podlazie;.....;Forma vlastnictva;Osobne
All in "one line", separator is ";" (later export in csv-file).
I´m beginner.. Help, thanks.
from BeautifulSoup import BeautifulSoup
import urllib2
import codecs
response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever')
html = response.read()
soup = BeautifulSoup(html)
tabulka = soup.find("table", {"class" : "detail-char"})
for row in tabulka.findAll('tr'):
col = row.findAll('td')
prvy = col[0].string.strip()
druhy = col[1].string.strip()
record = ([prvy], [druhy])
fl = codecs.open('output.txt', 'wb', 'utf8')
for rec in record:
line = ''
for val in rec:
line += val + u';'
fl.write(line + u'\r\n')
fl.close()
A:
You are not keeping each record as you read it in. Try this, which stores the records in records:
from BeautifulSoup import BeautifulSoup
import urllib2
import codecs
response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever')
html = response.read()
soup = BeautifulSoup(html)
tabulka = soup.find("table", {"class" : "detail-char"})
records = [] # store all of the records in this list
for row in tabulka.findAll('tr'):
col = row.findAll('td')
prvy = col[0].string.strip()
druhy = col[1].string.strip()
record = '%s;%s' % (prvy, druhy) # store the record with a ';' between prvy and druhy
records.append(record)
fl = codecs.open('output.txt', 'wb', 'utf8')
line = ';'.join(records)
fl.write(line + u'\r\n')
fl.close()
This could be cleaned up more, but I think it's what you are wanting.
A:
here's an alternative non BS way, just for your task
store=[] #to store your results
url="""http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever"""
page=urllib2.urlopen(url)
data=page.read()
for table in data.split("</table>"):
if "<table" in table and 'class="detail-char' in table:
for item in table.split("</td>"):
if "<td" in item:
store.append(item.split(">")[-1].strip())
print ','.join(store)
output
$ ./python.py
Celková podlahová plocha bytu,33 m2,Výťah,Áno,Nadzemné podlažie,Prízemné podlažie,Stav,Čiastočná rekonštrukcia,Konštrukcia bytu,tehlová,Forma vlastníctva,osobné
|
parsing table with BeautifulSoup and write in text file
|
I need data from table in text file (output.txt) in this format:
data1;data2;data3;data4;.....
Celkova podlahova plocha bytu;33m;Vytah;Ano;Nadzemne podlazie;Prizemne podlazie;.....;Forma vlastnictva;Osobne
All in "one line", separator is ";" (later export in csv-file).
I´m beginner.. Help, thanks.
from BeautifulSoup import BeautifulSoup
import urllib2
import codecs
response = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever')
html = response.read()
soup = BeautifulSoup(html)
tabulka = soup.find("table", {"class" : "detail-char"})
for row in tabulka.findAll('tr'):
col = row.findAll('td')
prvy = col[0].string.strip()
druhy = col[1].string.strip()
record = ([prvy], [druhy])
fl = codecs.open('output.txt', 'wb', 'utf8')
for rec in record:
line = ''
for val in rec:
line += val + u';'
fl.write(line + u'\r\n')
fl.close()
|
[
"You are not keeping each record as you read it in. Try this, which stores the records in records:\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2\nimport codecs\n\nresponse = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever')\nhtml = response.read()\nsoup = BeautifulSoup(html)\n\ntabulka = soup.find(\"table\", {\"class\" : \"detail-char\"})\n\nrecords = [] # store all of the records in this list\nfor row in tabulka.findAll('tr'):\n col = row.findAll('td')\n prvy = col[0].string.strip()\n druhy = col[1].string.strip()\n record = '%s;%s' % (prvy, druhy) # store the record with a ';' between prvy and druhy\n records.append(record)\n\nfl = codecs.open('output.txt', 'wb', 'utf8')\nline = ';'.join(records)\nfl.write(line + u'\\r\\n')\nfl.close()\n\nThis could be cleaned up more, but I think it's what you are wanting.\n",
"here's an alternative non BS way, just for your task\nstore=[] #to store your results\nurl=\"\"\"http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art-real-1-izb-byt-sladkovicova-ul-kosice-sever\"\"\"\npage=urllib2.urlopen(url)\ndata=page.read()\nfor table in data.split(\"</table>\"):\n if \"<table\" in table and 'class=\"detail-char' in table:\n for item in table.split(\"</td>\"):\n if \"<td\" in item:\n store.append(item.split(\">\")[-1].strip())\nprint ','.join(store)\n\noutput\n$ ./python.py\nCelková podlahová plocha bytu,33 m2,Výťah,Áno,Nadzemné podlažie,Prízemné podlažie,Stav,Čiastočná rekonštrukcia,Konštrukcia bytu,tehlová,Forma vlastníctva,osobné\n\n"
] |
[
15,
0
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0002224602_beautifulsoup_python.txt
|
Q:
PyObjC + Xcode 3.2 + Non-Apple Python
I want to get started trying to develop a few simple applications with PyObjC. I installed PyObjC and the Xcode templates. I know that PyObjC itself works, since I've run this script successfully. When I tried to create a project from the Cocoa-Python Application template and ran it, I got this error:
Traceback (most recent call last):
File "main.py", line 10, in
import objc
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyObjC/objc/__init__.py", line 25, in
from _convenience import *
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyObjC/objc/_convenience.py", line 21, in
from itertools import imap
ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so, 2): no suitable image found. Did find:
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so: mach-o, but wrong architecture
2010-02-08 19:40:09.280 TestApplication[3229:a0f] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '/Users/icktoofay/Desktop/TestApplication/main.m:44 main() PyRun_SimpleFile failed with file '/Users/icktoofay/Desktop/TestApplication/build/Debug/TestApplication.app/Contents/Resources/main.py'. See console for errors.'
When I tried opening a normal Python prompt and importing itertools, there was no error. I'm using Python 2.6.4 from MacPorts on Mac OS X 10.6 Snow Leopard.
I'd appreciate any help.
A:
You have a 32-bit vs 64-bit problem. It appears you are using a Python 2.6 installed from MacPorts and apparently it was not a universal (32-bit/64-bit) build. Either your app is running as 64-bit and the Python is only 32-bit or the reverse. You can check by using file:
cd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/
cd lib/python2.6/lib-dynload/
file itertools.so
itertools.so: Mach-O universal binary with 2 architectures
itertools.so (for architecture x86_64): Mach-O 64-bit bundle x86_64
itertools.so (for architecture i386): Mach-O bundle i386
The easiest fix is likely to re-install the MacPorts Python and the additional packages you installed like PyObjC:
sudo port selfupdate
sudo port -u install python26 +universal ...
EDIT: Since you report that the Python is 64-bit, the problem then is almost certainly due to a problem with the Xcode template setup for your Python PyObjC project. The startup code is probably loading the Apple-supplied Python interpreter which is universal. You can check by adding something like this prior to the import objc:
import sys
sys.stderr.write(sys.executable)
For MacPorts, it should be
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
I'm not familiar enough with the ins-and-outs of using the templates under Xcode to know what might need to be changed and I doubt that many people use them with a MacPorts Python, especially under 10.6.
Another thought, the Apple-suppied Python 2.6.1 comes with a version of PyObjC already installed. Perhaps using it would be simpler. Or don't use Xcode and use py2app or another solution to run it.
|
PyObjC + Xcode 3.2 + Non-Apple Python
|
I want to get started trying to develop a few simple applications with PyObjC. I installed PyObjC and the Xcode templates. I know that PyObjC itself works, since I've run this script successfully. When I tried to create a project from the Cocoa-Python Application template and ran it, I got this error:
Traceback (most recent call last):
File "main.py", line 10, in
import objc
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyObjC/objc/__init__.py", line 25, in
from _convenience import *
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyObjC/objc/_convenience.py", line 21, in
from itertools import imap
ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so, 2): no suitable image found. Did find:
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so: mach-o, but wrong architecture
2010-02-08 19:40:09.280 TestApplication[3229:a0f] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '/Users/icktoofay/Desktop/TestApplication/main.m:44 main() PyRun_SimpleFile failed with file '/Users/icktoofay/Desktop/TestApplication/build/Debug/TestApplication.app/Contents/Resources/main.py'. See console for errors.'
When I tried opening a normal Python prompt and importing itertools, there was no error. I'm using Python 2.6.4 from MacPorts on Mac OS X 10.6 Snow Leopard.
I'd appreciate any help.
|
[
"You have a 32-bit vs 64-bit problem. It appears you are using a Python 2.6 installed from MacPorts and apparently it was not a universal (32-bit/64-bit) build. Either your app is running as 64-bit and the Python is only 32-bit or the reverse. You can check by using file:\ncd /opt/local/Library/Frameworks/Python.framework/Versions/2.6/\ncd lib/python2.6/lib-dynload/\nfile itertools.so \nitertools.so: Mach-O universal binary with 2 architectures\nitertools.so (for architecture x86_64): Mach-O 64-bit bundle x86_64\nitertools.so (for architecture i386): Mach-O bundle i386\n\nThe easiest fix is likely to re-install the MacPorts Python and the additional packages you installed like PyObjC:\nsudo port selfupdate\nsudo port -u install python26 +universal ...\n\nEDIT: Since you report that the Python is 64-bit, the problem then is almost certainly due to a problem with the Xcode template setup for your Python PyObjC project. The startup code is probably loading the Apple-supplied Python interpreter which is universal. You can check by adding something like this prior to the import objc:\nimport sys\nsys.stderr.write(sys.executable)\n\nFor MacPorts, it should be\n/opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python\n\nI'm not familiar enough with the ins-and-outs of using the templates under Xcode to know what might need to be changed and I doubt that many people use them with a MacPorts Python, especially under 10.6.\nAnother thought, the Apple-suppied Python 2.6.1 comes with a version of PyObjC already installed. Perhaps using it would be simpler. Or don't use Xcode and use py2app or another solution to run it.\n"
] |
[
3
] |
[] |
[] |
[
"pyobjc",
"python",
"python_itertools",
"xcode"
] |
stackoverflow_0002226902_pyobjc_python_python_itertools_xcode.txt
|
Q:
formatting currencies with Python
I would like to format integers as professional looking currency strings. For example:
1200000 -> $1.2 million
456 -> $456.00
Do you know a good library for this, ideally with localization to handle European formats.
A:
locale.currency() can handle the number bits, but I've not seen a module for the word part.
A:
Such formatting seems reasonable in some limited uses. But, should 1200000 be formatted as 1.2 million or 1.20 million? And isn't 456 more friendly as $456 (without the cents)?
Adding cents to large precise numbers is common in sweepstakes mailers (Ed McMann says you can win $12,000,000.00).
It seems a careful specification of what the proper output for different kinds of numbers is the larger problem. Once that's done, it would be pretty straightforward to write a formatting function.
|
formatting currencies with Python
|
I would like to format integers as professional looking currency strings. For example:
1200000 -> $1.2 million
456 -> $456.00
Do you know a good library for this, ideally with localization to handle European formats.
|
[
"locale.currency() can handle the number bits, but I've not seen a module for the word part.\n",
"Such formatting seems reasonable in some limited uses. But, should 1200000 be formatted as 1.2 million or 1.20 million? And isn't 456 more friendly as $456 (without the cents)?\nAdding cents to large precise numbers is common in sweepstakes mailers (Ed McMann says you can win $12,000,000.00).\nIt seems a careful specification of what the proper output for different kinds of numbers is the larger problem. Once that's done, it would be pretty straightforward to write a formatting function.\n"
] |
[
4,
1
] |
[] |
[] |
[
"currency",
"format",
"integer",
"python",
"string"
] |
stackoverflow_0002226935_currency_format_integer_python_string.txt
|
Q:
how does create a new app in pinax?
thanks
only need 'python manage.py startapp xx' ???
A:
You don't create a new app in pinax, you create a new app in your project. And yes, that command will do it.
|
how does create a new app in pinax?
|
thanks
only need 'python manage.py startapp xx' ???
|
[
"You don't create a new app in pinax, you create a new app in your project. And yes, that command will do it.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"pinax",
"python"
] |
stackoverflow_0002227246_django_pinax_python.txt
|
Q:
Group and stack tuples
I'm just starting with Python, and I can't figure out how to group tuples.
For instance, I have tuple1=("A", "B", "C") and tuple2=("1","2","3"). I want to combine these into a list, grouped by the first tuple. I want it to appear stacked, as in A1 A2 A3 on one line, and B1 B2 B3 on the next line.
I can make them print concatenated, but I can't figure out how to stack them nicely.
A:
>>> t1 = ("A", "B", "C")
>>> t2 = ("1", "2", "3")
>>> [x + y for x in t1 for y in t2]
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
>>> [[x + y for y in t2] for x in t1]
[['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']]
>>> x = _ # assign x to the last value
>>> for row in x:
... print " ".join(row)
...
A1 A2 A3
B1 B2 B3
C1 C2 C3
>>> for x in t1:
... for y in t2:
... print x + y, # notice the comma, special print-statement syntax
... print
A1 A2 A3
B1 B2 B3
C1 C2 C3
The [..] are used here as list comprehensions.
A:
I'm not exacly sure what your problem is precisely, but do you mean the following?
for x in ("A", "B", "C"):
print [x + y for y in ("1", "2", "3")]
What do you mean by stacked?
|
Group and stack tuples
|
I'm just starting with Python, and I can't figure out how to group tuples.
For instance, I have tuple1=("A", "B", "C") and tuple2=("1","2","3"). I want to combine these into a list, grouped by the first tuple. I want it to appear stacked, as in A1 A2 A3 on one line, and B1 B2 B3 on the next line.
I can make them print concatenated, but I can't figure out how to stack them nicely.
|
[
">>> t1 = (\"A\", \"B\", \"C\")\n>>> t2 = (\"1\", \"2\", \"3\")\n>>> [x + y for x in t1 for y in t2]\n['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']\n>>> [[x + y for y in t2] for x in t1]\n[['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']]\n>>> x = _ # assign x to the last value\n>>> for row in x:\n... print \" \".join(row)\n... \nA1 A2 A3\nB1 B2 B3\nC1 C2 C3\n>>> for x in t1:\n... for y in t2:\n... print x + y, # notice the comma, special print-statement syntax\n... print\nA1 A2 A3\nB1 B2 B3\nC1 C2 C3\n\nThe [..] are used here as list comprehensions.\n",
"I'm not exacly sure what your problem is precisely, but do you mean the following?\nfor x in (\"A\", \"B\", \"C\"):\n print [x + y for y in (\"1\", \"2\", \"3\")]\n\nWhat do you mean by stacked?\n"
] |
[
3,
1
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002227532_list_python.txt
|
Q:
Python question - I have a List of Classes, how do I remove duplicates?
Am writing an App Engine application (it's a simple quest system for a game):
so I have a list
class Quest(db.Model):
name = db.StringProperty()
# note: I made about 10 different quest entities ( quest1 to quest10)
class User(db.Model):
completed_quests = db.StringListProperty() # to store keys of completed quests
# note: I made some fake data showing that the user completed 3 quests.
# user.completed_quests = ["key1","key2","key3"] - keys belong to the corresponding quests
so I query the user and his/her completed quests.
user = User.get_by_key_name(userid)
then I query the of quests model
all_quests = Quest.all()
the question is: how do I cross check my user.completed_quests list with all_quests?
my goal: I want to present to the user a web page, where he/she can see :
- a list of completed quests AND
- incomplete quests.
a method which I'm using:
# prepare a buffer
completed_quests = []
for quest in all_quests:
for k,completed_quest in enumerate(user.completed_quests):
if str(completed_quest) == str(quest.key()): # the point of detection
completed_quests.append(completed_quest)
# final product is a list of completed quest entites
but how do I do this for my incompleted quests?
A:
You can use difference:
all = set(quest.key() for quest in all_quests)
complete = set(completed_quests)
incomplete = all.difference(complete)
A:
Try something like this:
quests = [(x.key(), x) for x in Quest.all.fetch(1000)]
incomplete_quests = [v for k, v in quests if k not in a_user.completed_quests]
This presumes, for simplicity, that you first converted your list of completed quests to a db.ListProperty(db.Key).
|
Python question - I have a List of Classes, how do I remove duplicates?
|
Am writing an App Engine application (it's a simple quest system for a game):
so I have a list
class Quest(db.Model):
name = db.StringProperty()
# note: I made about 10 different quest entities ( quest1 to quest10)
class User(db.Model):
completed_quests = db.StringListProperty() # to store keys of completed quests
# note: I made some fake data showing that the user completed 3 quests.
# user.completed_quests = ["key1","key2","key3"] - keys belong to the corresponding quests
so I query the user and his/her completed quests.
user = User.get_by_key_name(userid)
then I query the of quests model
all_quests = Quest.all()
the question is: how do I cross check my user.completed_quests list with all_quests?
my goal: I want to present to the user a web page, where he/she can see :
- a list of completed quests AND
- incomplete quests.
a method which I'm using:
# prepare a buffer
completed_quests = []
for quest in all_quests:
for k,completed_quest in enumerate(user.completed_quests):
if str(completed_quest) == str(quest.key()): # the point of detection
completed_quests.append(completed_quest)
# final product is a list of completed quest entites
but how do I do this for my incompleted quests?
|
[
"You can use difference:\nall = set(quest.key() for quest in all_quests)\ncomplete = set(completed_quests)\nincomplete = all.difference(complete)\n\n",
"Try something like this:\nquests = [(x.key(), x) for x in Quest.all.fetch(1000)]\nincomplete_quests = [v for k, v in quests if k not in a_user.completed_quests]\n\nThis presumes, for simplicity, that you first converted your list of completed quests to a db.ListProperty(db.Key).\n"
] |
[
3,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002227297_google_app_engine_python.txt
|
Q:
Silverlight databinding with IronPython and Datagrid
We've been successfully using clrtype with IronPython 2.6 and
Silverlight for databinding, based on the example provided by Lukás(:
http://gui-at.blogspot.com/2009/11/inotifypropertychanged-and-databinding.html
We create the binding when we create the datagrid columns programatically. Because we are using IronPython some of the static databinding techniques you would normally use with C# don't work.
I've been trying (and failing) to get a column in the grid show
different colors based on databinding.
I've got the colored bubble showing in the grid, but can't get
databinding to the color to work. First the basics.
This is the xaml for the bubble with a fixed color:
<DataTemplate xmlns='http://schemas.microsoft.com/client/2007'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Ellipse Stroke="#FF222222" Height="15" Width="15">
<Ellipse.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop x:Name="bubbleColor" Offset="0.694"
Color="#FF00FF40" />
<GradientStop Color="#FFE6E6E6"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
I can add a column based on this template very simply. The loadXaml function is a thin wrapper around XamlReader.Load:
from com_modules.loadxaml import loadXaml
from System.Windows.Controls import DataGridTemplateColumn
column = DataGridTemplateColumn()
column.CellTemplate = loadXaml('templatecolumn')
column.Header = 'Bubble'
grid.Columns.Add(column)
If I try to naively specify a binding in the xaml then I get a
PARSER_BAD_PROPERTY_VALUE when I attempt to load the xaml (so no hope of
setting up the binding after load):
<GradientStop x:Name="bubbleColor" Offset="0.694" Color="{Binding color}" />
One approach I tried was to create a ValueConverter. Here is the
skeleton of the class I created:
from System import Type
from System.Globalization import CultureInfo
from System.Windows.Data import IValueConverter
class ColorConverter(IValueConverter):
_clrnamespace = "Converters"
__metaclass__ = clrtype.ClrClass
@clrtype.accepts(object, Type, object, CultureInfo)
@clrtype.returns(object)
def Convert(self, value, targetType, parameter, culture):
pass
@clrtype.accepts(object, Type, object, CultureInfo)
@clrtype.returns(object)
def ConvertBack(self, value, targetType, parameter, culture):
pass
As there is a _clrnamespace specified I thought I might then be able to use this converter in xaml. Trying to reference the ColorConverter class in the Converters namespace in a resources dictionary again causes blow ups when loading the xaml.
Setting this up programatically would be ideal. Anyone got any ideas?
A:
I don't know anything about IronPython, but I know that you cannot bind to a Color in Silverlight, regardless of the language used. This has caused me many grievances. In Silverlight 3 you can only bind properties on a FrameworkElement, and since GradientStop is a DependencyObject, it will not work. The good news is that Silverlight 4 will get rid of that limitation and allow you to bind properties on DependencyObject. I haven't tried it though, so I cannot say for sure. More info here:
http://timheuer.com/blog/archive/2009/11/18/whats-new-in-silverlight-4-complete-guide-new-features.aspx#dobind
At the moment, what you could do is to bind the Fill property on the Ellipse instead. But then you will have to create the entire LinearGradientBrush in your converter code, so it's a bit complicated.
|
Silverlight databinding with IronPython and Datagrid
|
We've been successfully using clrtype with IronPython 2.6 and
Silverlight for databinding, based on the example provided by Lukás(:
http://gui-at.blogspot.com/2009/11/inotifypropertychanged-and-databinding.html
We create the binding when we create the datagrid columns programatically. Because we are using IronPython some of the static databinding techniques you would normally use with C# don't work.
I've been trying (and failing) to get a column in the grid show
different colors based on databinding.
I've got the colored bubble showing in the grid, but can't get
databinding to the color to work. First the basics.
This is the xaml for the bubble with a fixed color:
<DataTemplate xmlns='http://schemas.microsoft.com/client/2007'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Ellipse Stroke="#FF222222" Height="15" Width="15">
<Ellipse.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop x:Name="bubbleColor" Offset="0.694"
Color="#FF00FF40" />
<GradientStop Color="#FFE6E6E6"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
I can add a column based on this template very simply. The loadXaml function is a thin wrapper around XamlReader.Load:
from com_modules.loadxaml import loadXaml
from System.Windows.Controls import DataGridTemplateColumn
column = DataGridTemplateColumn()
column.CellTemplate = loadXaml('templatecolumn')
column.Header = 'Bubble'
grid.Columns.Add(column)
If I try to naively specify a binding in the xaml then I get a
PARSER_BAD_PROPERTY_VALUE when I attempt to load the xaml (so no hope of
setting up the binding after load):
<GradientStop x:Name="bubbleColor" Offset="0.694" Color="{Binding color}" />
One approach I tried was to create a ValueConverter. Here is the
skeleton of the class I created:
from System import Type
from System.Globalization import CultureInfo
from System.Windows.Data import IValueConverter
class ColorConverter(IValueConverter):
_clrnamespace = "Converters"
__metaclass__ = clrtype.ClrClass
@clrtype.accepts(object, Type, object, CultureInfo)
@clrtype.returns(object)
def Convert(self, value, targetType, parameter, culture):
pass
@clrtype.accepts(object, Type, object, CultureInfo)
@clrtype.returns(object)
def ConvertBack(self, value, targetType, parameter, culture):
pass
As there is a _clrnamespace specified I thought I might then be able to use this converter in xaml. Trying to reference the ColorConverter class in the Converters namespace in a resources dictionary again causes blow ups when loading the xaml.
Setting this up programatically would be ideal. Anyone got any ideas?
|
[
"I don't know anything about IronPython, but I know that you cannot bind to a Color in Silverlight, regardless of the language used. This has caused me many grievances. In Silverlight 3 you can only bind properties on a FrameworkElement, and since GradientStop is a DependencyObject, it will not work. The good news is that Silverlight 4 will get rid of that limitation and allow you to bind properties on DependencyObject. I haven't tried it though, so I cannot say for sure. More info here:\nhttp://timheuer.com/blog/archive/2009/11/18/whats-new-in-silverlight-4-complete-guide-new-features.aspx#dobind\nAt the moment, what you could do is to bind the Fill property on the Ellipse instead. But then you will have to create the entire LinearGradientBrush in your converter code, so it's a bit complicated.\n"
] |
[
1
] |
[] |
[] |
[
"data_binding",
"datagrid",
"ironpython",
"python",
"silverlight"
] |
stackoverflow_0002224805_data_binding_datagrid_ironpython_python_silverlight.txt
|
Q:
How to retrieve attributes of xml tag in Python?
I'm looking for a way to add attributes to xml tags in python. Or to create a new tag with a new attributes
for example, I have the following xml file:
<types name='character' shortName='chrs'>
....
...
</types>
and i want to add an attribute to make it look like this:
<types name='character' shortName='chrs' fullName='MayaCharacters'>
....
...
</types>
how do I do that with python? by the way. I use python and minidom for this
please help. thanks in advance
A:
You can use the attributes property of the respective Node object.
For example:
from xml.dom.minidom import parseString
documentNode = parseString("<types name='character' shortName='chrs'></types>")
typesNode = documentNode.firstChild
# Getting an attribute
print typesNode.attributes["name"].value # will print "character"
# Setting an attribute
typesNode.attributes["mynewattribute"] = u"mynewvalue"
print documentNode.toprettyxml()
The last print statement will output this XML document:
<?xml version="1.0" ?>
<types mynewattribute="mynewvalue" name="character" shortName="chrs"/>
A:
I learned xml parsing in python from this great article. It has an attribute section, which cant be linked to, but just search for "Attributes" on that page and you'll find it, that holds the information you need.
But in short (snippet stolen from said page):
>>> building_element.setAttributeNS("http://www.boddie.org.uk/paul/business", "business:name", "Ivory Tower")
>>> building_element.getAttributeNS("http://www.boddie.org.uk/paul/business", "name")
'Ivory Tower'
You probably want to skip the handling of namespaces, to make the code cleaner, unless you need them.
A:
It would seem that you just call setAttribute for the parsed dom objects.
http://developer.taboca.com/cases/en/creating_a_new_xml_document_with_python/
|
How to retrieve attributes of xml tag in Python?
|
I'm looking for a way to add attributes to xml tags in python. Or to create a new tag with a new attributes
for example, I have the following xml file:
<types name='character' shortName='chrs'>
....
...
</types>
and i want to add an attribute to make it look like this:
<types name='character' shortName='chrs' fullName='MayaCharacters'>
....
...
</types>
how do I do that with python? by the way. I use python and minidom for this
please help. thanks in advance
|
[
"You can use the attributes property of the respective Node object.\nFor example:\nfrom xml.dom.minidom import parseString\ndocumentNode = parseString(\"<types name='character' shortName='chrs'></types>\")\ntypesNode = documentNode.firstChild\n\n# Getting an attribute\nprint typesNode.attributes[\"name\"].value # will print \"character\"\n\n# Setting an attribute\ntypesNode.attributes[\"mynewattribute\"] = u\"mynewvalue\"\nprint documentNode.toprettyxml()\n\nThe last print statement will output this XML document:\n<?xml version=\"1.0\" ?>\n<types mynewattribute=\"mynewvalue\" name=\"character\" shortName=\"chrs\"/>\n\n",
"I learned xml parsing in python from this great article. It has an attribute section, which cant be linked to, but just search for \"Attributes\" on that page and you'll find it, that holds the information you need.\nBut in short (snippet stolen from said page):\n>>> building_element.setAttributeNS(\"http://www.boddie.org.uk/paul/business\", \"business:name\", \"Ivory Tower\")\n>>> building_element.getAttributeNS(\"http://www.boddie.org.uk/paul/business\", \"name\")\n'Ivory Tower'\n\nYou probably want to skip the handling of namespaces, to make the code cleaner, unless you need them.\n",
"It would seem that you just call setAttribute for the parsed dom objects.\nhttp://developer.taboca.com/cases/en/creating_a_new_xml_document_with_python/\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"python",
"tags",
"xml"
] |
stackoverflow_0002228049_python_tags_xml.txt
|
Q:
cross-platform html widget for pygtk
I'm trying to write a small gui app in pygtk which needs an html-rendering widget. I'd like to be able to use it in a windows environment.
Currently I'm using pywebkitgtk on my GNU/Linux system, and it works extremely well, but it seems it's not possible to use this on Windows at this time.
Can anyone give me any suggestions on how to proceed? Do I need to work out how to embed IE using COM objects under Windows, and stick with pywebkitgtk on GNU/Linux?
I'm at an early stage, and am prepared to jettison pygtk in favour of another toolkit, say pyqt, if it affords a simpler solution (though I'd sooner stick with pygtk if possible).
A:
In my experience, having developed cross-platform applications with both PyQt and PyGTK, you should consider moving to PyQt. It comes with a browser widget by default which runs fine on all platforms, and support for non-Linux platforms is outstanding compared to PyGTK. For PyGTK, you will have to be prepared building PyGObject/PyCairo/PyGTK, or even the full stack, yourself on Windows and Mac OS X.
A:
There is also gtkhtml2, but might not solve your problem on Windows. I haven't used it before myself. Another option to consider is pymozembed, to embed a Mozilla browser window in your GTK app.
|
cross-platform html widget for pygtk
|
I'm trying to write a small gui app in pygtk which needs an html-rendering widget. I'd like to be able to use it in a windows environment.
Currently I'm using pywebkitgtk on my GNU/Linux system, and it works extremely well, but it seems it's not possible to use this on Windows at this time.
Can anyone give me any suggestions on how to proceed? Do I need to work out how to embed IE using COM objects under Windows, and stick with pywebkitgtk on GNU/Linux?
I'm at an early stage, and am prepared to jettison pygtk in favour of another toolkit, say pyqt, if it affords a simpler solution (though I'd sooner stick with pygtk if possible).
|
[
"In my experience, having developed cross-platform applications with both PyQt and PyGTK, you should consider moving to PyQt. It comes with a browser widget by default which runs fine on all platforms, and support for non-Linux platforms is outstanding compared to PyGTK. For PyGTK, you will have to be prepared building PyGObject/PyCairo/PyGTK, or even the full stack, yourself on Windows and Mac OS X.\n",
"There is also gtkhtml2, but might not solve your problem on Windows. I haven't used it before myself. Another option to consider is pymozembed, to embed a Mozilla browser window in your GTK app.\n"
] |
[
2,
0
] |
[] |
[] |
[
"cross_platform",
"html_rendering",
"pygtk",
"pyqt",
"python"
] |
stackoverflow_0002227770_cross_platform_html_rendering_pygtk_pyqt_python.txt
|
Q:
Is there a way to prevent detection by the website when a screenshot is taken using a Mac Os X Safari browser?
There is a thread discussing Darwin notifications being sent after a screenshot is taken. Does this apply to websites viewed via Safari? Do the same restrictions apply to PC sytems? Would taking the picture via a Python script in Linux or running Safari in a VM circumvent detection?
A:
if you are talking about this thread, please note that it seems to apply only to the iPhone. there is nothing similar in any decent web browser on any desktop platform (plus, anybody can put a proxy to filter this kind of notification, or create its own browser out of off-the-shelf components).
note that rendering a webpage in a browser is the same as taking a screenshot: the browser needs to know what to render on the screen and how to draw it. this is the purpose of HTML and CSS, to describe what and how to render a page, so the simple fact of downloading the content of a webpage gives enough informations for rendering into whatever you want, be it a screen, a picture saved or a file on disk.
|
Is there a way to prevent detection by the website when a screenshot is taken using a Mac Os X Safari browser?
|
There is a thread discussing Darwin notifications being sent after a screenshot is taken. Does this apply to websites viewed via Safari? Do the same restrictions apply to PC sytems? Would taking the picture via a Python script in Linux or running Safari in a VM circumvent detection?
|
[
"if you are talking about this thread, please note that it seems to apply only to the iPhone. there is nothing similar in any decent web browser on any desktop platform (plus, anybody can put a proxy to filter this kind of notification, or create its own browser out of off-the-shelf components).\nnote that rendering a webpage in a browser is the same as taking a screenshot: the browser needs to know what to render on the screen and how to draw it. this is the purpose of HTML and CSS, to describe what and how to render a page, so the simple fact of downloading the content of a webpage gives enough informations for rendering into whatever you want, be it a screen, a picture saved or a file on disk.\n"
] |
[
2
] |
[] |
[] |
[
"browser_detection",
"python",
"safari",
"screenshot",
"virtual_machine"
] |
stackoverflow_0002227469_browser_detection_python_safari_screenshot_virtual_machine.txt
|
Q:
A blackbox testing frame with testing management system
Is there a testing framework (preferable python) that executes test, monitor the progress (failed/passed/timeout) and controls the vmware? Thanks
I am trying to make some automation functional testing in Vmware using Autoit script, VMs are controlled by a little python script on the host machine (deploy test files into VMs, execute them and collect the results data). But now it seems to be lots of works to do if I want this script to be able to manage and execute a series of test cases.
Thanks a lot!
Cheers,
Zhe
A:
There are lots of continuous integration tools that may do what you want.
One implemented in Python that may fit your need is Buildbot - it can manage running builds and tests across multiple machines and consolidating the results.
|
A blackbox testing frame with testing management system
|
Is there a testing framework (preferable python) that executes test, monitor the progress (failed/passed/timeout) and controls the vmware? Thanks
I am trying to make some automation functional testing in Vmware using Autoit script, VMs are controlled by a little python script on the host machine (deploy test files into VMs, execute them and collect the results data). But now it seems to be lots of works to do if I want this script to be able to manage and execute a series of test cases.
Thanks a lot!
Cheers,
Zhe
|
[
"There are lots of continuous integration tools that may do what you want.\nOne implemented in Python that may fit your need is Buildbot - it can manage running builds and tests across multiple machines and consolidating the results.\n"
] |
[
2
] |
[] |
[] |
[
"frameworks",
"python",
"testing",
"vmware"
] |
stackoverflow_0002228349_frameworks_python_testing_vmware.txt
|
Q:
Python Authentication to SAMBA share
I'm able to map the drive without problems on network shares without authentication. But I'm missing something once I try to authenticate with a username and password. Here is the current working example of the code with the error message I keep receiving.
#!/usr/bin/python
# Drive Map Script
import pywintypes
import win32com.client
# Disconnect previous mapped drives
testnetwork = win32com.client.Dispatch('Wscript.Network')
network_drives = testnetwork.EnumNetworkDrives()
for mapped_drive in [network_drives.Item(i)
for i in range(0, network_drives.Count() -1 , 2)
if network_drives.Item(i)]:
testnetwork.RemoveNetworkDrive(mapped_drive, True, True)
# Mount the drives
drive_mapping = [
('z:', '\\\\192.168.1.100\\Some_Share', 'someuser', 'somepass')]
for drive_letter, network_path, user_name, user_pass in drive_mapping:
try:
testnetwork.MapNetworkDrive(drive_letter, network_path)
except Exception, err:
print err
And the error the code generates upon execution:
(-2147352567, 'Exception occurred.',
(0, u'WSHNetwork.MapNetworkDrive',
u'Logon failure: unknown user name or
bad password.\r\n', None, 0,
-2147023570), None)
A:
You aren't passing user_name and user_pass to MapNetworkDrive.
Try this instead:
testnetwork.MapNetworkDrive(drive_letter, network_path, True, user_name, user_pass)
Note: the True passed there is a flag that indicates whether the mapping information is stored in the current user's profile.
|
Python Authentication to SAMBA share
|
I'm able to map the drive without problems on network shares without authentication. But I'm missing something once I try to authenticate with a username and password. Here is the current working example of the code with the error message I keep receiving.
#!/usr/bin/python
# Drive Map Script
import pywintypes
import win32com.client
# Disconnect previous mapped drives
testnetwork = win32com.client.Dispatch('Wscript.Network')
network_drives = testnetwork.EnumNetworkDrives()
for mapped_drive in [network_drives.Item(i)
for i in range(0, network_drives.Count() -1 , 2)
if network_drives.Item(i)]:
testnetwork.RemoveNetworkDrive(mapped_drive, True, True)
# Mount the drives
drive_mapping = [
('z:', '\\\\192.168.1.100\\Some_Share', 'someuser', 'somepass')]
for drive_letter, network_path, user_name, user_pass in drive_mapping:
try:
testnetwork.MapNetworkDrive(drive_letter, network_path)
except Exception, err:
print err
And the error the code generates upon execution:
(-2147352567, 'Exception occurred.',
(0, u'WSHNetwork.MapNetworkDrive',
u'Logon failure: unknown user name or
bad password.\r\n', None, 0,
-2147023570), None)
|
[
"You aren't passing user_name and user_pass to MapNetworkDrive.\nTry this instead:\ntestnetwork.MapNetworkDrive(drive_letter, network_path, True, user_name, user_pass)\n\nNote: the True passed there is a flag that indicates whether the mapping information is stored in the current user's profile.\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002228846_python.txt
|
Q:
How to find the source of increasing memory usage of a twisted server?
I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see in following figure:
You can see the curve of memory usage goes up where the curve of listeners/radios goes up, but after the peak of listener/radios, the memory usage is still high, never goes down.
I have tried following method for solving this problem:
Upgrade Twisted from 8.2 to 9.0
Use guppy to dump heapy, but doesn't help at all
Switch selector reactor to epoll reactor, same problem.
Use objgraph to draw the diagram of objects' relation, but I can't see points from that.
Here is the environment I used for running my twisted server:
Python: 2.5.4 r254:67916
OS: Linux version 2.6.18-164.9.1.el5PAE (mockbuild@builder16.centos.org) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-46))
Twisted: 9.0 (under virtualenv)
The dump of guppy:
Partition of a set of 116280 objects. Total size = 9552004 bytes.
Index Count % Size % Cumulative % Type
0 52874 45 4505404 47 4505404 47 str
1 5927 5 2231096 23 6736500 71 dict
2 29215 25 1099676 12 7836176 82 tuple
3 7503 6 510204 5 8346380 87 types.CodeType
4 7625 7 427000 4 8773380 92 function
5 672 1 292968 3 9066348 95 type
6 866 1 82176 1 9148524 96 list
7 1796 2 71840 1 9220364 97 __builtin__.weakref
8 1140 1 41040 0 9261404 97 __builtin__.wrapper_descriptor
9 2603 2 31236 0 9292640 97 int
As you can see, the total size 9552004 bytes is 9.1 MB, and you can see the rss reported by ps command:
[xxxx@webxx ~]$ ps -u xxxx-o pid,rss,cmd
PID RSS CMD
22123 67492 twistd -y broadcast.tac -r epoll
The rss of my server is 65.9 MB, it means there are 56.8 MB invisible memory usage in my server, what are they?
My questions are:
How to find the source of increasing memory usage?
What are visible memory usage to guppy?
What are those invisible memory usage?
Is that caused by memory leaks of some modules written in C? If it is, how can I trace and fix that?
How does Python manage memory? Memory pool? I think this might caused by audio data chunks. So that there are little leaks in memory chunk owned by Python interpreter.
Update 2010/1/20:
It's interesting, I download the latest log file, and it shows that the memory never increase from a moment. I think might be the allocated memory space is big enough. Here is the latest figure.
Update 2010/1/21:
Another figure here. hum.... raise a little bit
Oops... Still going up
A:
As my guessing, it is due to memory fragmentation problem. The original design is to keep audio data chunks in a list, all of them are not in fixed size. Once the total size of the buffering list exceeds the limit of buffer, it pops some chunks from the top of list for limiting the size. It might looks like this:
chunk size 511
chunk size 1040
chunk size 386
chunk size 1350
...
Most of them are bigger than 256 bytes, Python uses malloc for chunks that are bigger than 256 bytes rather than uses memory pool. And you can imagine that those chunks are allocated, and released, what would happened? For example, when the chunk with 1350 size is released, then there might be a free 1350 bytes space in heap. After that, here comes another request 988, once malloc pick up the hole, and then there is another new little free hole of size 362. After long running, there are more and more little holes in heaps, in other words, there are so many fragments in heaps. The size of page of virtual memory usually is 4KB, those fragments are distributed around a big range of heap, it makes OS can't swap those page out. Thus, the RSS is always high.
After modification of the design of the audio chunk management module of my server, it uses little memory now. You can see the figure and compare to previous one.
The new design use bytearray rather than list of strings. It is a big chunk of memory, so there is no more fragmentation.
A:
It does sound like a memory leak in a C module to me. Valgrind is a good tool to track memory-allocation related problems. I don't know how good it works with run-time loaded modules though...
A:
Have you thought about using CentOS' alternative to dtrace - SystemTap I think its called.
This should give you a pretty low level trace of what's happening inside your *nix processes.......a stab in the dark, but might give you some more transparency on intraprocess activity.
Interesting question though. Looking forward to see other's responses.
Ben
|
How to find the source of increasing memory usage of a twisted server?
|
I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see in following figure:
You can see the curve of memory usage goes up where the curve of listeners/radios goes up, but after the peak of listener/radios, the memory usage is still high, never goes down.
I have tried following method for solving this problem:
Upgrade Twisted from 8.2 to 9.0
Use guppy to dump heapy, but doesn't help at all
Switch selector reactor to epoll reactor, same problem.
Use objgraph to draw the diagram of objects' relation, but I can't see points from that.
Here is the environment I used for running my twisted server:
Python: 2.5.4 r254:67916
OS: Linux version 2.6.18-164.9.1.el5PAE (mockbuild@builder16.centos.org) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-46))
Twisted: 9.0 (under virtualenv)
The dump of guppy:
Partition of a set of 116280 objects. Total size = 9552004 bytes.
Index Count % Size % Cumulative % Type
0 52874 45 4505404 47 4505404 47 str
1 5927 5 2231096 23 6736500 71 dict
2 29215 25 1099676 12 7836176 82 tuple
3 7503 6 510204 5 8346380 87 types.CodeType
4 7625 7 427000 4 8773380 92 function
5 672 1 292968 3 9066348 95 type
6 866 1 82176 1 9148524 96 list
7 1796 2 71840 1 9220364 97 __builtin__.weakref
8 1140 1 41040 0 9261404 97 __builtin__.wrapper_descriptor
9 2603 2 31236 0 9292640 97 int
As you can see, the total size 9552004 bytes is 9.1 MB, and you can see the rss reported by ps command:
[xxxx@webxx ~]$ ps -u xxxx-o pid,rss,cmd
PID RSS CMD
22123 67492 twistd -y broadcast.tac -r epoll
The rss of my server is 65.9 MB, it means there are 56.8 MB invisible memory usage in my server, what are they?
My questions are:
How to find the source of increasing memory usage?
What are visible memory usage to guppy?
What are those invisible memory usage?
Is that caused by memory leaks of some modules written in C? If it is, how can I trace and fix that?
How does Python manage memory? Memory pool? I think this might caused by audio data chunks. So that there are little leaks in memory chunk owned by Python interpreter.
Update 2010/1/20:
It's interesting, I download the latest log file, and it shows that the memory never increase from a moment. I think might be the allocated memory space is big enough. Here is the latest figure.
Update 2010/1/21:
Another figure here. hum.... raise a little bit
Oops... Still going up
|
[
"As my guessing, it is due to memory fragmentation problem. The original design is to keep audio data chunks in a list, all of them are not in fixed size. Once the total size of the buffering list exceeds the limit of buffer, it pops some chunks from the top of list for limiting the size. It might looks like this:\n\nchunk size 511\nchunk size 1040\nchunk size 386\nchunk size 1350\n...\n\nMost of them are bigger than 256 bytes, Python uses malloc for chunks that are bigger than 256 bytes rather than uses memory pool. And you can imagine that those chunks are allocated, and released, what would happened? For example, when the chunk with 1350 size is released, then there might be a free 1350 bytes space in heap. After that, here comes another request 988, once malloc pick up the hole, and then there is another new little free hole of size 362. After long running, there are more and more little holes in heaps, in other words, there are so many fragments in heaps. The size of page of virtual memory usually is 4KB, those fragments are distributed around a big range of heap, it makes OS can't swap those page out. Thus, the RSS is always high. \nAfter modification of the design of the audio chunk management module of my server, it uses little memory now. You can see the figure and compare to previous one.\n\nThe new design use bytearray rather than list of strings. It is a big chunk of memory, so there is no more fragmentation.\n",
"It does sound like a memory leak in a C module to me. Valgrind is a good tool to track memory-allocation related problems. I don't know how good it works with run-time loaded modules though...\n",
"Have you thought about using CentOS' alternative to dtrace - SystemTap I think its called. \nThis should give you a pretty low level trace of what's happening inside your *nix processes.......a stab in the dark, but might give you some more transparency on intraprocess activity.\nInteresting question though. Looking forward to see other's responses.\nBen\n"
] |
[
6,
2,
0
] |
[] |
[] |
[
"memory_leaks",
"memory_management",
"python",
"twisted"
] |
stackoverflow_0002100192_memory_leaks_memory_management_python_twisted.txt
|
Q:
Python CDROM Production
I have been using Macromedia / Adobe Director & Lingo since 1998. I am extremely familiar with using this software to create CDROMs and DVDs and also have a good knowledge of design elements and their integration such as flash videos, images & audio etc.
I am always keen to explore other technologies and understand that Python can be used to create CDROMs.
I have tried Googling some information on this subject but to no avail. Does anyone know the pros and cons of Python CDROM production? Is it capable of delivering such media rich experiences as Adobe Director? What are the limitations?
Any help / resources would be greatly appreciated.
A:
sounds grim to me
I presume you mean an auto-run executable for Windows that runs when a CDROM is inserted, to provide some sort of flashy popup experience thing.
I would stick with flash. You can make Python executables, and you can use them for this, but flash or a similar tech seems like a better alternative.
I suppose Cairo SVG rendering/Animation and Python would work theoretically, but really, you would be reinventing the wheel.
A:
Python isn't the tool you are looking for... [waves hand across in front of Mindblip's face]
Stick with Director or try Flash with either MPlayer or Zinc.
A:
It sounds like you're not asking so much for mass-copying of CDs/DVDs (which is what I assumed from reading the title), but for a Python-based replacement for Adobe Director? I don't think anything like that presently exists.
However, Python could certainly help you out with the scripting and control of various elements in the production process -- for example, taking the tedium out of assembling lots of files together into one final package. You'd have to be more specific about what you're looking for, though.
|
Python CDROM Production
|
I have been using Macromedia / Adobe Director & Lingo since 1998. I am extremely familiar with using this software to create CDROMs and DVDs and also have a good knowledge of design elements and their integration such as flash videos, images & audio etc.
I am always keen to explore other technologies and understand that Python can be used to create CDROMs.
I have tried Googling some information on this subject but to no avail. Does anyone know the pros and cons of Python CDROM production? Is it capable of delivering such media rich experiences as Adobe Director? What are the limitations?
Any help / resources would be greatly appreciated.
|
[
"sounds grim to me \nI presume you mean an auto-run executable for Windows that runs when a CDROM is inserted, to provide some sort of flashy popup experience thing.\nI would stick with flash. You can make Python executables, and you can use them for this, but flash or a similar tech seems like a better alternative.\nI suppose Cairo SVG rendering/Animation and Python would work theoretically, but really, you would be reinventing the wheel.\n",
"Python isn't the tool you are looking for... [waves hand across in front of Mindblip's face]\nStick with Director or try Flash with either MPlayer or Zinc.\n",
"It sounds like you're not asking so much for mass-copying of CDs/DVDs (which is what I assumed from reading the title), but for a Python-based replacement for Adobe Director? I don't think anything like that presently exists.\nHowever, Python could certainly help you out with the scripting and control of various elements in the production process -- for example, taking the tedium out of assembling lots of files together into one final package. You'd have to be more specific about what you're looking for, though.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"adobe",
"cd_rom",
"dvd",
"media",
"python"
] |
stackoverflow_0002228988_adobe_cd_rom_dvd_media_python.txt
|
Q:
How to transform tuple of string(object locations) to dictionary of objects in python
I would like to transform a tuple:
TEST_CLASSES = (
'common.test.TestClass',
)
to
TEST_CLASSES = {
'test': common.test.TestClass,
}
How to make a dictionary is simple but I have a problem with conversion from string to object. Could anybody help me please? thanks!
A:
You could use eval, which can be evil if your inputs are not safe:
>>> import os
>>> eval('os.path.join')
<function join at 0x00BBA2B8>
if the common.test.TestClass doesn't exist in the current namespace a NameError will be raised:
>>> eval('math.isnan')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eval('math.isnan')
File "<string>", line 1, in <module>
NameError: name 'math' is not defined
A:
As far as I understand, you try to get class by its string name. There was a similar question: How to dynamically load a Python class
A:
You can't directly "convert from string to object" (though in a technical sense, strings are objects), but you can use a function that can import the objects for you. Werkzeug's werkzeug.utils module has a function in it named import_string that does just that (source here).
(I'm assuming that the objects you want are to be imported from modules.)
So, if you use a similar import_string function, you can transform the tuple to a dictionary with this:
test_classes = {}
for path in TEST_CLASSES:
obj = import_string(path)
test_classes[obj.__module__.split('.')[-1]] = obj
A:
The straightforward and oftenly not recomended way there is to use "eval".
Simply doing:
obj = eval('common.test.TestClass')
Will give you the object as specified on the string.
Other, more elegant ways, would involve querying each object on the chain for the next attribute - you can avoud eval in this way:
string = 'common.test.TestClass'
# this retrieves the topmost name, supposedly a module, as an object:
obj = globals()[string.split(".")[0]]
# And retrieve each subobject object therein:
for part in string.split(".")[1:]:
obj = getattr(obj, part)
If part of your object path is an yet not-imported submodule, though, this won't work - You'd have to "exec" an import statement to retrieve the module - Exec being a "stronger" form of eval, wich supports statements, while eval is reserved only for expressions.
|
How to transform tuple of string(object locations) to dictionary of objects in python
|
I would like to transform a tuple:
TEST_CLASSES = (
'common.test.TestClass',
)
to
TEST_CLASSES = {
'test': common.test.TestClass,
}
How to make a dictionary is simple but I have a problem with conversion from string to object. Could anybody help me please? thanks!
|
[
"You could use eval, which can be evil if your inputs are not safe:\n>>> import os\n>>> eval('os.path.join')\n<function join at 0x00BBA2B8>\n\nif the common.test.TestClass doesn't exist in the current namespace a NameError will be raised:\n>>> eval('math.isnan')\nTraceback (most recent call last):\n File \"<pyshell#5>\", line 1, in <module>\n eval('math.isnan')\n File \"<string>\", line 1, in <module>\nNameError: name 'math' is not defined\n\n",
"As far as I understand, you try to get class by its string name. There was a similar question: How to dynamically load a Python class\n",
"You can't directly \"convert from string to object\" (though in a technical sense, strings are objects), but you can use a function that can import the objects for you. Werkzeug's werkzeug.utils module has a function in it named import_string that does just that (source here).\n(I'm assuming that the objects you want are to be imported from modules.)\nSo, if you use a similar import_string function, you can transform the tuple to a dictionary with this:\ntest_classes = {}\nfor path in TEST_CLASSES:\n obj = import_string(path)\n test_classes[obj.__module__.split('.')[-1]] = obj\n\n",
"The straightforward and oftenly not recomended way there is to use \"eval\".\nSimply doing:\nobj = eval('common.test.TestClass') \n\nWill give you the object as specified on the string.\nOther, more elegant ways, would involve querying each object on the chain for the next attribute - you can avoud eval in this way:\nstring = 'common.test.TestClass'\n\n# this retrieves the topmost name, supposedly a module, as an object:\nobj = globals()[string.split(\".\")[0]]\n\n# And retrieve each subobject object therein:\nfor part in string.split(\".\")[1:]: \n obj = getattr(obj, part)\n\nIf part of your object path is an yet not-imported submodule, though, this won't work - You'd have to \"exec\" an import statement to retrieve the module - Exec being a \"stronger\" form of eval, wich supports statements, while eval is reserved only for expressions.\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002228750_python.txt
|
Q:
Using unicode in Python
I have csv file having some address data mostly in Finnish language. I need to read that file and getting some geocode information of these address. But It doesn't work for Finnish alphabet and says it cant read those! Can anybody please help me out of this?
import urllib,urllib2,time
addr_file = 'address.csv'
out_file = 'addresses_geocoded.csv'
out_file_failed = 'failed.csv'
sleep_time = 2
root_url = "http://maps.google.com/maps/geo?"
gkey = "asfasdfasdfasdf" # not an actual value
return_codes = {'200':'SUCCESS',
'400':'BAD REQUEST',
'500':'SERVER ERROR',
'601':'MISSING QUERY',
'602':'UNKOWN ADDRESS',
'603':'UNAVAILABLE ADDRESS',
'604':'UNKOWN DIRECTIONS',
'610':'BAD KEY',
'620':'TOO MANY QUERIES'
}
def geocode_for_musiquitous(addr_file,out_fmt='csv'):
#encode our dictionary of url parameters
values = {'q' : addr_file, 'output':out_fmt, 'key':gkey}
data = urllib.urlencode(values)
#set up our request
url = root_url+data
req = urllib2.Request(url)
#make request and read response
response = urllib2.urlopen(req)
geodat = response.read().split(',')
response.close()
# this section is just handle the data returned from google
code = return_codes[geodat[0]]
if code == 'SUCCESS':
code,precision,lat,lng = geodat
return {'code':code,'precision':precision,'lat':lat,'lng':lng}
else:
return {'code':code}
def main():
#open i/o files
outf = open(out_file,'w')
outf_failed = open(out_file_failed,'w')
inf = open(addr_file,'r')
for address in inf:
#get latitude and longitude of address
data = geocode_for_musiquitous(address)
#output results and log to file
if len(data)>1:
print "Latitude and Longitude of "+address+":"
print "\tLatitude:",data['lat']
print "\tLongitude:",data['lng']
outf.write(address.strip()+data['lat']+','+data['lng']+'\n')
outf.flush()
else:
print "Geocoding of '"+addr_file+"' failed with error code "+data['code']
outf_failed.write(address)
outf_failed.flush()
time.sleep(sleep_time)
#clean up
inf.close()
outf.close()
outf_failed.close()
if __name__ == "__main__":
main()
A:
The argument of urllib.url should be UTF-8 encoded beforehand:
addr_file = addr_file.encode("utf-8")
values = {'q' : addr_file, 'output':out_fmt, 'key':gkey}
data = urllib.urlencode(values)
And make sure you open the CSV file with the correct encoding (might be "windows-1252" or "iso-8859-1"):
inf = codecs.open(addr_file, 'r', 'iso-8859-1')
A:
I don't know Python, but I'm pretty sure this is an encoding issue.
Make sure your address file is UTF-8 encoded and that urlencode() function you use can deal with UTF-8 characters (the latter shouldn't be a problem though, as Python can handle UTF-8 natively as far as I know).
A:
Use the codecs module.
codecs.open():
codecs.open(filename, mode[, encoding[, errors[, buffering]]])
Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. The default file mode is 'r' meaning to open the file in read mode.
You can use wrapped file objects to read encoded files into unicode strings.
A:
You need to open file using the correct encoding using the codecs module. The correct encoding for Finnish is probably ISO-8859-1
inf = codecs.open(addr_file,'r', 'iso-8859-1')
If this is not the correct encoding for your file you need to find out what the correct encoding for you file is then check whether a codec for it is available like below:
import codecs
codec = codecs.lookup("iso-8859-1'")
print codec.name
If codecs.lookup() returns a codec object for the encoding you a looking for then it is available and can be used in codecs.open().
|
Using unicode in Python
|
I have csv file having some address data mostly in Finnish language. I need to read that file and getting some geocode information of these address. But It doesn't work for Finnish alphabet and says it cant read those! Can anybody please help me out of this?
import urllib,urllib2,time
addr_file = 'address.csv'
out_file = 'addresses_geocoded.csv'
out_file_failed = 'failed.csv'
sleep_time = 2
root_url = "http://maps.google.com/maps/geo?"
gkey = "asfasdfasdfasdf" # not an actual value
return_codes = {'200':'SUCCESS',
'400':'BAD REQUEST',
'500':'SERVER ERROR',
'601':'MISSING QUERY',
'602':'UNKOWN ADDRESS',
'603':'UNAVAILABLE ADDRESS',
'604':'UNKOWN DIRECTIONS',
'610':'BAD KEY',
'620':'TOO MANY QUERIES'
}
def geocode_for_musiquitous(addr_file,out_fmt='csv'):
#encode our dictionary of url parameters
values = {'q' : addr_file, 'output':out_fmt, 'key':gkey}
data = urllib.urlencode(values)
#set up our request
url = root_url+data
req = urllib2.Request(url)
#make request and read response
response = urllib2.urlopen(req)
geodat = response.read().split(',')
response.close()
# this section is just handle the data returned from google
code = return_codes[geodat[0]]
if code == 'SUCCESS':
code,precision,lat,lng = geodat
return {'code':code,'precision':precision,'lat':lat,'lng':lng}
else:
return {'code':code}
def main():
#open i/o files
outf = open(out_file,'w')
outf_failed = open(out_file_failed,'w')
inf = open(addr_file,'r')
for address in inf:
#get latitude and longitude of address
data = geocode_for_musiquitous(address)
#output results and log to file
if len(data)>1:
print "Latitude and Longitude of "+address+":"
print "\tLatitude:",data['lat']
print "\tLongitude:",data['lng']
outf.write(address.strip()+data['lat']+','+data['lng']+'\n')
outf.flush()
else:
print "Geocoding of '"+addr_file+"' failed with error code "+data['code']
outf_failed.write(address)
outf_failed.flush()
time.sleep(sleep_time)
#clean up
inf.close()
outf.close()
outf_failed.close()
if __name__ == "__main__":
main()
|
[
"The argument of urllib.url should be UTF-8 encoded beforehand:\naddr_file = addr_file.encode(\"utf-8\")\nvalues = {'q' : addr_file, 'output':out_fmt, 'key':gkey}\ndata = urllib.urlencode(values)\n\nAnd make sure you open the CSV file with the correct encoding (might be \"windows-1252\" or \"iso-8859-1\"):\ninf = codecs.open(addr_file, 'r', 'iso-8859-1')\n\n",
"I don't know Python, but I'm pretty sure this is an encoding issue.\nMake sure your address file is UTF-8 encoded and that urlencode() function you use can deal with UTF-8 characters (the latter shouldn't be a problem though, as Python can handle UTF-8 natively as far as I know).\n",
"Use the codecs module.\ncodecs.open():\n\ncodecs.open(filename, mode[, encoding[, errors[, buffering]]])\nOpen an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. The default file mode is 'r' meaning to open the file in read mode.\n\nYou can use wrapped file objects to read encoded files into unicode strings.\n",
"You need to open file using the correct encoding using the codecs module. The correct encoding for Finnish is probably ISO-8859-1\ninf = codecs.open(addr_file,'r', 'iso-8859-1')\n\nIf this is not the correct encoding for your file you need to find out what the correct encoding for you file is then check whether a codec for it is available like below:\nimport codecs\ncodec = codecs.lookup(\"iso-8859-1'\")\nprint codec.name\n\nIf codecs.lookup() returns a codec object for the encoding you a looking for then it is available and can be used in codecs.open().\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0002228953_python_unicode.txt
|
Q:
Python MD5 not matching md5 in terminal
I am getting MD5 of several files using python function:
filehash = hashlib.md5(file)
print "FILE HASH: " + filehash.hexdigest()
though when I go to the terminal and do a
md5 file
the result I'm getting is not the same my python script is outputting (they don't match). Any chance someone knows why?
A:
hashlib.md5() takes the contents of the file not its name.
See http://docs.python.org/library/hashlib.html
You need to open the file, and read its contents before hashing it.
f = open(filename,'rb')
m = hashlib.md5()
while True:
## Don't read the entire file at once...
data = f.read(10240)
if len(data) == 0:
break
m.update(data)
print m.hexdigest()
A:
$ md5 test.py
MD5 (test.py) = 04523172fa400cb2d45652d818103ac3
$ python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib
>>> s = open('test.py','rb').read()
>>> hashlib.md5(s).hexdigest()
'04523172fa400cb2d45652d818103ac3'
A:
Try this
filehash = hashlib.md5(open('filename','rb').read())
print "FILE HASH: " + filehash.hexdigest()
A:
what is file? it should equal to open(filename, 'rb').read(). is it?
|
Python MD5 not matching md5 in terminal
|
I am getting MD5 of several files using python function:
filehash = hashlib.md5(file)
print "FILE HASH: " + filehash.hexdigest()
though when I go to the terminal and do a
md5 file
the result I'm getting is not the same my python script is outputting (they don't match). Any chance someone knows why?
|
[
"hashlib.md5() takes the contents of the file not its name.\nSee http://docs.python.org/library/hashlib.html\nYou need to open the file, and read its contents before hashing it.\nf = open(filename,'rb')\nm = hashlib.md5()\nwhile True:\n ## Don't read the entire file at once...\n data = f.read(10240)\n if len(data) == 0:\n break\n m.update(data)\nprint m.hexdigest()\n\n",
"$ md5 test.py\nMD5 (test.py) = 04523172fa400cb2d45652d818103ac3\n$ python\nPython 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import hashlib\n>>> s = open('test.py','rb').read()\n>>> hashlib.md5(s).hexdigest()\n'04523172fa400cb2d45652d818103ac3'\n\n",
"Try this\nfilehash = hashlib.md5(open('filename','rb').read())\nprint \"FILE HASH: \" + filehash.hexdigest()\n\n",
"what is file? it should equal to open(filename, 'rb').read(). is it?\n"
] |
[
22,
6,
3,
1
] |
[] |
[] |
[
"hash",
"md5",
"python"
] |
stackoverflow_0002229298_hash_md5_python.txt
|
Q:
Why does Pylint give error E0702, raising NoneType, on this raise statement?
Say I have the following code.
def foo():
foobar = None
if foobar is not None:
raise foobar
When I run this code through pylint, I get the following error:
E0702:4:foo: Raising NoneType while only classes, instances or string are allowed
Is this a bug in pylint? Is my pylint too old?
pylint 0.18.0,
astng 0.19.1, common 0.45.0
Python 2.5.1 (r251:54863, Aug 25 2008, 09:23:26)
Note: I know this code doesn't make any sense, it's distilled to its bare bones to expose the issue at hand, normally stuff happens in between line 2 and 3 which could make foobar not be None, and no I can't just raise an exception there, because that happens in another thread that has restrictions on it.
A:
It's a known bug. Pylint doesn't do a lot of flow-control inferencing.
A:
Luckily you can tell pylint that you know better than it does:
def foo():
foobar = None
if foobar is not None:
raise foobar # pylint: disable-msg=E0702
|
Why does Pylint give error E0702, raising NoneType, on this raise statement?
|
Say I have the following code.
def foo():
foobar = None
if foobar is not None:
raise foobar
When I run this code through pylint, I get the following error:
E0702:4:foo: Raising NoneType while only classes, instances or string are allowed
Is this a bug in pylint? Is my pylint too old?
pylint 0.18.0,
astng 0.19.1, common 0.45.0
Python 2.5.1 (r251:54863, Aug 25 2008, 09:23:26)
Note: I know this code doesn't make any sense, it's distilled to its bare bones to expose the issue at hand, normally stuff happens in between line 2 and 3 which could make foobar not be None, and no I can't just raise an exception there, because that happens in another thread that has restrictions on it.
|
[
"It's a known bug. Pylint doesn't do a lot of flow-control inferencing.\n",
"Luckily you can tell pylint that you know better than it does:\ndef foo():\n foobar = None\n if foobar is not None:\n raise foobar # pylint: disable-msg=E0702\n\n"
] |
[
17,
12
] |
[] |
[] |
[
"exception",
"pylint",
"python"
] |
stackoverflow_0002228790_exception_pylint_python.txt
|
Q:
Python Django simple site
I'm trying to create site using Django framework. I looked on tutorial on Django project site but contains much information which I don't need. I have python scripts which provides output and I need to have this output on the web. My question is how simply manage Django to have link which start the script and provides its output on the web or perhaps you provide the link where I can read about this?
Thank you.
A:
"I have python scripts which provides
output and I need to have this output
on the web."
That is not what Django is for. What you want to do can be achieved with something as simple as this:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("magic content goes here")
if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
Observe the self.wfile.write line. Whatever you write there ends up in the browser. If it matters, you can use self.path in the Handler to check which file was requested.
Tested with Python 2.6.4, accessed the server with Chrome browser.
A:
Everyone is right. This is the wrong way to use django. However, if you need a stop-gap measure while you convert your script to the proper idiom:
import sys
from django.http import HttpResponse
def cgi_view(request, my_module):
__import__(my_module)
mod = sys.modules[my_module]
text = mod.main()
resp = HttpResponse(text)
# Then set your headers on resp
return resp
I leave it as an exercise to figure out how to set the headers. Sorry for the laziness, but I gotta go get to work.
P.S. if your script is not factored to wrap all its output producing functions in a main() function, you can use subprocess to get the output instead.
A:
Use mod_wsgi plugin to Apache.
You can do this to see how an existing script might be transformed into a WSGI application. This is a starting point, to show how the WSGI interface works.
import sys
def myWSGIApp( environ, start_response ):
with file( "temp", "w" ) as output:
sys.stdout= output
execfile( "some script.py" )
sys.stdout= __stdout__
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
result= file( "temp", "r" )
return result
Note that you can easily rewrite your scripts to conform to the WSGI
standard, also. This is still not quite the best approach.
If you had this
if __name__ == "__main__":
main()
You simply have to add something like this to each script.
def myWSGIApp( environ, start_response ):
with file( "temp", "w" ) as output:
sys.stdout= output
main()
sys.stdout= __stdout__
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
result= file( "temp", "r" )
return result
Then each script is callable as a WSGI application and can be plugged
into a WSGI-based framework.
The best approach is to rewrite your scripts so they do not use sys.stdout, but write to a file that's passed to them as an argument.
A test version of your server can be this simple.
from wsgiref.simple_server import make_server
httpd = make_server('', 8000, myWSGIApp)
Once you have WSGI applications for your scripts, you can create an smarter
WSGI application that
Parses the URL. Updates the environ with the name of the script to run.
Runs your WSGI application with an appropriate environment.
Look at http://docs.python.org/library/wsgiref.html for information.
You can then configure Apache to use your WSGI server via mod_wsgi.
Look at http://code.google.com/p/modwsgi/ for details.
A:
That's not how Django works. Do the tutorial, you'll save a lot of time and frustration.
A:
I have python scripts which provides output and I need to have this output on the web.
What is Django for? Use either CGI script on python (probably you already have one) or WSGI application (which is a bit harder to deploy)
A:
Django is a frame work. Just use CGI scripts.
|
Python Django simple site
|
I'm trying to create site using Django framework. I looked on tutorial on Django project site but contains much information which I don't need. I have python scripts which provides output and I need to have this output on the web. My question is how simply manage Django to have link which start the script and provides its output on the web or perhaps you provide the link where I can read about this?
Thank you.
|
[
"\n\"I have python scripts which provides\n output and I need to have this output\n on the web.\"\n\nThat is not what Django is for. What you want to do can be achieved with something as simple as this:\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n\n self.wfile.write(\"magic content goes here\")\n\nif __name__==\"__main__\":\n try:\n server = HTTPServer((\"\", 8080), Handler)\n server.serve_forever()\n except KeyboardInterrupt:\n server.socket.close()\n\nObserve the self.wfile.write line. Whatever you write there ends up in the browser. If it matters, you can use self.path in the Handler to check which file was requested.\nTested with Python 2.6.4, accessed the server with Chrome browser.\n",
"Everyone is right. This is the wrong way to use django. However, if you need a stop-gap measure while you convert your script to the proper idiom:\nimport sys\nfrom django.http import HttpResponse\n\ndef cgi_view(request, my_module):\n __import__(my_module)\n mod = sys.modules[my_module]\n text = mod.main()\n\n resp = HttpResponse(text)\n # Then set your headers on resp\n return resp\n\nI leave it as an exercise to figure out how to set the headers. Sorry for the laziness, but I gotta go get to work.\nP.S. if your script is not factored to wrap all its output producing functions in a main() function, you can use subprocess to get the output instead.\n",
"Use mod_wsgi plugin to Apache.\nYou can do this to see how an existing script might be transformed into a WSGI application. This is a starting point, to show how the WSGI interface works.\nimport sys\ndef myWSGIApp( environ, start_response ):\n with file( \"temp\", \"w\" ) as output:\n sys.stdout= output\n execfile( \"some script.py\" )\n sys.stdout= __stdout__\n\n status = '200 OK'\n headers = [('Content-type', 'text/plain')]\n\n start_response(status, headers)\n\n result= file( \"temp\", \"r\" )\n return result\n\nNote that you can easily rewrite your scripts to conform to the WSGI\nstandard, also. This is still not quite the best approach.\nIf you had this\nif __name__ == \"__main__\":\n main()\n\nYou simply have to add something like this to each script.\ndef myWSGIApp( environ, start_response ):\n with file( \"temp\", \"w\" ) as output:\n sys.stdout= output\n main()\n sys.stdout= __stdout__\n\n status = '200 OK'\n headers = [('Content-type', 'text/plain')]\n\n start_response(status, headers)\n\n result= file( \"temp\", \"r\" )\n return result\n\nThen each script is callable as a WSGI application and can be plugged\ninto a WSGI-based framework.\nThe best approach is to rewrite your scripts so they do not use sys.stdout, but write to a file that's passed to them as an argument.\nA test version of your server can be this simple.\nfrom wsgiref.simple_server import make_server\nhttpd = make_server('', 8000, myWSGIApp)\n\nOnce you have WSGI applications for your scripts, you can create an smarter\nWSGI application that\n\nParses the URL. Updates the environ with the name of the script to run.\nRuns your WSGI application with an appropriate environment. \n\nLook at http://docs.python.org/library/wsgiref.html for information.\nYou can then configure Apache to use your WSGI server via mod_wsgi. \nLook at http://code.google.com/p/modwsgi/ for details.\n",
"That's not how Django works. Do the tutorial, you'll save a lot of time and frustration.\n",
"\nI have python scripts which provides output and I need to have this output on the web.\n\nWhat is Django for? Use either CGI script on python (probably you already have one) or WSGI application (which is a bit harder to deploy)\n",
"Django is a frame work. Just use CGI scripts.\n"
] |
[
4,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002228966_django_python.txt
|
Q:
Giving 'hints' problem
I have a simple word jumble game. I made the jumble already, but now I want to add a 'hint' system. I don't know how to have 1 item from tuples show up. I have 2 tuples, and I want to pull from the 2nd tuple based on the what the first tuple is. I have a WORD=("x", "y", "z") and HINT=("x", "y", "z"). When the user enters "hint", I want the program to return the corresponding value from HINT. I tried:
for h in HINT:
if guess=="hint":
print h
Obviously, this doesn't work, and just prints all of the HINT values.
If I had:
hints=dict(zip(WORDS, HINT))
if guess=="hint":
print "Here's a hint:", hints[correct]
while (guess !=correct) and (guess != ""):
print "Sorry, that's not the answer."
guess=raw_input("Your guess: ")
guess=guess.lower()
if guess==correct:
print "That's it! You guessed it!\n"
print "Thanks for playing."
would there be any way for me to make it NOT print "Sorry, that's not it."? (also, 'correct' here is the word)
A:
Create a dictionary:
hints = dict(zip(WORD, HINT))
and then:
if guess=='hint':
print hints[current_word]
Simple if is not enough?
if guess != 'hint':
print "Sorry, that's not the answer."
|
Giving 'hints' problem
|
I have a simple word jumble game. I made the jumble already, but now I want to add a 'hint' system. I don't know how to have 1 item from tuples show up. I have 2 tuples, and I want to pull from the 2nd tuple based on the what the first tuple is. I have a WORD=("x", "y", "z") and HINT=("x", "y", "z"). When the user enters "hint", I want the program to return the corresponding value from HINT. I tried:
for h in HINT:
if guess=="hint":
print h
Obviously, this doesn't work, and just prints all of the HINT values.
If I had:
hints=dict(zip(WORDS, HINT))
if guess=="hint":
print "Here's a hint:", hints[correct]
while (guess !=correct) and (guess != ""):
print "Sorry, that's not the answer."
guess=raw_input("Your guess: ")
guess=guess.lower()
if guess==correct:
print "That's it! You guessed it!\n"
print "Thanks for playing."
would there be any way for me to make it NOT print "Sorry, that's not it."? (also, 'correct' here is the word)
|
[
"Create a dictionary:\n hints = dict(zip(WORD, HINT))\n\nand then:\n if guess=='hint':\n print hints[current_word]\n\nSimple if is not enough?\nif guess != 'hint':\n print \"Sorry, that's not the answer.\"\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"tuples"
] |
stackoverflow_0002229618_python_tuples.txt
|
Q:
What are features considerd as advanced python?
I do basic python programming and now I want to get deep into language features. I have collected/considered the following to be advanced python capabilities and learning them now.
Decorator
Iterator
Generator
Meta Class
Anything else to be added/considered to the above list?
A:
First, this thread should be community wiki.
Second, iterators and generators are pretty basic Python IMHO. I agree with you on decorators and metaclasses. But I'm not a very good programmer, so I probably find this more difficult to wrap my brain around than others.
Third, I would add threading/multiprocessing to the list. That's really tricky :)
A:
There are some useful core concepts that can be added to your list, and that I would not necessarily teach in an introductory Python class (from the most common to the more specific):
the various protocols (sequence, iterator, context,…)
properties
packages
Some points related to important standard modules:
Making your classes compatible with the standard copy and pickle modules.
A:
The first 3 are intermediate Python, not advanced. For advanced add the stuff in the Importing Modules and Python Language Services sections of the library reference.
A:
I think you'll find that there isn't a good answer to your question. What's great about Python is that all of its features are fairly easy to understand. But there's enough stuff in the language and the library that you never get around to learning it all. So it really boils down to which you've had occasion to use, and which you've only heard about.
If you haven't used decorators or generators, they sound advanced. But once you actually have to use them in a real-world situation, you'll realize that they're really quite simple, and wonder how you managed to live without them before.
|
What are features considerd as advanced python?
|
I do basic python programming and now I want to get deep into language features. I have collected/considered the following to be advanced python capabilities and learning them now.
Decorator
Iterator
Generator
Meta Class
Anything else to be added/considered to the above list?
|
[
"First, this thread should be community wiki.\nSecond, iterators and generators are pretty basic Python IMHO. I agree with you on decorators and metaclasses. But I'm not a very good programmer, so I probably find this more difficult to wrap my brain around than others.\nThird, I would add threading/multiprocessing to the list. That's really tricky :)\n",
"There are some useful core concepts that can be added to your list, and that I would not necessarily teach in an introductory Python class (from the most common to the more specific):\n\nthe various protocols (sequence, iterator, context,…)\nproperties\npackages\n\nSome points related to important standard modules:\n\nMaking your classes compatible with the standard copy and pickle modules.\n\n",
"The first 3 are intermediate Python, not advanced. For advanced add the stuff in the Importing Modules and Python Language Services sections of the library reference.\n",
"I think you'll find that there isn't a good answer to your question. What's great about Python is that all of its features are fairly easy to understand. But there's enough stuff in the language and the library that you never get around to learning it all. So it really boils down to which you've had occasion to use, and which you've only heard about.\nIf you haven't used decorators or generators, they sound advanced. But once you actually have to use them in a real-world situation, you'll realize that they're really quite simple, and wonder how you managed to live without them before.\n"
] |
[
2,
2,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002227537_python.txt
|
Q:
Django: Setting one page as the main page
I'm a newbie at Django and I want to do something that I'm not sure how to do.
I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.)
So I have a bunch of SimplePages for my site, and I want one of them to be the main page. (a.k.a. the index page.) I know how to make it available on the url /. But I also want it to receive slightly different processing. (It contains different page elements than the other pages.)
What would be a good way to mark a page as the main page? I considered adding a boolean field is_main_page to the SimplePage model, but how could I assure that only one page could be marked as the main page?
A:
Create MAIN_PAGE setting inside settings.py with primary key. Then create view main_page nad retrieve the main_page object from the database using the setting.
EDIT:
You can also do it like this: add a model, which will reference a SimplePage and point to the main page. In main page view, you will retrieve the wanted SimplePage and it can be easily changed by anyone in django admin.
A:
Easiest way to do this would be to create the boolean value, as you suggested and use the pre_save signal to remove the boolean value from everything else in the database.
from django.db.models import signals
def simple_page_pre_save(sender, instance, **kwargs):
if instance.is_main_page == True:
SimplePage.objects.update(is_main_page=False)
signals.pre_save.connect(simple_page_pre_save, sender=SimplePage)
This way whenever you save a SimplePage, it will see if is_main_page is true, and if it is set is_main_page for every other page to False. There is still some work to be done to ensure that there is always one is_main_page, but that is more up to you.
|
Django: Setting one page as the main page
|
I'm a newbie at Django and I want to do something that I'm not sure how to do.
I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.)
So I have a bunch of SimplePages for my site, and I want one of them to be the main page. (a.k.a. the index page.) I know how to make it available on the url /. But I also want it to receive slightly different processing. (It contains different page elements than the other pages.)
What would be a good way to mark a page as the main page? I considered adding a boolean field is_main_page to the SimplePage model, but how could I assure that only one page could be marked as the main page?
|
[
"Create MAIN_PAGE setting inside settings.py with primary key. Then create view main_page nad retrieve the main_page object from the database using the setting.\nEDIT:\nYou can also do it like this: add a model, which will reference a SimplePage and point to the main page. In main page view, you will retrieve the wanted SimplePage and it can be easily changed by anyone in django admin.\n",
"Easiest way to do this would be to create the boolean value, as you suggested and use the pre_save signal to remove the boolean value from everything else in the database.\nfrom django.db.models import signals\ndef simple_page_pre_save(sender, instance, **kwargs):\n if instance.is_main_page == True:\n SimplePage.objects.update(is_main_page=False)\n\nsignals.pre_save.connect(simple_page_pre_save, sender=SimplePage)\n\nThis way whenever you save a SimplePage, it will see if is_main_page is true, and if it is set is_main_page for every other page to False. There is still some work to be done to ensure that there is always one is_main_page, but that is more up to you.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002229640_django_python.txt
|
Q:
Python dictionary instead of switch/case
I've recently learned that python doesn't have the switch/case statement. I've been reading about using dictionaries in its stead, like this for example:
values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
valueN: do_some_stuffN,
}
values.get(var, do_default_stuff)()
What I can't figure out is how to apply this to do a range test. So instead of doing some stuff if value1=4 say, doing some stuff if value1<4. So something like this (which I know doesn't work):
values = {
if value1 <val: do_some_stuff1,
if value2 >val: do_some_stuff2,
}
values.get(var, do_default_stuff)()
I've tried doing this with if/elif/else statements. It works fine but it seems to go considerably slower compared to the situation where I don't need the if statements at all (which is maybe something obvious an inevitable). So here's my code with the if/elif/else statement:
if sep_ang(val1,val2,X,Y)>=ROI :
main.removeChild(source)
elif sep_ang(val1,val2,X,Y)<=5.0:
integral=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
index=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
print name,val1,val2,sep_ang(val1,val2,X,Y),integral,index
print >> reg,'fk5;point(',val1,val2,')# point=cross text={',name,'}'
else:
spectrum[0].getElementsByTagName("parameter")[0].setAttribute("free","0") #Integral
spectrum[0].getElementsByTagName("parameter")[1].setAttribute("free","0") #Index
integral=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
index=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
print name,val1,val2,sep_ang(val1,val2,X,Y),integral,index
print >> reg,'fk5;point(',val1,val2,')# point=cross text={',name,'}'
Which takes close to 5 min for checking about 1500 values of the var sep_ang. Where as if I don't want to use setAttribute() to change values in my xml file based on the value of sep_ang, I use this simple if else:
if sep_ang(val1,val2,X,Y)>=ROI :
main.removeChild(source)
else:
print name,val1,val2,ang_sep(val1,val2,X,Y);print >> reg,'fk5;point(',val1,val2,')# point
Which only takes ~30sec. Again I know it's likely that adding that elif statement and changing values of that attribute inevitably increases the execution time of my code by a great deal, I was just curious if there's a way around it.
Edit:
Is the benefit of using bisect as opposed to an if/elif statement in my situation that it can check values over some range quicker than using a bunch of elif statements?
It seems like I'll still need to use elif statements. Like this for example:
range=[10,100]
options='abc'
def func(val)
return options[bisect(range, val)]
if func(val)=a:
do stuff
elif func(val)=b:
do other stuff
else:
do other other stuff
So then my elif statement are only checking against a single value.
Thanks much for the help, it's greatly appreciated.
A:
A dictionary is the wrong structure for this. The bisect examples show an example of this sort of range test.
A:
Whilst the dictionary approach works well for single values, if you want ranges, if ... else if ... else if is probably the simplest approach.
If you're looking for a single value this a good match to a dictionary - since this is what dictionaries are for - but if you're looking for a range it doesn't work. You could do it with a dict using something like:
values = {
lambda x: x < 4: foo,
lambda x: x > 4: bar
}
and then loop through all the key-value pairs in the dictionary, passing your value key and running the value as a function if the key function returns true.
However, this wouldn't give you any benefit over a number of if statements and would be harder to maintain and debug. So don't do it, and just use if instead.
A:
In that case you would use an if/then/else. You cannot do this with a switch, either.
The idea of a switch statement is that you have a value V that you test for identity against N possible outcomes. You can do this with an if-construct - however that would take O(N) runtime on average. The switch gives you constant O(1) every time.
This is obviously not possible for ranges (since they are not easily hashable) and thus you use if-constructs for these cases.
Example
if value1 <val: do_some_stuff1()
elif value2 >val: do_some_stuff2()
Note that this is actually smaller than trying to use a dictionary.
A:
dict is not for doing this (nor is switch!).
A couple posters have suggested a dict with containment functions, but this is not the solution you want at all. It is O(n) (like an if statement), it doesn't really work (because you could have overlapping conditions), is unpredictable (because you do not know what order you will do the loop), and is much less clear than the equivalent if statement. The if statement is probably the way you want to go if you have a short, static-length list of conditions to apply.
If you have tons of conditions or if they could change as a result of your program, you want a different data structure. You could implement a binary tree or keep a sorted list and use the bisect module to find a value associated with the given range.
A:
I don't know of any practicable solution. If you want to go with the guess what it does approach though you could do something like this:
obsure_switch = {
lambda x: 1<x<6 : some_function,
...
}
[action() for condition,action in obscure_switch.iteritems() if condition(var)]
A:
Finally figured out what to do!
So instead of using a bunch of elif statements I did this:
range=[10,100]
options='abc'
def func(val)
choose=str(options[bisect(range,val)])
exec choose+"()"
def a():
do_stuff
def b():
do_other_stuff
def c():
do_other_other stuff
Not only does it work but it goes almost as fast as my original 4 line code where I'm not changing any values of things!
|
Python dictionary instead of switch/case
|
I've recently learned that python doesn't have the switch/case statement. I've been reading about using dictionaries in its stead, like this for example:
values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
valueN: do_some_stuffN,
}
values.get(var, do_default_stuff)()
What I can't figure out is how to apply this to do a range test. So instead of doing some stuff if value1=4 say, doing some stuff if value1<4. So something like this (which I know doesn't work):
values = {
if value1 <val: do_some_stuff1,
if value2 >val: do_some_stuff2,
}
values.get(var, do_default_stuff)()
I've tried doing this with if/elif/else statements. It works fine but it seems to go considerably slower compared to the situation where I don't need the if statements at all (which is maybe something obvious an inevitable). So here's my code with the if/elif/else statement:
if sep_ang(val1,val2,X,Y)>=ROI :
main.removeChild(source)
elif sep_ang(val1,val2,X,Y)<=5.0:
integral=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
index=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
print name,val1,val2,sep_ang(val1,val2,X,Y),integral,index
print >> reg,'fk5;point(',val1,val2,')# point=cross text={',name,'}'
else:
spectrum[0].getElementsByTagName("parameter")[0].setAttribute("free","0") #Integral
spectrum[0].getElementsByTagName("parameter")[1].setAttribute("free","0") #Index
integral=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
index=float(spectrum[0].getElementsByTagName("parameter")[0].getAttribute("free"))
print name,val1,val2,sep_ang(val1,val2,X,Y),integral,index
print >> reg,'fk5;point(',val1,val2,')# point=cross text={',name,'}'
Which takes close to 5 min for checking about 1500 values of the var sep_ang. Where as if I don't want to use setAttribute() to change values in my xml file based on the value of sep_ang, I use this simple if else:
if sep_ang(val1,val2,X,Y)>=ROI :
main.removeChild(source)
else:
print name,val1,val2,ang_sep(val1,val2,X,Y);print >> reg,'fk5;point(',val1,val2,')# point
Which only takes ~30sec. Again I know it's likely that adding that elif statement and changing values of that attribute inevitably increases the execution time of my code by a great deal, I was just curious if there's a way around it.
Edit:
Is the benefit of using bisect as opposed to an if/elif statement in my situation that it can check values over some range quicker than using a bunch of elif statements?
It seems like I'll still need to use elif statements. Like this for example:
range=[10,100]
options='abc'
def func(val)
return options[bisect(range, val)]
if func(val)=a:
do stuff
elif func(val)=b:
do other stuff
else:
do other other stuff
So then my elif statement are only checking against a single value.
Thanks much for the help, it's greatly appreciated.
|
[
"A dictionary is the wrong structure for this. The bisect examples show an example of this sort of range test.\n",
"Whilst the dictionary approach works well for single values, if you want ranges, if ... else if ... else if is probably the simplest approach.\nIf you're looking for a single value this a good match to a dictionary - since this is what dictionaries are for - but if you're looking for a range it doesn't work. You could do it with a dict using something like:\nvalues = {\n lambda x: x < 4: foo,\n lambda x: x > 4: bar\n}\n\nand then loop through all the key-value pairs in the dictionary, passing your value key and running the value as a function if the key function returns true.\nHowever, this wouldn't give you any benefit over a number of if statements and would be harder to maintain and debug. So don't do it, and just use if instead.\n",
"In that case you would use an if/then/else. You cannot do this with a switch, either. \nThe idea of a switch statement is that you have a value V that you test for identity against N possible outcomes. You can do this with an if-construct - however that would take O(N) runtime on average. The switch gives you constant O(1) every time. \nThis is obviously not possible for ranges (since they are not easily hashable) and thus you use if-constructs for these cases.\nExample\nif value1 <val: do_some_stuff1()\nelif value2 >val: do_some_stuff2()\n\nNote that this is actually smaller than trying to use a dictionary.\n",
"dict is not for doing this (nor is switch!). \nA couple posters have suggested a dict with containment functions, but this is not the solution you want at all. It is O(n) (like an if statement), it doesn't really work (because you could have overlapping conditions), is unpredictable (because you do not know what order you will do the loop), and is much less clear than the equivalent if statement. The if statement is probably the way you want to go if you have a short, static-length list of conditions to apply.\nIf you have tons of conditions or if they could change as a result of your program, you want a different data structure. You could implement a binary tree or keep a sorted list and use the bisect module to find a value associated with the given range.\n",
"I don't know of any practicable solution. If you want to go with the guess what it does approach though you could do something like this:\nobsure_switch = {\n lambda x: 1<x<6 : some_function,\n ...\n}\n\n[action() for condition,action in obscure_switch.iteritems() if condition(var)]\n\n",
"Finally figured out what to do!\nSo instead of using a bunch of elif statements I did this:\nrange=[10,100]\noptions='abc' \ndef func(val)\n choose=str(options[bisect(range,val)])\n exec choose+\"()\"\ndef a():\n do_stuff\ndef b():\n do_other_stuff\ndef c():\n do_other_other stuff\n\nNot only does it work but it goes almost as fast as my original 4 line code where I'm not changing any values of things!\n"
] |
[
11,
5,
3,
3,
0,
-2
] |
[] |
[] |
[
"dictionary",
"python",
"switch_statement"
] |
stackoverflow_0002222859_dictionary_python_switch_statement.txt
|
Q:
Dynamic form requirements in Django
I am about to start a large Django project at work. And the key features are form handling. There is going to be a lot of forms that the users of the app is going to use. And one requirement is that it should be possible to edit the forms in the admin interface of the application.
That is, it is not a requirement to add/delete form fields. But it should be possible to edit form field attributes. E.g change which fields which is required and such.
Anybody have any good solutions on how to do this. I'm thinking that I might have to subclass the fields I want to be dynamic and do something there. I guess that all the models fields have to have "blank=True/null=True" and some how add some meta information in a separate model(?) about the model which declares which fields are required. And then use that information when forms is displayed and validated.
Before I start off doing this I would really like some input in how to design such a solution, anybody got ideas on how it should be done?
After more research, I've learned that you could do a lot with factory functions that would return the form with the given attributes set. So it looks like the problem is not that hard do solve.
I would make a function that returns a form with the right attributes/fields set. But the part that I haven't found a good solution for is how to manage this in the admin interface. I am thinking that I would make a db.Model that stores information about another models fields. Where I can set which is required and such.
And then in the function that returns the form, go trough that model and return a form with the right attributes. But how to make that model (which should mirror another model's fields) in a good way?
A:
You should use certain models for this. For every form that might be customised this way, a new database entry must be created. I guess, it should look like this:
class FormSettings(Model):
form = CharField(..)
class FormAttrib(Model):
form_settings = ForeignKey(FormSettings)
field = CharField(..)
attrib_name=CharField(..)
attrib_value=CharField(..)
In FormSettings.form you should store some address of form, like say . and when form is built (in init), it should look for an entry in db and use attribs, that were described for it.
You can make it create db entries easily, if you use own metaclass for your forms and make it register in the database (create proper FormSettings entry), when a class is created. It will be done once when the process is started, which shouldn't be that bad.
I hope it helps a little. If you have further questions, I'll be happy to help :-) I like those non standard appliances of django :-) This is where all the fun begins :-)
EDIT:
OK, let's say, that you want to you have app food and form FavouriteFoodForm with food_name field. You store in the database in formsettings table as food.FavouriteFoodForm and add one attribute setting: field='food_name', attrib_name='required', attribute_value='True' (it's not perfect, but still it's not that bad').
No in FavouriteFoddForm you look for the settings in database, so you do:
settings = FormSettings.objects.get(form=app_name + self.__class__.name)
and you iterate over settings
for setting in settings.formattrib_set():
and here you simple call exec and set proper attribute:
exec("getattr(self, settings.field)[attrib_name] = %s" % attrib_value)
This should set attributes to required=True.
A:
This isn't an exact answer to your problem, but I did something similar which I thought might be of use to you. I created an entirely customizable form, so that the form can be customized by end users.
I ended up with 2 models, a BuiltForm and a BuiltFormField:
class BuiltForm(models.Model):
name = models.CharField(max_length=32)
def form(self, data=None, initial=None):
form = BuiltFormGenericForm(data, initial=initial)
form.addBuiltFormFields(BuiltFormField.objects.filter(builtform=self, disabled=0))
return form
class BuiltFormField(models.Model):
builtform = models.ForeignKey(BuiltForm)
type = models.CharField(max_length=32, choices=ALL_FIELD_TYPES)
label = models.CharField(max_length=32)
fieldname = models.CharField(max_length=32)
helptext = models.CharField(max_length=256, blank=True)
required = models.BooleanField(default=False)
sort_order = models.IntegerField(default=0)
disabled = models.BooleanField(default=False)
options = models.TextField(blank=True)
def field(self):
field = ALL_FIELD_MAPS.get(self.type)
## Build out the field, supplying choices, `required`, etc.
There are a couple of things that are abnormal. ALL_FIELD_TYPES is a map of the types of fields allowed in the form. This is used in conjuction with a dict() to discern what class (CharField, EmailField, ChoiceField, etc) should be used for this field. options is also a pickled list of options for later use in a ChoiceField. This allowed me to create an arbitrary list of options without a separate call to the database.
The other major piece to this is a custom Form class which allows itself to be populated with the fields from a BuiltForm. Mine looks like this:
class BuiltFormGenericForm(forms.Form):
built_form_fields = {}
builtform = None
def addBuiltFormFields(self, fields):
for field in fields:
self.fields[field.label] = field.field()
self.built_form_fields[field.pk] = field
def is_valid(self):
# Do validation here. My code for this is pretty big because of custom fields
# and calculations that I have to squeeze in.
The BuiltFormField objects aren't designed to be created through the admin interface, but rather through a custom one with a ton of JavaScript to make it user-friendly, but you can certainly expose parts of the BuiltFormField model in the admin interface for them to be updated.
Hope this helps you work out a model for your forms.
|
Dynamic form requirements in Django
|
I am about to start a large Django project at work. And the key features are form handling. There is going to be a lot of forms that the users of the app is going to use. And one requirement is that it should be possible to edit the forms in the admin interface of the application.
That is, it is not a requirement to add/delete form fields. But it should be possible to edit form field attributes. E.g change which fields which is required and such.
Anybody have any good solutions on how to do this. I'm thinking that I might have to subclass the fields I want to be dynamic and do something there. I guess that all the models fields have to have "blank=True/null=True" and some how add some meta information in a separate model(?) about the model which declares which fields are required. And then use that information when forms is displayed and validated.
Before I start off doing this I would really like some input in how to design such a solution, anybody got ideas on how it should be done?
After more research, I've learned that you could do a lot with factory functions that would return the form with the given attributes set. So it looks like the problem is not that hard do solve.
I would make a function that returns a form with the right attributes/fields set. But the part that I haven't found a good solution for is how to manage this in the admin interface. I am thinking that I would make a db.Model that stores information about another models fields. Where I can set which is required and such.
And then in the function that returns the form, go trough that model and return a form with the right attributes. But how to make that model (which should mirror another model's fields) in a good way?
|
[
"You should use certain models for this. For every form that might be customised this way, a new database entry must be created. I guess, it should look like this:\nclass FormSettings(Model):\n form = CharField(..)\n\nclass FormAttrib(Model):\n form_settings = ForeignKey(FormSettings)\n field = CharField(..)\n attrib_name=CharField(..)\n attrib_value=CharField(..)\n\nIn FormSettings.form you should store some address of form, like say . and when form is built (in init), it should look for an entry in db and use attribs, that were described for it.\nYou can make it create db entries easily, if you use own metaclass for your forms and make it register in the database (create proper FormSettings entry), when a class is created. It will be done once when the process is started, which shouldn't be that bad.\nI hope it helps a little. If you have further questions, I'll be happy to help :-) I like those non standard appliances of django :-) This is where all the fun begins :-)\nEDIT:\nOK, let's say, that you want to you have app food and form FavouriteFoodForm with food_name field. You store in the database in formsettings table as food.FavouriteFoodForm and add one attribute setting: field='food_name', attrib_name='required', attribute_value='True' (it's not perfect, but still it's not that bad').\nNo in FavouriteFoddForm you look for the settings in database, so you do:\nsettings = FormSettings.objects.get(form=app_name + self.__class__.name)\n\nand you iterate over settings\nfor setting in settings.formattrib_set():\n\nand here you simple call exec and set proper attribute:\nexec(\"getattr(self, settings.field)[attrib_name] = %s\" % attrib_value)\n\nThis should set attributes to required=True.\n",
"This isn't an exact answer to your problem, but I did something similar which I thought might be of use to you. I created an entirely customizable form, so that the form can be customized by end users.\nI ended up with 2 models, a BuiltForm and a BuiltFormField:\nclass BuiltForm(models.Model): \n name = models.CharField(max_length=32) \n def form(self, data=None, initial=None):\n form = BuiltFormGenericForm(data, initial=initial)\n form.addBuiltFormFields(BuiltFormField.objects.filter(builtform=self, disabled=0))\n return form \n\nclass BuiltFormField(models.Model):\n builtform = models.ForeignKey(BuiltForm)\n type = models.CharField(max_length=32, choices=ALL_FIELD_TYPES)\n label = models.CharField(max_length=32)\n fieldname = models.CharField(max_length=32)\n helptext = models.CharField(max_length=256, blank=True)\n required = models.BooleanField(default=False)\n sort_order = models.IntegerField(default=0)\n disabled = models.BooleanField(default=False)\n options = models.TextField(blank=True)\n def field(self):\n field = ALL_FIELD_MAPS.get(self.type)\n ## Build out the field, supplying choices, `required`, etc.\n\nThere are a couple of things that are abnormal. ALL_FIELD_TYPES is a map of the types of fields allowed in the form. This is used in conjuction with a dict() to discern what class (CharField, EmailField, ChoiceField, etc) should be used for this field. options is also a pickled list of options for later use in a ChoiceField. This allowed me to create an arbitrary list of options without a separate call to the database.\nThe other major piece to this is a custom Form class which allows itself to be populated with the fields from a BuiltForm. Mine looks like this:\nclass BuiltFormGenericForm(forms.Form):\n built_form_fields = {}\n builtform = None\n def addBuiltFormFields(self, fields):\n for field in fields:\n self.fields[field.label] = field.field()\n self.built_form_fields[field.pk] = field\n def is_valid(self):\n # Do validation here. My code for this is pretty big because of custom fields\n # and calculations that I have to squeeze in.\n\nThe BuiltFormField objects aren't designed to be created through the admin interface, but rather through a custom one with a ton of JavaScript to make it user-friendly, but you can certainly expose parts of the BuiltFormField model in the admin interface for them to be updated. \nHope this helps you work out a model for your forms.\n"
] |
[
2,
2
] |
[] |
[] |
[
"django",
"forms",
"python"
] |
stackoverflow_0002229427_django_forms_python.txt
|
Q:
How to get the system library path on Unix (Linux, FreeBSD)
I need a more-or-less portable programmatic way for querying the dynamic library path list. For Linux, I can concatenate the $LD_LIBRARY_PATH and the contents of /etc/ld.so.conf (processing the include directives as needed and possibly filtering by architecture), but that doesn't work e.g. on FreeBSD.
Ultimately, I need a Python function for doing that. It can call gcc or other external commands if needed.
A:
For both Linux and FreeBSD you can try working through the output of ldconfig(8). The options for listing the libraries are different though (-p on Linux, -r on FreeBSD.) Hope this helps.
Edit:
Solaris is different - see man crle.
Mac OSX is different yet again - see man dyld.
|
How to get the system library path on Unix (Linux, FreeBSD)
|
I need a more-or-less portable programmatic way for querying the dynamic library path list. For Linux, I can concatenate the $LD_LIBRARY_PATH and the contents of /etc/ld.so.conf (processing the include directives as needed and possibly filtering by architecture), but that doesn't work e.g. on FreeBSD.
Ultimately, I need a Python function for doing that. It can call gcc or other external commands if needed.
|
[
"For both Linux and FreeBSD you can try working through the output of ldconfig(8). The options for listing the libraries are different though (-p on Linux, -r on FreeBSD.) Hope this helps.\nEdit:\nSolaris is different - see man crle.\nMac OSX is different yet again - see man dyld.\n"
] |
[
6
] |
[] |
[] |
[
"freebsd",
"library_path",
"linux",
"python",
"unix"
] |
stackoverflow_0002230467_freebsd_library_path_linux_python_unix.txt
|
Q:
Django urlsafe base64 decoding with decryption
I'm writing my own captcha system for user registration. So I need to create a suitable URL for receiving generated captcha pictures. Generation looks like this:
_cipher = cipher.new(settings.CAPTCHA_SECRET_KEY, cipher.MODE_ECB)
_encrypt_block = lambda block: _cipher.encrypt(block + ' ' * (_cipher.block_size - len(block) % _cipher.block_size))
#...
a = (self.rightnum, self.animal_type[1])
serialized = pickle.dumps(a)
encrypted = _encrypt_block(serialized)
safe_url = urlsafe_b64encode(encrypted)
But then I'm trying to receive this key via GET request in the view function, it fails on urlsafe_b64decode() with "character mapping must return integer, None or unicode" error:
def captcha(request):
try:
key = request.REQUEST['key']
decoded = urlsafe_b64decode(key)
decrypted = _decrypt_block(decoded)
deserialized = pickle.loads(decrypted)
return HttpResponse(deserialized)
except KeyError:
return HttpResponseBadRequest()
I found that on the output of urlsafe_b64encode there is an str, but GET request returns a unicode object (nevertheless it's a right string). Str() didn't help (it returns decode error deep inside django), and if I use key.repr it works, but decryptor doesn't work with an error "Input strings must be a multiple of 16 in length".
Inside a test file all this construction works perfectly, I can't understand, what's wrong?
A:
The problem is that b64decode quite explicitly can only take bytes (a string), not unicode.
>>> import base64
>>> test = "Hi, I'm a string"
>>> enc = base64.urlsafe_b64encode(test)
>>> enc
'SGksIEknbSBhIHN0cmluZw=='
>>> uenc = unicode(enc)
>>> base64.urlsafe_b64decode(enc)
"Hi, I'm a string"
>>> base64.urlsafe_b64decode(uenc)
Traceback (most recent call last):
...
TypeError: character mapping must return integer, None or unicode
Since you know that your data only contains ASCII data (that's what base64encode will return), it should be safe to encode your unicode code points as ASCII or UTF-8 bytes, those bytes will be equivalent to the ASCII you expected.
>>> base64.urlsafe_b64decode(uenc.encode("ascii"))
"Hi, I'm a string"
A:
I solved the problem!
deserialized = pickle.loads(captcha_decrypt(urlsafe_b64decode(key.encode('ascii'))))
return HttpResponse(str(deserialized))
But still I don't understand, why it didn't work first time.
|
Django urlsafe base64 decoding with decryption
|
I'm writing my own captcha system for user registration. So I need to create a suitable URL for receiving generated captcha pictures. Generation looks like this:
_cipher = cipher.new(settings.CAPTCHA_SECRET_KEY, cipher.MODE_ECB)
_encrypt_block = lambda block: _cipher.encrypt(block + ' ' * (_cipher.block_size - len(block) % _cipher.block_size))
#...
a = (self.rightnum, self.animal_type[1])
serialized = pickle.dumps(a)
encrypted = _encrypt_block(serialized)
safe_url = urlsafe_b64encode(encrypted)
But then I'm trying to receive this key via GET request in the view function, it fails on urlsafe_b64decode() with "character mapping must return integer, None or unicode" error:
def captcha(request):
try:
key = request.REQUEST['key']
decoded = urlsafe_b64decode(key)
decrypted = _decrypt_block(decoded)
deserialized = pickle.loads(decrypted)
return HttpResponse(deserialized)
except KeyError:
return HttpResponseBadRequest()
I found that on the output of urlsafe_b64encode there is an str, but GET request returns a unicode object (nevertheless it's a right string). Str() didn't help (it returns decode error deep inside django), and if I use key.repr it works, but decryptor doesn't work with an error "Input strings must be a multiple of 16 in length".
Inside a test file all this construction works perfectly, I can't understand, what's wrong?
|
[
"The problem is that b64decode quite explicitly can only take bytes (a string), not unicode.\n>>> import base64\n>>> test = \"Hi, I'm a string\"\n>>> enc = base64.urlsafe_b64encode(test)\n>>> enc\n'SGksIEknbSBhIHN0cmluZw=='\n>>> uenc = unicode(enc)\n>>> base64.urlsafe_b64decode(enc)\n\"Hi, I'm a string\"\n>>> base64.urlsafe_b64decode(uenc)\nTraceback (most recent call last):\n...\nTypeError: character mapping must return integer, None or unicode\n\nSince you know that your data only contains ASCII data (that's what base64encode will return), it should be safe to encode your unicode code points as ASCII or UTF-8 bytes, those bytes will be equivalent to the ASCII you expected.\n>>> base64.urlsafe_b64decode(uenc.encode(\"ascii\"))\n\"Hi, I'm a string\"\n\n",
"I solved the problem! \ndeserialized = pickle.loads(captcha_decrypt(urlsafe_b64decode(key.encode('ascii'))))\nreturn HttpResponse(str(deserialized))\n\nBut still I don't understand, why it didn't work first time.\n"
] |
[
41,
3
] |
[] |
[] |
[
"base64",
"django",
"encoding",
"encryption",
"python"
] |
stackoverflow_0002229827_base64_django_encoding_encryption_python.txt
|
Q:
how to get specific nodes in xml file with python
im searching for a way to get a specific tags .. from a very big xml document
with python dom built in module
for example :
<AssetType longname="characters" shortname="chr" shortnames="chrs">
<type>
pub
</type>
<type>
geo
</type>
<type>
rig
</type>
</AssetType>
<AssetType longname="camera" shortname="cam" shortnames="cams">
<type>
cam1
</type>
<type>
cam2
</type>
<type>
cam4
</type>
</AssetType>
i want to retrieve the value of children of AssetType node who got attribute (longname= "characters" )
to have the result of 'pub','geo','rig'
please put in mind that i have more than 1000 < AssetType> nodes
thanx in advance
A:
If you don't mind loading the whole document into memory:
from lxml import etree
data = etree.parse(fname)
result = [node.text.strip()
for node in data.xpath("//AssetType[@longname='characters']/type")]
You may need to remove the spaces at the beginning of your tags to make this work.
A:
Assuming your document is called assets.xml and has the following structure:
<assets>
<AssetType>
...
</AssetType>
<AssetType>
...
</AssetType>
</assets>
Then you can do the following:
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
root = tree.parse("assets.xml")
for assetType in root.findall("//AssetType[@longname='characters']"):
for type in assetType.getchildren():
print type.text
A:
You could use the pulldom API to handle parsing a large file, without loading it all into memory at once. This provides a more convenient interface than using SAX with only a slight loss of performance.
It basically lets you stream the xml file until you find the bit you are interested in, then start using regular DOM operations after that.
from xml.dom import pulldom
# http://mail.python.org/pipermail/xml-sig/2005-March/011022.html
def getInnerText(oNode):
rc = ""
nodelist = oNode.childNodes
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
elif node.nodeType==node.ELEMENT_NODE:
rc = rc + getInnerText(node) # recursive !!!
elif node.nodeType==node.CDATA_SECTION_NODE:
rc = rc + node.data
else:
# node.nodeType: PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, NOTATION_NODE and so on
pass
return rc
# xml_file is either a filename or a file
stream = pulldom.parse(xml_file)
for event, node in stream:
if event == "START_ELEMENT" and node.nodeName == "AssetType":
if node.getAttribute("longname") == "characters":
stream.expandNode(node) # node now contains a mini-dom tree
type_nodes = node.getElementsByTagName('type')
for type_node in type_nodes:
# type_text will have the value of what's inside the type text
type_text = getInnerText(type_node)
A:
Use xml.sax module. Build your own handler and inside startElement you should check, whether name is AssetType. This way you should be able to only act, when AssetType node is processed.
Here you have example handler, which shows, how to build one (though it's not the most pretty way, at that point I didn't know all the cool tricks with Python ;-)).
A:
You could use xpath, something like "//AssetType[longname='characters']/xyz".
For XPath libs in Python see http://www.somebits.com/weblog/tech/python/xpath.html
A:
Similar to eswald's solution, again stripping whitespace, again loading the document into memory, but returning the three text items at a time
from lxml import etree
data = """<AssetType longname="characters" shortname="chr" shortnames="chrs"
<type>
pub
</type>
<type>
geo
</type>
<type>
rig
</type>
</AssetType>
"""
doc = etree.XML(data)
for asset in doc.xpath('//AssetType[@longname="characters"]'):
threetypes = [ x.strip() for x in asset.xpath('./type/text()') ]
print threetypes
|
how to get specific nodes in xml file with python
|
im searching for a way to get a specific tags .. from a very big xml document
with python dom built in module
for example :
<AssetType longname="characters" shortname="chr" shortnames="chrs">
<type>
pub
</type>
<type>
geo
</type>
<type>
rig
</type>
</AssetType>
<AssetType longname="camera" shortname="cam" shortnames="cams">
<type>
cam1
</type>
<type>
cam2
</type>
<type>
cam4
</type>
</AssetType>
i want to retrieve the value of children of AssetType node who got attribute (longname= "characters" )
to have the result of 'pub','geo','rig'
please put in mind that i have more than 1000 < AssetType> nodes
thanx in advance
|
[
"If you don't mind loading the whole document into memory:\nfrom lxml import etree\ndata = etree.parse(fname)\nresult = [node.text.strip() \n for node in data.xpath(\"//AssetType[@longname='characters']/type\")]\n\nYou may need to remove the spaces at the beginning of your tags to make this work.\n",
"Assuming your document is called assets.xml and has the following structure:\n<assets>\n <AssetType>\n ...\n </AssetType>\n <AssetType>\n ...\n </AssetType>\n</assets>\n\nThen you can do the following:\nfrom xml.etree.ElementTree import ElementTree\ntree = ElementTree()\nroot = tree.parse(\"assets.xml\")\nfor assetType in root.findall(\"//AssetType[@longname='characters']\"):\n for type in assetType.getchildren():\n print type.text\n\n",
"You could use the pulldom API to handle parsing a large file, without loading it all into memory at once. This provides a more convenient interface than using SAX with only a slight loss of performance.\nIt basically lets you stream the xml file until you find the bit you are interested in, then start using regular DOM operations after that.\n\nfrom xml.dom import pulldom\n\n# http://mail.python.org/pipermail/xml-sig/2005-March/011022.html\ndef getInnerText(oNode):\n rc = \"\"\n nodelist = oNode.childNodes\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc = rc + node.data\n elif node.nodeType==node.ELEMENT_NODE:\n rc = rc + getInnerText(node) # recursive !!!\n elif node.nodeType==node.CDATA_SECTION_NODE:\n rc = rc + node.data\n else:\n # node.nodeType: PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, NOTATION_NODE and so on\n pass\n return rc\n\n\n# xml_file is either a filename or a file\nstream = pulldom.parse(xml_file) \nfor event, node in stream:\n if event == \"START_ELEMENT\" and node.nodeName == \"AssetType\":\n if node.getAttribute(\"longname\") == \"characters\":\n stream.expandNode(node) # node now contains a mini-dom tree\n type_nodes = node.getElementsByTagName('type')\n for type_node in type_nodes:\n # type_text will have the value of what's inside the type text\n type_text = getInnerText(type_node)\n\n\n",
"Use xml.sax module. Build your own handler and inside startElement you should check, whether name is AssetType. This way you should be able to only act, when AssetType node is processed.\nHere you have example handler, which shows, how to build one (though it's not the most pretty way, at that point I didn't know all the cool tricks with Python ;-)).\n",
"You could use xpath, something like \"//AssetType[longname='characters']/xyz\".\nFor XPath libs in Python see http://www.somebits.com/weblog/tech/python/xpath.html\n",
"Similar to eswald's solution, again stripping whitespace, again loading the document into memory, but returning the three text items at a time\nfrom lxml import etree\n\ndata = \"\"\"<AssetType longname=\"characters\" shortname=\"chr\" shortnames=\"chrs\"\n <type>\n pub\n </type>\n <type>\n geo\n </type>\n <type>\n rig\n </type>\n</AssetType>\n\"\"\"\n\ndoc = etree.XML(data)\n\nfor asset in doc.xpath('//AssetType[@longname=\"characters\"]'):\n threetypes = [ x.strip() for x in asset.xpath('./type/text()') ]\n print threetypes\n\n"
] |
[
8,
8,
3,
2,
1,
1
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002230677_python_xml.txt
|
Q:
Python, next iteration of the loop over a loop
I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code)
ok = 0
for x in range(0,10):
if ok == 1:
ok = 0
continue
for y in range(0,20):
if y == 5:
ok = 1
continue
What about in this situation?
for attribute in object1.__dict__:
object2 = self.getobject()
if object2 is not None:
for attribute2 in object2:
if attribute1 == attribute2:
# Do something
#Need the next item of the outer loop
The second example shows better my current situation. I dont want to post the original code because it's in spanish. object1 and object2 are 2 very different objects, one is of object-relational mapping nature and the other is a webcontrol. But 2 of their attributes have the same values in certain situations, and I need to jump to the next item of the outer loop.
A:
Replace the continue in the inner loop with a break. What you want to do is to actually break out of the inner loop, so a continue there does the opposite of what you want.
ok = 0
for x in range(0,10):
print "x=",x
if ok == 1:
ok = 0
continue
for y in range(0,20):
print "y=",y
if y == 5:
ok = 1
break
A:
You can always transform into a while loop:
flag = False
for x in range(0, 10):
if x == 4:
flag = True
continue
becomes
x = 0
while (x != 4) and x < 10:
x += 1
flag = x < 10
Not necessary simpler, but nicer imho.
A:
Your example code is equivalent to (that doesn't seem what you want):
for x in range(0, 10, 2):
for y in range(20):
if y == 5:
continue
To skip to the next item without using continue in the outer loop:
it = iter(range(10))
for x in it:
for y in range(20):
if y == 5:
nextx = next(it)
continue
A:
So you're not after something like this? I'm assuming that you're looping through the keys to a dictionary, rather than the values, going by your example.
for i in range(len(object1.__dict__)):
attribute1 = objects1.__dict__.keys()[i]
object2 = self.getobject() # Huh?
if object2 is not None:
for j in range(len(object2.__dict__)):
if attribute1 == object2.__dict__.keys()[j]:
try:
nextattribute1 = object1.__dict__.keys()[i+1]
except IndexError:
print "Ran out of attributes in object1"
raise
A:
It's not completely clear to me what you want, but if you're testing something for each item produced in the inner loop, any might be what you want (docs)
>>> def f(n): return n % 2
...
>>> for x in range(10):
... print 'x=', x
... if f(x):
... if any([y == 8 for y in range(x+2,10)]):
... print 'yes'
...
x= 0
x= 1
yes
x= 2
x= 3
yes
x= 4
x= 5
yes
x= 6
x= 7
x= 8
x= 9
|
Python, next iteration of the loop over a loop
|
I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code)
ok = 0
for x in range(0,10):
if ok == 1:
ok = 0
continue
for y in range(0,20):
if y == 5:
ok = 1
continue
What about in this situation?
for attribute in object1.__dict__:
object2 = self.getobject()
if object2 is not None:
for attribute2 in object2:
if attribute1 == attribute2:
# Do something
#Need the next item of the outer loop
The second example shows better my current situation. I dont want to post the original code because it's in spanish. object1 and object2 are 2 very different objects, one is of object-relational mapping nature and the other is a webcontrol. But 2 of their attributes have the same values in certain situations, and I need to jump to the next item of the outer loop.
|
[
"Replace the continue in the inner loop with a break. What you want to do is to actually break out of the inner loop, so a continue there does the opposite of what you want.\nok = 0\nfor x in range(0,10):\n print \"x=\",x\n if ok == 1:\n ok = 0\n continue\n for y in range(0,20): \n print \"y=\",y\n if y == 5:\n ok = 1\n break\n\n",
"You can always transform into a while loop:\nflag = False\nfor x in range(0, 10):\n if x == 4: \n flag = True\n continue\n\nbecomes\nx = 0\nwhile (x != 4) and x < 10:\n x += 1\nflag = x < 10\n\nNot necessary simpler, but nicer imho.\n",
"Your example code is equivalent to (that doesn't seem what you want):\nfor x in range(0, 10, 2):\n for y in range(20): \n if y == 5:\n continue\n\nTo skip to the next item without using continue in the outer loop:\nit = iter(range(10))\nfor x in it:\n for y in range(20):\n if y == 5:\n nextx = next(it)\n continue\n\n",
"So you're not after something like this? I'm assuming that you're looping through the keys to a dictionary, rather than the values, going by your example.\nfor i in range(len(object1.__dict__)):\n attribute1 = objects1.__dict__.keys()[i]\n object2 = self.getobject() # Huh?\n if object2 is not None:\n for j in range(len(object2.__dict__)):\n if attribute1 == object2.__dict__.keys()[j]:\n try:\n nextattribute1 = object1.__dict__.keys()[i+1]\n except IndexError:\n print \"Ran out of attributes in object1\"\n raise\n\n",
"It's not completely clear to me what you want, but if you're testing something for each item produced in the inner loop, any might be what you want (docs)\n>>> def f(n): return n % 2\n... \n>>> for x in range(10):\n... print 'x=', x\n... if f(x):\n... if any([y == 8 for y in range(x+2,10)]):\n... print 'yes'\n... \nx= 0\nx= 1\nyes\nx= 2\nx= 3\nyes\nx= 4\nx= 5\nyes\nx= 6\nx= 7\nx= 8\nx= 9\n\n"
] |
[
15,
2,
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002230244_python.txt
|
Q:
Are there any downsides to upgrading Python on Snow Leopard?
I want to use the newest version of Python on Snow Leopard using the installer package, but I've read some confusing articles about conflicts when upgrading. I plan on using PyDev in Eclipse, will there be any conflicts with Snow Leopard if I upgrade?
A:
To answer your question explicitly: Are there any downsides to upgrading Python on SL? Only if you upgrade the system installation. It can have strange repercussions on any system/CLI tools that use Python, and on any bundled applications (.app) that are utilizing PyObjC runtime libraries.
I would not upgrade, tangle with, or otherwise modify the default installation of Python, if that's what you are asking. You are much better off installing an upgraded version of Python in an alternate location using MacPorts.
MacPorts installs everything into /opt/local (i.e. /opt/local/bin/python) by default. You can then also install python_select which does some jiggering to make sure that whichever version you choose will be preferred based on your PATH.
You might want to consider using virtualenv coupled with pip for managing this environment as well, unless you become accustomed to MacPorts. Things to consider!
|
Are there any downsides to upgrading Python on Snow Leopard?
|
I want to use the newest version of Python on Snow Leopard using the installer package, but I've read some confusing articles about conflicts when upgrading. I plan on using PyDev in Eclipse, will there be any conflicts with Snow Leopard if I upgrade?
|
[
"To answer your question explicitly: Are there any downsides to upgrading Python on SL? Only if you upgrade the system installation. It can have strange repercussions on any system/CLI tools that use Python, and on any bundled applications (.app) that are utilizing PyObjC runtime libraries.\nI would not upgrade, tangle with, or otherwise modify the default installation of Python, if that's what you are asking. You are much better off installing an upgraded version of Python in an alternate location using MacPorts.\nMacPorts installs everything into /opt/local (i.e. /opt/local/bin/python) by default. You can then also install python_select which does some jiggering to make sure that whichever version you choose will be preferred based on your PATH.\nYou might want to consider using virtualenv coupled with pip for managing this environment as well, unless you become accustomed to MacPorts. Things to consider!\n"
] |
[
3
] |
[] |
[] |
[
"macos",
"osx_snow_leopard",
"python"
] |
stackoverflow_0002230968_macos_osx_snow_leopard_python.txt
|
Q:
Is there an alternative to the threading.Condition variables in python that better support timeouts without polling?
I'm using condition variables in threads that require a timeout. I didn't notice until I saw the CPU usage when having a lot of threads running, that the condition variable provided in the threading module doesn't actually sleep, but polls when a timeout is provided as an argument.
Is there an alternative to this that actually sleeps like pthreads?
Seems painful to have a lot of threads sleeping at multiple second intervals only to have it still eating CPU time.
Thanks!
A:
This seems tricky to do in Python, but here is a one solution. It relies on spawning additional threads but doesn't use polling AND ensures that the original thread is woken up as soon as the timeout expires or as soon as the original wait() returns.
Note: The following code includes a test case which tests both the conditional wait ending due to a timeout as well as due to a notification.
from thread import start_new_thread
from threading import Condition, Timer
class ConditionWithoutPolling():
"""Implements wait() with a timeout without polling. Wraps the Condition
class."""
def __init__(self, condition):
self.condition = condition
self.wait_timeout_condition = Condition()
def wait(self, timeout=None):
"""Same as Condition.wait() but it does not use a poll-and-sleep method
to implement timeouts. Instead, if a timeout is requested two new
threads are spawned to implement a non-pol-and-wait method."""
if timeout is None:
# just use the original implementation if no waiting is involved
self.condition.wait()
return
else:
# this new boolean will tell us whether we are done waiting or not
done = [False]
# wait on the original condition in a new thread
start_new_thread(self.wait_on_original, (done,))
# wait for a timeout (without polling) in a new thread
Timer(timeout, lambda : self.wait_timed_out(done)).start()
# wait for EITHER of the previous threads to stop waiting
with self.wait_timeout_condition:
while not done[0]:
self.wait_timeout_condition.wait()
def wait_on_original(self, done):
"""Waits on the original Condition and signals wait_is_over when done."""
self.condition.wait()
self.wait_is_over(done)
def wait_timed_out(self, done):
"""Called when the timeout time is reached."""
# we must re-acquire the lock we were waiting on before we can return
self.condition.acquire()
self.wait_is_over(done)
def wait_is_over(self, done):
"""Modifies done to indicate that the wait is over."""
done[0] = True
with self.wait_timeout_condition:
self.wait_timeout_condition.notify()
# wrap Condition methods since it wouldn't let us subclass it ...
def acquire(self, *args):
self.condition.acquire(*args)
def release(self):
self.condition.release()
def notify(self):
self.condition.notify()
def notify_all(self):
self.condition.notify_all()
def notifyAll(self):
self.condition.notifyAll()
def test(wait_timeout, wait_sec_before_notification):
import time
from threading import Lock
lock = Lock()
cwp = ConditionWithoutPolling(Condition(lock))
start = time.time()
def t1():
with lock:
print 't1 has the lock, will wait up to %f sec' % (wait_timeout,)
cwp.wait(wait_timeout)
time_elapsed = time.time() - start
print 't1: alive after %f sec' % (time_elapsed,)
# this thread will acquire the lock and then conditionally wait for up to
# timeout seconds and then print a message
start_new_thread(t1, ())
# wait until it is time to send the notification and then send it
print 'main thread sleeping (will notify in %f sec)' % (wait_sec_before_notification,)
time.sleep(wait_sec_before_notification)
with lock:
cwp.notifyAll()
print 'notification sent, will continue in 2sec'
time.sleep(2.0) # give the other time thread to finish before exiting
if __name__ == "__main__":
print 'test wait() ending before the timeout ...'
test(2.0, 1.0)
print '\ntest wait() ending due to the timeout ...'
test(2.0, 4.0)
A:
I'm not familiar with Python, but if you are able to block on a condition variable (without a timeout), you could implement the timeout yourself. Let the blocking thread store the time it began blocking and set a timer to signal it. When it wakes, check the time elapsed for a timeout. This isn't a very good way to do it unless you can aggregate the timers to a single thread, otherwise, your thread count would double without reason.
|
Is there an alternative to the threading.Condition variables in python that better support timeouts without polling?
|
I'm using condition variables in threads that require a timeout. I didn't notice until I saw the CPU usage when having a lot of threads running, that the condition variable provided in the threading module doesn't actually sleep, but polls when a timeout is provided as an argument.
Is there an alternative to this that actually sleeps like pthreads?
Seems painful to have a lot of threads sleeping at multiple second intervals only to have it still eating CPU time.
Thanks!
|
[
"This seems tricky to do in Python, but here is a one solution. It relies on spawning additional threads but doesn't use polling AND ensures that the original thread is woken up as soon as the timeout expires or as soon as the original wait() returns.\nNote: The following code includes a test case which tests both the conditional wait ending due to a timeout as well as due to a notification.\nfrom thread import start_new_thread\nfrom threading import Condition, Timer\n\nclass ConditionWithoutPolling():\n \"\"\"Implements wait() with a timeout without polling. Wraps the Condition\n class.\"\"\"\n def __init__(self, condition):\n self.condition = condition\n self.wait_timeout_condition = Condition()\n\n def wait(self, timeout=None):\n \"\"\"Same as Condition.wait() but it does not use a poll-and-sleep method\n to implement timeouts. Instead, if a timeout is requested two new\n threads are spawned to implement a non-pol-and-wait method.\"\"\"\n if timeout is None:\n # just use the original implementation if no waiting is involved\n self.condition.wait()\n return\n else:\n # this new boolean will tell us whether we are done waiting or not\n done = [False]\n\n # wait on the original condition in a new thread\n start_new_thread(self.wait_on_original, (done,))\n\n # wait for a timeout (without polling) in a new thread\n Timer(timeout, lambda : self.wait_timed_out(done)).start()\n\n # wait for EITHER of the previous threads to stop waiting\n with self.wait_timeout_condition:\n while not done[0]:\n self.wait_timeout_condition.wait()\n\n def wait_on_original(self, done):\n \"\"\"Waits on the original Condition and signals wait_is_over when done.\"\"\"\n self.condition.wait()\n self.wait_is_over(done)\n\n def wait_timed_out(self, done):\n \"\"\"Called when the timeout time is reached.\"\"\"\n # we must re-acquire the lock we were waiting on before we can return\n self.condition.acquire()\n self.wait_is_over(done)\n\n def wait_is_over(self, done):\n \"\"\"Modifies done to indicate that the wait is over.\"\"\"\n done[0] = True\n with self.wait_timeout_condition:\n self.wait_timeout_condition.notify()\n\n # wrap Condition methods since it wouldn't let us subclass it ...\n def acquire(self, *args):\n self.condition.acquire(*args)\n def release(self):\n self.condition.release()\n def notify(self):\n self.condition.notify()\n def notify_all(self):\n self.condition.notify_all()\n def notifyAll(self):\n self.condition.notifyAll()\n\ndef test(wait_timeout, wait_sec_before_notification):\n import time\n from threading import Lock\n lock = Lock()\n cwp = ConditionWithoutPolling(Condition(lock))\n start = time.time()\n\n def t1():\n with lock:\n print 't1 has the lock, will wait up to %f sec' % (wait_timeout,)\n cwp.wait(wait_timeout)\n time_elapsed = time.time() - start\n print 't1: alive after %f sec' % (time_elapsed,) \n\n # this thread will acquire the lock and then conditionally wait for up to \n # timeout seconds and then print a message \n start_new_thread(t1, ())\n\n # wait until it is time to send the notification and then send it\n print 'main thread sleeping (will notify in %f sec)' % (wait_sec_before_notification,)\n time.sleep(wait_sec_before_notification)\n with lock:\n cwp.notifyAll()\n print 'notification sent, will continue in 2sec'\n time.sleep(2.0) # give the other time thread to finish before exiting\n\nif __name__ == \"__main__\":\n print 'test wait() ending before the timeout ...'\n test(2.0, 1.0)\n\n print '\\ntest wait() ending due to the timeout ...'\n test(2.0, 4.0)\n\n",
"I'm not familiar with Python, but if you are able to block on a condition variable (without a timeout), you could implement the timeout yourself. Let the blocking thread store the time it began blocking and set a timer to signal it. When it wakes, check the time elapsed for a timeout. This isn't a very good way to do it unless you can aggregate the timers to a single thread, otherwise, your thread count would double without reason.\n"
] |
[
3,
1
] |
[] |
[] |
[
"condition_variable",
"multithreading",
"python"
] |
stackoverflow_0002229086_condition_variable_multithreading_python.txt
|
Q:
getting an attachment from a Outlook mail in linux
I would like to get a file attached to an email I receive using Outlook.
I need to run this python script in a Linux Box.
I read about the win32com.client library.
Do you know if it works also for Linux?
If not do you know any alternative if there are?
A:
Coincidentally, today I posted an example of retrieving attachments over IMAP here, it may be of some use to you.
Outlook is an email client, it may use one or more of a variety of protocols (MAPI,POP,IMAP) to access your mailbox. Your mail may be stored on the server, or it may be stored on your computer (more likely when using POP).
|
getting an attachment from a Outlook mail in linux
|
I would like to get a file attached to an email I receive using Outlook.
I need to run this python script in a Linux Box.
I read about the win32com.client library.
Do you know if it works also for Linux?
If not do you know any alternative if there are?
|
[
"Coincidentally, today I posted an example of retrieving attachments over IMAP here, it may be of some use to you.\nOutlook is an email client, it may use one or more of a variety of protocols (MAPI,POP,IMAP) to access your mailbox. Your mail may be stored on the server, or it may be stored on your computer (more likely when using POP).\n"
] |
[
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002230958_python.txt
|
Q:
Python comparison evaluation
As per the python documentation,x<y<z comparison is translated to x<y and y<z and expression y is evaluated only once at most.
Now my question is , does an expression y ( look at the code below) is evaluated only once here?
if(x<y and y<z):
A:
Twice:
>>> def f():
... print "F called"
... return 1
...
>>> 0 < f() < 100
F called
True
>>> 0 < f() and f() < 100
F called
F called
True
>>> if (0 < f() and f() < 100):
... print True
...
F called
F called
True
>>>
A:
No:
>>> dis.dis(lambda x, y, z: x < y() < z)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 CALL_FUNCTION 0
9 DUP_TOP
10 ROT_THREE
11 COMPARE_OP 0 (<)
14 JUMP_IF_FALSE 8 (to 25)
17 POP_TOP
18 LOAD_FAST 2 (z)
21 COMPARE_OP 0 (<)
24 RETURN_VALUE
>> 25 ROT_TWO
26 POP_TOP
27 RETURN_VALUE
>>> dis.dis(lambda x, y, z: x < y() and y() < z)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 CALL_FUNCTION 0
9 COMPARE_OP 0 (<)
12 JUMP_IF_FALSE 13 (to 28)
15 POP_TOP
16 LOAD_FAST 1 (y)
19 CALL_FUNCTION 0
22 LOAD_FAST 2 (z)
25 COMPARE_OP 0 (<)
>> 28 RETURN_VALUE
|
Python comparison evaluation
|
As per the python documentation,x<y<z comparison is translated to x<y and y<z and expression y is evaluated only once at most.
Now my question is , does an expression y ( look at the code below) is evaluated only once here?
if(x<y and y<z):
|
[
"Twice:\n>>> def f():\n... print \"F called\"\n... return 1\n...\n>>> 0 < f() < 100\nF called\nTrue\n>>> 0 < f() and f() < 100\nF called\nF called\nTrue\n>>> if (0 < f() and f() < 100):\n... print True\n...\nF called\nF called\nTrue\n>>>\n\n",
"No:\n>>> dis.dis(lambda x, y, z: x < y() < z)\n 1 0 LOAD_FAST 0 (x)\n 3 LOAD_FAST 1 (y)\n 6 CALL_FUNCTION 0\n 9 DUP_TOP \n 10 ROT_THREE \n 11 COMPARE_OP 0 (<)\n 14 JUMP_IF_FALSE 8 (to 25)\n 17 POP_TOP \n 18 LOAD_FAST 2 (z)\n 21 COMPARE_OP 0 (<)\n 24 RETURN_VALUE \n >> 25 ROT_TWO \n 26 POP_TOP \n 27 RETURN_VALUE \n>>> dis.dis(lambda x, y, z: x < y() and y() < z)\n 1 0 LOAD_FAST 0 (x)\n 3 LOAD_FAST 1 (y)\n 6 CALL_FUNCTION 0\n 9 COMPARE_OP 0 (<)\n 12 JUMP_IF_FALSE 13 (to 28)\n 15 POP_TOP \n 16 LOAD_FAST 1 (y)\n 19 CALL_FUNCTION 0\n 22 LOAD_FAST 2 (z)\n 25 COMPARE_OP 0 (<)\n >> 28 RETURN_VALUE \n\n"
] |
[
9,
3
] |
[] |
[] |
[
"comparison",
"python",
"syntax"
] |
stackoverflow_0002231220_comparison_python_syntax.txt
|
Q:
pyserial- sending in parameters at runtime- input vs. raw_input - security flaw?
I am writing a program that opens and records data sent through a serial port into a text file. I am currently adding functionality to allow reconfiguring the serial port during run-time. I prompt the user to choose which variable to change one at a time, so as to keep it simple for myself (i would appreciate elegant solutions as well).
The pyserial function that creates the serial instance (serial.Serial()) has the following parameters:
import serial
ser = serial.Serial(port=0, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None, interCharTimeout=None) #default values shown
I notice that while most are int() arguments, some are not, i.e. "timeout".
I know using int(raw_input("for the int() type variables)) would let me safely assign the int variables, but the variables with None as default would require an input() function to properly assign the possible None value.
I have read elsewhere that input() is generally not recommended, since it has potential for being exploited(something about eval()?). How then should i handle those inputs? i.e. using serial.Serial() where writeTimout = str(None) throws an error.
Thanks!
A:
The safest way is just to accept the user's input as a string and then parse it. I.e. let the user enter key=value pairs:
baudrate = 9600
parity = N
Then parse these pairs, by splitting on '=' and stripping both sides. Assign the variables with a string lookup table (the baudrate string maps to the baudrate var, and so on). This way you can handle the None value any way you want.
This method is simple and safe. input will raise exceptions if the user input isn't valid Python, and you may not want that.
|
pyserial- sending in parameters at runtime- input vs. raw_input - security flaw?
|
I am writing a program that opens and records data sent through a serial port into a text file. I am currently adding functionality to allow reconfiguring the serial port during run-time. I prompt the user to choose which variable to change one at a time, so as to keep it simple for myself (i would appreciate elegant solutions as well).
The pyserial function that creates the serial instance (serial.Serial()) has the following parameters:
import serial
ser = serial.Serial(port=0, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None, interCharTimeout=None) #default values shown
I notice that while most are int() arguments, some are not, i.e. "timeout".
I know using int(raw_input("for the int() type variables)) would let me safely assign the int variables, but the variables with None as default would require an input() function to properly assign the possible None value.
I have read elsewhere that input() is generally not recommended, since it has potential for being exploited(something about eval()?). How then should i handle those inputs? i.e. using serial.Serial() where writeTimout = str(None) throws an error.
Thanks!
|
[
"The safest way is just to accept the user's input as a string and then parse it. I.e. let the user enter key=value pairs:\nbaudrate = 9600\nparity = N\n\nThen parse these pairs, by splitting on '=' and stripping both sides. Assign the variables with a string lookup table (the baudrate string maps to the baudrate var, and so on). This way you can handle the None value any way you want.\nThis method is simple and safe. input will raise exceptions if the user input isn't valid Python, and you may not want that.\n"
] |
[
0
] |
[] |
[] |
[
"pyserial",
"python",
"security",
"user_input"
] |
stackoverflow_0002231249_pyserial_python_security_user_input.txt
|
Q:
Unexpected object assignment
class TrafficData(object):
def __init__(self):
self.__data = {}
def __getitem__(self, epoch):
if not isinstance(epoch, int):
raise TypeError()
return self.__data.setdefault(epoch, ProcessTraffic())
def __iadd__(self, other):
for epoch, traffic in other.iteritems():
# these work
#existing = self[epoch]
#existing += traffic
# this does not
self[epoch] += traffic # here the exception is thrown
return self
In the above trimmed down code, I do not expect an item assignment, yet apparently one is occurring on the marked line, and throwing the following exception:
File "nethogs2.py", line 130, in __iadd__
self[epoch] += traffic
TypeError: 'TrafficData' object does not support item assignment
However if I instead use the preceding 2 commented out lines, no exception is thrown.
As I see it, the 2 should behave in the same way. self[epoch] returns a reference to an object, and it's modified in place through that objects __iadd__. What am I misunderstanding here? I frequently run into this problem when using dictionaries.
Update0
It's probably worth pointing out that the values in self.__data have __iadd__ defined, but not __add__, and I'd much prefer to modify the value in place if possible. I would also like to avoid creating a __setitem__ method.
Update1
Below is a test case demonstrating the problem, I've left the code above for existing answers.
class Value(object):
def __init__(self, initial=0):
self.a = initial
def __iadd__(self, other):
self.a += other
return self
def __str__(self):
return str(self.a)
class Blah(object):
def __init__(self):
self.__data = {}
def __getitem__(self, key):
return self.__data.setdefault(key, Value())
a = Blah()
b = a[1]
b += 1
print a[1]
a[1] += 2
print a[1]
A:
What you are exactly doing in:
self[epoch] += traffic
is:
self[epoch] = self[epoch] + traffic
But you haven't defined __setitem__ method, so you can do that on self.
You also need:
def __setitem__(self, epoch, value):
self.__data[epoch] = value
or something similar.
A:
It's probably worth pointing out that
the values in self.__data have
__iadd__ defined, but not __add__, and I'd much prefer to modify the value in
place if possible.
To add some precision to previous answers, under the circumstances you describe, self[epoch] += traffic translates exactly to:
self[epoch] = self[epoch].__iadd__(traffic)
So if all you want are the side effects of __iadd__, without the item-assignment part, your choices are limited to the workaround that you've already identified in the comments in the code you've posted, or calling __iadd__ yourself -- possibly through the operator module, though I believe operator.__iadd__(self[epoch], traffic) has no added value compared to the simpler self[epoch].__iadd__(traffic) (when self[epoch] does have a __iadd__ method).
A:
The code:
self[epoch] += traffic
Is syntactic sugar for:
self[epoch] = self[epoch] + traffic
So the assignment is not unexpected it is the assignment in +=. So you also need to override the __setitem__() method.
|
Unexpected object assignment
|
class TrafficData(object):
def __init__(self):
self.__data = {}
def __getitem__(self, epoch):
if not isinstance(epoch, int):
raise TypeError()
return self.__data.setdefault(epoch, ProcessTraffic())
def __iadd__(self, other):
for epoch, traffic in other.iteritems():
# these work
#existing = self[epoch]
#existing += traffic
# this does not
self[epoch] += traffic # here the exception is thrown
return self
In the above trimmed down code, I do not expect an item assignment, yet apparently one is occurring on the marked line, and throwing the following exception:
File "nethogs2.py", line 130, in __iadd__
self[epoch] += traffic
TypeError: 'TrafficData' object does not support item assignment
However if I instead use the preceding 2 commented out lines, no exception is thrown.
As I see it, the 2 should behave in the same way. self[epoch] returns a reference to an object, and it's modified in place through that objects __iadd__. What am I misunderstanding here? I frequently run into this problem when using dictionaries.
Update0
It's probably worth pointing out that the values in self.__data have __iadd__ defined, but not __add__, and I'd much prefer to modify the value in place if possible. I would also like to avoid creating a __setitem__ method.
Update1
Below is a test case demonstrating the problem, I've left the code above for existing answers.
class Value(object):
def __init__(self, initial=0):
self.a = initial
def __iadd__(self, other):
self.a += other
return self
def __str__(self):
return str(self.a)
class Blah(object):
def __init__(self):
self.__data = {}
def __getitem__(self, key):
return self.__data.setdefault(key, Value())
a = Blah()
b = a[1]
b += 1
print a[1]
a[1] += 2
print a[1]
|
[
"What you are exactly doing in:\nself[epoch] += traffic\n\nis:\nself[epoch] = self[epoch] + traffic\n\nBut you haven't defined __setitem__ method, so you can do that on self.\nYou also need:\ndef __setitem__(self, epoch, value):\n self.__data[epoch] = value\n\nor something similar.\n",
"\nIt's probably worth pointing out that\n the values in self.__data have\n __iadd__ defined, but not __add__, and I'd much prefer to modify the value in\n place if possible.\n\nTo add some precision to previous answers, under the circumstances you describe, self[epoch] += traffic translates exactly to:\nself[epoch] = self[epoch].__iadd__(traffic)\n\nSo if all you want are the side effects of __iadd__, without the item-assignment part, your choices are limited to the workaround that you've already identified in the comments in the code you've posted, or calling __iadd__ yourself -- possibly through the operator module, though I believe operator.__iadd__(self[epoch], traffic) has no added value compared to the simpler self[epoch].__iadd__(traffic) (when self[epoch] does have a __iadd__ method).\n",
"The code:\nself[epoch] += traffic\n\nIs syntactic sugar for:\nself[epoch] = self[epoch] + traffic\n\nSo the assignment is not unexpected it is the assignment in +=. So you also need to override the __setitem__() method.\n"
] |
[
6,
1,
0
] |
[] |
[] |
[
"dictionary",
"python",
"variable_assignment"
] |
stackoverflow_0002230993_dictionary_python_variable_assignment.txt
|
Q:
Mako thinks my template has a 'pass' after an if statement, even though the traceback shows there isn't one
I have Mako taking a template from a preprocessor, and now thinks there is a 'pass' after my if statement.
Here is the complete traceback
Error !
SyntaxException: (SyntaxError) invalid syntax (, line 1) (u"if ${session['anonymous']}:pass") in file '/.../site/templates/shpaml/views/index.html' at line: 3 char: 1
1 <p>your anonymous status is ${session['anonymous']}</p>
2
3 % if ${session['anonymous']}:
4
5 <a href='/login/'>login</a>
6
7 % else:
8
/.../site/library/mako/pyparser.py, line 37:
raise exceptions.SyntaxException("(%s) %s (%s)" % (e.__class__.__name__, str(e), repr(code[0:50])), **exception_kwargs)
/.../site/library/mako/ast.py, line 30:
expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
/.../site/library/mako/ast.py, line 82:
super(PythonFragment, self).__init__(code, **exception_kwargs)
/.../site/library/mako/parsetree.py, line 69:
code = ast.PythonFragment(text, **self.exception_kwargs)
/.../site/library/mako/lexer.py, line 94:
node = nodecls(*args, **kwargs)
/.../site/library/mako/lexer.py, line 313:
self.append_node(parsetree.ControlLine, keyword, isend, self.escape_code(text))
/.../site/library/mako/lexer.py, line 152:
if self.match_control_line():
/.../site/library/mako/template.py, line 257:
node = lexer.parse()
/.../site/library/mako/template.py, line 93:
(code, module) = _compile_text(self, file(filename).read(), filename)
/.../site/library/mako/lookup.py, line 127:
self.__collection[uri] = Template(uri=uri, filename=posixpath.normpath(filename), lookup=self, module_filename=(self.modulename_callable is not None and self.modulename_callable(filename, uri) or None), **self.template_args)
/.../site/library/mako/lookup.py, line 85:
return self.__load(srcfile, uri)
/.../site/library/templates/__init__.py, line 25:
template = lookup_map[type].get_template(template_name)
Why would the traceback show pass but not show it in the traceback source? On top of that, it says the wrong line number. ${session['anonymous']} in line 1 returns True (if I remove the syntax error). So that doesn't have any problems.
A:
Well, this is one of those embarrassing cases that took days of agony to figure out something so simple:
It needed to be
if session['anonymous']:
|
Mako thinks my template has a 'pass' after an if statement, even though the traceback shows there isn't one
|
I have Mako taking a template from a preprocessor, and now thinks there is a 'pass' after my if statement.
Here is the complete traceback
Error !
SyntaxException: (SyntaxError) invalid syntax (, line 1) (u"if ${session['anonymous']}:pass") in file '/.../site/templates/shpaml/views/index.html' at line: 3 char: 1
1 <p>your anonymous status is ${session['anonymous']}</p>
2
3 % if ${session['anonymous']}:
4
5 <a href='/login/'>login</a>
6
7 % else:
8
/.../site/library/mako/pyparser.py, line 37:
raise exceptions.SyntaxException("(%s) %s (%s)" % (e.__class__.__name__, str(e), repr(code[0:50])), **exception_kwargs)
/.../site/library/mako/ast.py, line 30:
expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
/.../site/library/mako/ast.py, line 82:
super(PythonFragment, self).__init__(code, **exception_kwargs)
/.../site/library/mako/parsetree.py, line 69:
code = ast.PythonFragment(text, **self.exception_kwargs)
/.../site/library/mako/lexer.py, line 94:
node = nodecls(*args, **kwargs)
/.../site/library/mako/lexer.py, line 313:
self.append_node(parsetree.ControlLine, keyword, isend, self.escape_code(text))
/.../site/library/mako/lexer.py, line 152:
if self.match_control_line():
/.../site/library/mako/template.py, line 257:
node = lexer.parse()
/.../site/library/mako/template.py, line 93:
(code, module) = _compile_text(self, file(filename).read(), filename)
/.../site/library/mako/lookup.py, line 127:
self.__collection[uri] = Template(uri=uri, filename=posixpath.normpath(filename), lookup=self, module_filename=(self.modulename_callable is not None and self.modulename_callable(filename, uri) or None), **self.template_args)
/.../site/library/mako/lookup.py, line 85:
return self.__load(srcfile, uri)
/.../site/library/templates/__init__.py, line 25:
template = lookup_map[type].get_template(template_name)
Why would the traceback show pass but not show it in the traceback source? On top of that, it says the wrong line number. ${session['anonymous']} in line 1 returns True (if I remove the syntax error). So that doesn't have any problems.
|
[
"Well, this is one of those embarrassing cases that took days of agony to figure out something so simple:\nIt needed to be \nif session['anonymous']:\n\n"
] |
[
1
] |
[] |
[] |
[
"mako",
"python",
"syntax_error"
] |
stackoverflow_0002230455_mako_python_syntax_error.txt
|
Q:
how can i pass xml format data from flex to python
i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python should convert all the data into xml format,and pass all the data to the flex..
Thank's in advance.....
A:
See http://www.artima.com/weblogs/viewpost.jsp?thread=208528 for more details, here is a breif overview of what I think you are looking for.
The SimpleXMLRPCServer library allows you to easily create a server. Here's about the simplest server you can create, which provides two services to manipulate strings:
import sys
from random import shuffle
from SimpleXMLRPCServer import SimpleXMLRPCServer
class MyFuncs:
def reverse(self, str) :
x = list(str);
x.reverse();
return ''.join(x);
def scramble(self, str):
x = list(str);
shuffle(x);
return ''.join(x);
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(MyFuncs())
server.serve_forever()
Once you make a connection to the server, that server acts like a local object. You call the server's methods just like they're ordinary methods of that object.
This is about as clean an RPC implementation as you can hope for (and other Python RPC libraries exist; for example, CORBA clients). But it's all text based; not very satisfying when trying to create polished applications with nice GUIs. What we'd like is the best of all worlds -- Python (or your favorite language) doing the heavy lifting under the covers, and Flex creating the user experience.
To use the library, download it and unpack it somewhere. The package includes all the source code and the compiled as3-rpclib.swc library -- the .swc extension indicates an archive file, and pieces of this library can be pulled out and incorporated into your final .swf. To include the library in your project, you must tell Flexbuilder (you can get a free trial or just use the free command-line tools, and add on the Apollo portion) where the library is located by going to Project|Properties and selecting "Apollo Build Path," then choosing the "Library path" tab and pressing the "Add SWC..." button. Next, you add the namespace ak33m to your project as seen in the code below, and you're ready to create an XMLRPCObject.
Note: the only reason I used Apollo here was that I was thinking in terms of desktop applications with nice UIs. You can just as easily make it a Flex app.
Here's the entire Apollo application as a single MXML file, which I'll explain in detail:
<?xml version="1.0" encoding="utf-8"?>
<mx:ApolloApplication xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:ak33m="http://ak33m.com/mxml" layout="absolute">
<mx:Form>
<mx:FormHeading label="String Modifier"/>
<mx:FormItem label="Input String">
<mx:TextInput id="instring" change="manipulate()"/>
</mx:FormItem>
<mx:FormItem label="Reversed">
<mx:Text id="reversed"/>
</mx:FormItem>
<mx:FormItem label="Scrambled">
<mx:Text id="scrambled"/>
</mx:FormItem>
</mx:Form>
<ak33m:XMLRPCObject id="server" endpoint="http://localhost:8000"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.AsyncToken;
import mx.controls.Alert;
import mx.collections.ItemResponder;
private function manipulate() : void {
server.reverse(instring.text).addResponder(new ItemResponder(reverseResult, onFault));
server.scramble(instring.text).addResponder(new ItemResponder(scrambleResult, onFault));
}
private function reverseResult(event : ResultEvent, token : AsyncToken = null) : void {
reversed.text = event.result.toString();
}
private function scrambleResult(event : ResultEvent, token : AsyncToken = null) : void {
scrambled.text = event.result.toString();
}
private function onFault (event : FaultEvent, token : AsyncToken = null) : void {
Alert.show(event.fault.faultString, event.fault.faultCode);
}
]]>
</mx:Script>
</mx:ApolloApplication>
|
how can i pass xml format data from flex to python
|
i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python should convert all the data into xml format,and pass all the data to the flex..
Thank's in advance.....
|
[
"See http://www.artima.com/weblogs/viewpost.jsp?thread=208528 for more details, here is a breif overview of what I think you are looking for.\nThe SimpleXMLRPCServer library allows you to easily create a server. Here's about the simplest server you can create, which provides two services to manipulate strings: \nimport sys\nfrom random import shuffle\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\n\nclass MyFuncs:\n def reverse(self, str) :\n x = list(str);\n x.reverse();\n return ''.join(x);\n def scramble(self, str):\n x = list(str);\n shuffle(x);\n return ''.join(x);\n\nserver = SimpleXMLRPCServer((\"localhost\", 8000))\nserver.register_instance(MyFuncs())\nserver.serve_forever()\n\nOnce you make a connection to the server, that server acts like a local object. You call the server's methods just like they're ordinary methods of that object.\nThis is about as clean an RPC implementation as you can hope for (and other Python RPC libraries exist; for example, CORBA clients). But it's all text based; not very satisfying when trying to create polished applications with nice GUIs. What we'd like is the best of all worlds -- Python (or your favorite language) doing the heavy lifting under the covers, and Flex creating the user experience. \nTo use the library, download it and unpack it somewhere. The package includes all the source code and the compiled as3-rpclib.swc library -- the .swc extension indicates an archive file, and pieces of this library can be pulled out and incorporated into your final .swf. To include the library in your project, you must tell Flexbuilder (you can get a free trial or just use the free command-line tools, and add on the Apollo portion) where the library is located by going to Project|Properties and selecting \"Apollo Build Path,\" then choosing the \"Library path\" tab and pressing the \"Add SWC...\" button. Next, you add the namespace ak33m to your project as seen in the code below, and you're ready to create an XMLRPCObject.\nNote: the only reason I used Apollo here was that I was thinking in terms of desktop applications with nice UIs. You can just as easily make it a Flex app.\nHere's the entire Apollo application as a single MXML file, which I'll explain in detail: \n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:ApolloApplication xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n xmlns:ak33m=\"http://ak33m.com/mxml\" layout=\"absolute\">\n <mx:Form>\n <mx:FormHeading label=\"String Modifier\"/>\n <mx:FormItem label=\"Input String\">\n <mx:TextInput id=\"instring\" change=\"manipulate()\"/>\n </mx:FormItem>\n <mx:FormItem label=\"Reversed\">\n <mx:Text id=\"reversed\"/>\n </mx:FormItem>\n <mx:FormItem label=\"Scrambled\">\n <mx:Text id=\"scrambled\"/>\n </mx:FormItem>\n </mx:Form>\n <ak33m:XMLRPCObject id=\"server\" endpoint=\"http://localhost:8000\"/>\n <mx:Script>\n <![CDATA[\n import mx.rpc.events.ResultEvent;\n import mx.rpc.events.FaultEvent;\n import mx.rpc.AsyncToken;\n import mx.controls.Alert;\n import mx.collections.ItemResponder;\n private function manipulate() : void {\n server.reverse(instring.text).addResponder(new ItemResponder(reverseResult, onFault));\n server.scramble(instring.text).addResponder(new ItemResponder(scrambleResult, onFault));\n }\n private function reverseResult(event : ResultEvent, token : AsyncToken = null) : void {\n reversed.text = event.result.toString();\n }\n private function scrambleResult(event : ResultEvent, token : AsyncToken = null) : void {\n scrambled.text = event.result.toString();\n }\n private function onFault (event : FaultEvent, token : AsyncToken = null) : void {\n Alert.show(event.fault.faultString, event.fault.faultCode);\n } \n ]]>\n </mx:Script>\n</mx:ApolloApplication>\n\n"
] |
[
1
] |
[] |
[] |
[
"flex3",
"mysql",
"python"
] |
stackoverflow_0002228078_flex3_mysql_python.txt
|
Q:
What's python complaining about here?
I'm trying to run Adobe's sample python policy server script, linked to here: http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
I'm getting the following error:
# python flashpolicyd.py --file=policy.xml
File "flashpolicyd.py", line 40
with file(path, 'rb') as f:
^
SyntaxError: invalid syntax
In context:
class policy_server(object):
def __init__(self, port, path):
self.port = port
self.path = path
self.policy = self.read_policy(path)
self.log('Listening on port %d\n' % port)
try:
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
except AttributeError:
# AttributeError catches Python built without IPv6
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
# socket.error catches OS with IPv6 disabled
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', port))
self.sock.listen(5)
def read_policy(self, path):
with file(path, 'rb') as f:
I know nothing about python, so this may be something very simple and obvious.
A:
with is only available in 2.6+, or in 2.5+ with from __future__ import with_statement.
A:
The with statement is new in Python 2.5. Perhaps you are using an older version?
|
What's python complaining about here?
|
I'm trying to run Adobe's sample python policy server script, linked to here: http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
I'm getting the following error:
# python flashpolicyd.py --file=policy.xml
File "flashpolicyd.py", line 40
with file(path, 'rb') as f:
^
SyntaxError: invalid syntax
In context:
class policy_server(object):
def __init__(self, port, path):
self.port = port
self.path = path
self.policy = self.read_policy(path)
self.log('Listening on port %d\n' % port)
try:
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
except AttributeError:
# AttributeError catches Python built without IPv6
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
# socket.error catches OS with IPv6 disabled
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', port))
self.sock.listen(5)
def read_policy(self, path):
with file(path, 'rb') as f:
I know nothing about python, so this may be something very simple and obvious.
|
[
"with is only available in 2.6+, or in 2.5+ with from __future__ import with_statement.\n",
"The with statement is new in Python 2.5. Perhaps you are using an older version?\n"
] |
[
6,
1
] |
[] |
[] |
[
"flash",
"policyfiles",
"python",
"sockets"
] |
stackoverflow_0002231954_flash_policyfiles_python_sockets.txt
|
Q:
Assign a value equal only to itself
I wish to assign to a variable (a "constant"), a value that will allow that variable to only ever return True in is and == comparisons against itself.
I want to avoid assigning an arbitary value such as an int or some other type on the off chance that the value I choose clashes with some other.
I'm considering generating an instance of a class that uses the uniqueness of CPython's id() values in any comparisons the value might support.
From here:
If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity (“address”).
Would suggest that:
MY_CONSTANT = object()
Will only ever return true in a comparison with MY_CONSTANT on a CPython implementation if MY_CONSTANT was somehow garbage collected, and something else allocated in it's place during the comparison (I would assume this is probably never going to happen).
A:
Yes. This is a good way to define unique constants. There is of course, the minimal risk of whatever object you are comparing it to being defined as equal to everything, but if everyone is playing reasonably nicely, this should work. Also, the garbage collection issue won't be a problem, because if that should ever happen, your constant has already gone away, and isn't around to compare equal to the new object with the same id.
A:
As long as MY_CONSTANT stays in scope the object it references can not be garbage collected.
You really should always use is for comparison, as the behaviour of == can be overridden
|
Assign a value equal only to itself
|
I wish to assign to a variable (a "constant"), a value that will allow that variable to only ever return True in is and == comparisons against itself.
I want to avoid assigning an arbitary value such as an int or some other type on the off chance that the value I choose clashes with some other.
I'm considering generating an instance of a class that uses the uniqueness of CPython's id() values in any comparisons the value might support.
From here:
If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity (“address”).
Would suggest that:
MY_CONSTANT = object()
Will only ever return true in a comparison with MY_CONSTANT on a CPython implementation if MY_CONSTANT was somehow garbage collected, and something else allocated in it's place during the comparison (I would assume this is probably never going to happen).
|
[
"Yes. This is a good way to define unique constants. There is of course, the minimal risk of whatever object you are comparing it to being defined as equal to everything, but if everyone is playing reasonably nicely, this should work. Also, the garbage collection issue won't be a problem, because if that should ever happen, your constant has already gone away, and isn't around to compare equal to the new object with the same id.\n",
"As long as MY_CONSTANT stays in scope the object it references can not be garbage collected.\nYou really should always use is for comparison, as the behaviour of == can be overridden\n"
] |
[
1,
0
] |
[] |
[] |
[
"comparison",
"constants",
"cpython",
"python",
"unique"
] |
stackoverflow_0002231781_comparison_constants_cpython_python_unique.txt
|
Q:
check that a script is actually using a proxy from a ip list
I have a list of proxy ip's that I want to use in one of my python scripts, but how do I verify that I am using one of the ip addresses from the list and not my own? I'm using mechanize, but any general explanation of how to do this would be helpful.
This is the first time I have worked with proxies, so anything you can tell me will be be really appreciated.
Thanks
A:
Running wireshark / tshark would be one way.
Many proxies run on port 3128, but substitute this for the proxy you're using. Make you request and if you get traffic to the host and port of your configured proxy, it's probably
working. If it goes to the host for the website, then it's not.
E.g. First without a proxy:
$ tshark -i eth0 -n -Nn tcp port 3128 or tcp port 80
from mechanize import Browser
br = Browser()
br.open('http://news.bbc.co.uk')
0.000000 mylocalhost -> nol-vip05.cwwtf.bbc.co.uk TCP 51088 > 80 [SYN]
0.003296 nol-vip05.cwwtf.bbc.co.uk -> mylocalhost TCP 80 > 51088 [SYN, ACK]
0.003318 mylocalhost -> nol-vip05.cwwtf.bbc.co.uk TCP 51088 > 80 [ACK]
0.003375 mylocalhost -> nol-vip05.cwwtf.bbc.co.uk HTTP GET / HTTP/1.1
With a proxy:
br.set_proxies({'http':'some.proxy:3128'})
br.open('http://news.bbc.co.uk')
0.000000 mylocalhost -> some.proxy TCP 57556 > 3128 [SYN]
0.011529 some.proxy -> mylocalhost TCP 3128 > 57556 [SYN, ACK]
0.011571 mylocalhost -> some.proxy TCP 57556 > 3128 [ACK]
0.011636 mylocalhost -> some.proxy HTTP GET / HTTP/1.1
|
check that a script is actually using a proxy from a ip list
|
I have a list of proxy ip's that I want to use in one of my python scripts, but how do I verify that I am using one of the ip addresses from the list and not my own? I'm using mechanize, but any general explanation of how to do this would be helpful.
This is the first time I have worked with proxies, so anything you can tell me will be be really appreciated.
Thanks
|
[
"Running wireshark / tshark would be one way.\nMany proxies run on port 3128, but substitute this for the proxy you're using. Make you request and if you get traffic to the host and port of your configured proxy, it's probably \nworking. If it goes to the host for the website, then it's not.\nE.g. First without a proxy:\n$ tshark -i eth0 -n -Nn tcp port 3128 or tcp port 80\nfrom mechanize import Browser\nbr = Browser()\nbr.open('http://news.bbc.co.uk')\n\n\n0.000000 mylocalhost -> nol-vip05.cwwtf.bbc.co.uk TCP 51088 > 80 [SYN]\n0.003296 nol-vip05.cwwtf.bbc.co.uk -> mylocalhost TCP 80 > 51088 [SYN, ACK]\n0.003318 mylocalhost -> nol-vip05.cwwtf.bbc.co.uk TCP 51088 > 80 [ACK]\n0.003375 mylocalhost -> nol-vip05.cwwtf.bbc.co.uk HTTP GET / HTTP/1.1\n\nWith a proxy:\nbr.set_proxies({'http':'some.proxy:3128'})\nbr.open('http://news.bbc.co.uk')\n\n\n0.000000 mylocalhost -> some.proxy TCP 57556 > 3128 [SYN]\n0.011529 some.proxy -> mylocalhost TCP 3128 > 57556 [SYN, ACK]\n0.011571 mylocalhost -> some.proxy TCP 57556 > 3128 [ACK]\n0.011636 mylocalhost -> some.proxy HTTP GET / HTTP/1.1\n\n"
] |
[
1
] |
[] |
[] |
[
"proxy",
"python"
] |
stackoverflow_0002231887_proxy_python.txt
|
Q:
Updating python variable from c
I am having an intermittent error causing my Python module to crash, and I'm assuming it's because of a memory error occurring by not getting the refcounts correct in the c code. I have a bit of code that gets a response at a random time from a remote location. Based on the data received, it needs to update a data variable which I should have access to in Python. What's the best way to accomplish this? The following code runs most of the time, and it works correctly when it does, but when it doesn't it crashes Python (bringing up the visual studio debug box). Thanks.
if (event == kResponseEvent) {
list = PyList_New(0);
for (i = 0; i < event->count; i++) {
PyList_Append(list, Py_BuildValue("{s:i, s:s}",
"id", event->id,
"name", event->name));
}
PyModule_AddObject(module, "names", list);
}
A:
PyModule_AddObject() steals a reference. As such, you should not be decrefing list after.
A:
PyList_New() can return NULL to indicate an error, which you aren't checking for. Py_BuildValue() can return NULL to indicate an error, which you aren't checking for. PyList_Append() can return -1 to indicate an error, which you're also not checking for. PyList_Append() doesn't steal the reference, so you're leaking the reference to the dict returned by Py_BuildValue(). The latter may be causing you to run out of memory, which can cause Py_BuildValue() or PyList_Append() to fail, and your failure to handle the error can cause a crash.
(Something else can also cause Py_BuildValue() or PyList_Append() to fail, but that's hard to guess at from just this snippet.)
|
Updating python variable from c
|
I am having an intermittent error causing my Python module to crash, and I'm assuming it's because of a memory error occurring by not getting the refcounts correct in the c code. I have a bit of code that gets a response at a random time from a remote location. Based on the data received, it needs to update a data variable which I should have access to in Python. What's the best way to accomplish this? The following code runs most of the time, and it works correctly when it does, but when it doesn't it crashes Python (bringing up the visual studio debug box). Thanks.
if (event == kResponseEvent) {
list = PyList_New(0);
for (i = 0; i < event->count; i++) {
PyList_Append(list, Py_BuildValue("{s:i, s:s}",
"id", event->id,
"name", event->name));
}
PyModule_AddObject(module, "names", list);
}
|
[
"PyModule_AddObject() steals a reference. As such, you should not be decrefing list after.\n",
"PyList_New() can return NULL to indicate an error, which you aren't checking for. Py_BuildValue() can return NULL to indicate an error, which you aren't checking for. PyList_Append() can return -1 to indicate an error, which you're also not checking for. PyList_Append() doesn't steal the reference, so you're leaking the reference to the dict returned by Py_BuildValue(). The latter may be causing you to run out of memory, which can cause Py_BuildValue() or PyList_Append() to fail, and your failure to handle the error can cause a crash.\n(Something else can also cause Py_BuildValue() or PyList_Append() to fail, but that's hard to guess at from just this snippet.)\n"
] |
[
1,
1
] |
[] |
[] |
[
"c",
"python"
] |
stackoverflow_0002231287_c_python.txt
|
Q:
Python newbie having a problem using classes
Im just beginning to mess around a bit with classes; however, I am running across a problem.
class MyClass(object):
def f(self):
return 'hello world'
print MyClass.f
The previous script is returning <unbound method MyClass.f> instead of the intended value. How do I fix this?
A:
MyClass.f refers to the function object f which is a property of MyClass. In your case, f is an instance method (has a self parameter) so its called on a particular instance. Its "unbound" because you're referring to f without specifying a specific class, kind of like referring to a steering wheel without a car.
You can create an instance of MyClass and call f from it like so:
x = MyClass()
x.f()
(This specifies which instance to call f from, so you can refer to instance variables and the like.)
You're using f as a static method. These methods aren't bound to a particular class, and can only reference their parameters.
A static method would be created and used like so:
class MyClass(object):
def f(): #no self parameter
return 'hello world'
print MyClass.f()
A:
Create an instance of your class: m = MyClass()
then use m.f() to call the function
Now you may wonder why you don't have to pass a parameter to the function (the 'self' param). It is because the instance on which you call the function is actually passed as the first parameter.
That is, MyClass.f(m) equals m.f(), where m is an instance object of class MyClass.
Good luck!
|
Python newbie having a problem using classes
|
Im just beginning to mess around a bit with classes; however, I am running across a problem.
class MyClass(object):
def f(self):
return 'hello world'
print MyClass.f
The previous script is returning <unbound method MyClass.f> instead of the intended value. How do I fix this?
|
[
"MyClass.f refers to the function object f which is a property of MyClass. In your case, f is an instance method (has a self parameter) so its called on a particular instance. Its \"unbound\" because you're referring to f without specifying a specific class, kind of like referring to a steering wheel without a car.\nYou can create an instance of MyClass and call f from it like so: \nx = MyClass()\nx.f()\n\n(This specifies which instance to call f from, so you can refer to instance variables and the like.) \nYou're using f as a static method. These methods aren't bound to a particular class, and can only reference their parameters.\nA static method would be created and used like so:\nclass MyClass(object):\n def f(): #no self parameter\n return 'hello world'\nprint MyClass.f()\n\n",
"Create an instance of your class: m = MyClass()\nthen use m.f() to call the function\nNow you may wonder why you don't have to pass a parameter to the function (the 'self' param). It is because the instance on which you call the function is actually passed as the first parameter.\nThat is, MyClass.f(m) equals m.f(), where m is an instance object of class MyClass.\nGood luck!\n"
] |
[
13,
6
] |
[] |
[] |
[
"class",
"python"
] |
stackoverflow_0002232740_class_python.txt
|
Q:
How to include in code an unique ID related to a mercurial commit?
I'd like to do the same thing that they're doing here in stackoverflow.
<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6274">
<script type="text/javascript" src="http://sstatic.net/so/js/master.js?v=6180"></script>
<script src="http://sstatic.net/so/js/question.js?v=6274" type="text/javascript"></script>
Do you see those ?v=... ?
I'd like, at each commit, to change some variable in my code in order to make browsers refresh their cache when needed.
It may be even just one for each commit (it doesn't need to monitor each file in an independent way) but I'd like it to be automatically generated when I commit.
The difference is that I'm using mercurial and not subversion. Any hint?
A:
KeywordExtension will let you put a keyword in a file whose results you can tear apart in order to get the hash.
|
How to include in code an unique ID related to a mercurial commit?
|
I'd like to do the same thing that they're doing here in stackoverflow.
<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6274">
<script type="text/javascript" src="http://sstatic.net/so/js/master.js?v=6180"></script>
<script src="http://sstatic.net/so/js/question.js?v=6274" type="text/javascript"></script>
Do you see those ?v=... ?
I'd like, at each commit, to change some variable in my code in order to make browsers refresh their cache when needed.
It may be even just one for each commit (it doesn't need to monitor each file in an independent way) but I'd like it to be automatically generated when I commit.
The difference is that I'm using mercurial and not subversion. Any hint?
|
[
"KeywordExtension will let you put a keyword in a file whose results you can tear apart in order to get the hash.\n"
] |
[
4
] |
[] |
[] |
[
"caching",
"django",
"mercurial",
"python"
] |
stackoverflow_0002232852_caching_django_mercurial_python.txt
|
Q:
Compiling Mysqldb for jython 2.5 on Solaris
I have used python2.6 + MySQL on Windows and there are binaries available.
I wanted to get the whole thing working on Solaris
Hence got the Mysql-Python package from here
I had to get the setuptools installed which is done.
Exploded the MySQL-python-1.2.3c1
When I this
/jython2.5.1/jython setup.py build
Error -
`File "/opt/somepath/MySQL-python-1.2.3c1/setup_windows.py", line 2, in get_config
import os, sys, _winreg
ImportError: No module named _winreg`
I don't understand why it would require windows.py. Either I'm using the incorrect code or I'm not passing the correct flags. Or I'm going on a tangent somewhere else 8-)
Sorry, this is the first time I'm compiling something like a driver on Solaris.
Any suggestions are appreciated.
Jython : 2.5.1
Solaris : 5.9
MySQL - 5.1.42
A:
You should be using zxJDBC and JDBC instead of an external DB-API adapter.
|
Compiling Mysqldb for jython 2.5 on Solaris
|
I have used python2.6 + MySQL on Windows and there are binaries available.
I wanted to get the whole thing working on Solaris
Hence got the Mysql-Python package from here
I had to get the setuptools installed which is done.
Exploded the MySQL-python-1.2.3c1
When I this
/jython2.5.1/jython setup.py build
Error -
`File "/opt/somepath/MySQL-python-1.2.3c1/setup_windows.py", line 2, in get_config
import os, sys, _winreg
ImportError: No module named _winreg`
I don't understand why it would require windows.py. Either I'm using the incorrect code or I'm not passing the correct flags. Or I'm going on a tangent somewhere else 8-)
Sorry, this is the first time I'm compiling something like a driver on Solaris.
Any suggestions are appreciated.
Jython : 2.5.1
Solaris : 5.9
MySQL - 5.1.42
|
[
"You should be using zxJDBC and JDBC instead of an external DB-API adapter.\n"
] |
[
1
] |
[] |
[] |
[
"driver",
"jython",
"mysql",
"python",
"solaris"
] |
stackoverflow_0002233422_driver_jython_mysql_python_solaris.txt
|
Q:
Python - letter frequency count and translation
I am using Python 3.1, but I can downgrade if needed.
I have an ASCII file containing a short story written in one of the languages the alphabet of which can be represented with upper and or lower ASCII. I wish to:
1) Detect an encoding to the best of my abilities, get some sort of confidence metric (would vary depending on the length of the file, right?)
2) Automatically translate the whole thing using some free online service or a library.
Additional question: What if the text is written in a language where it takes 2 or more bytes to represent one letter and the byte order mark is not there to help me?
Finally, how do I deal with punctuation and misc characters such as space? It will occur more frequently than some letters, right? How about the fact that punctuation and characters can be sometimes mixed - there might be two representations of a comma, two representations for what looks like an "a", etc.?
Yes, I have read the article by Joel Spolsky on Unicode. Please help me with at least some of these items.
Thank you!
P.S. This is not a homework, but it is for self-educational purposes. I prefer using a letter frequency library that is open-source and readable as opposed to the one that is closed, efficient, but gets the job done well.
A:
Essentially there are three main tasks to implement the described application:
1a) Identify the character encoding of the input text
1b) Identify the language of the input text
2) Get the text translated the text, by way of one of the online services' API
For 1a, you may want to take a look at decodeh.py, aside from the script itself, it provides many very useful resources regarding character sets and encoding at large. CharDet, mentioned in other answer also seems to be worthy of consideration.
Once the character encoding is known, as you suggest, you may solve 1b) by calculating the character frequency profile of the text, and matching it with known frequencies. While simple, this approach typically provide a decent precision ratio, although it may be weak on shorter texts and also on texts which follow particular patterns; for example a text in French with many references to units in the metric system will have an unusually high proportion of the letters M, K and C.
A complementary and very similar approach, use bi-grams (sequences of two letters) and tri-grams (three letters) and the corresponding tables of frequency distribution references in various languages.
Other language detection methods involve tokenizing the text, i.e. considering the words within the text. NLP resources include tables with the most used words in various languages. Such words are typically articles, possessive adjectives, adverbs and the like.
An alternative solution to the language detection is to rely on the online translation service to figure this out for us. What is important is to supply the translation service with text in a character encoding it understands, providing it the language may be superfluous.
Finally, as many practical NLP applications, you may decide to implement multiple solutions. By using a strategy design pattern, one can apply several filters/classifiers/steps in a particular order, and exit this logic at different points depending on the situation. For example, if a simple character/bigram frequency matches the text to English (with a small deviation), one may just stop there. Otherwise, if the guessed language is French or German, perform another test, etc. etc.
A:
If you have an ASCII file then I can tell you with 100% confidence that it is encoded in ASCII. Beyond that try chardet. But knowing the encoding isn't necessarily enough to determine what language it's in.
As for multibyte encodings, The only reliable way to handle it is to hope that it has characters in the Latin alphabet and look for which half of the pair has the NULL. Otherwise treat it as UTF-8 unless you know better (Shift-JIS, GB2312, etc.).
Oh, and UTF-8. UTF-8, UTF-8, UTF-8. I don't think I can stress that enough. And in case I haven't... UTF-8.
A:
Character frequency is pretty straight forward
I just noticed that you are using Python3.1 so this is even easier
>>> from collections import Counter
>>> Counter("Μεταλλικα")
Counter({'α': 2, 'λ': 2, 'τ': 1, 'ε': 1, 'ι': 1, 'κ': 1, 'Μ': 1})
For older versions of Python:
>>> from collections import defaultdict
>>> letter_freq=defaultdict(int)
>>> unistring = "Μεταλλικα"
>>> for uc in unistring: letter_freq[uc]+=1
...
>>> letter_freq
defaultdict(<class 'int'>, {'τ': 1, 'α': 2, 'ε': 1, 'ι': 1, 'λ': 2, 'κ': 1, 'Μ': 1})
A:
I have provided some conditional answers however your question is a little vague and inconsistent. Please edit your question to provide answers to my questions below.
(1) You say that the file is ASCII but you want to detect an encoding? Huh? Isn't the answer "ascii"?? If you really need to detect an encoding, use chardet
(2) Automatically translate what? encoding? language? If language, do you know what the input language is or are you trying to detect that also? To detect language, try guess-language ... note that it needs a tweak for better detection of Japanese. See this SO topic which notes the Japanese problem and also highlights that for ANY language-guesser, you need to remove all HTML/XML/Javascript/etc noise from your text otherwise it will heavily bias the result towards ASCII-only languages like English (or Catalan!).
(3) You are talking about a "letter-frequency library" ... you are going to use this library to do what? If language guessing, it appears that using frequency of single letters is not much help distinguishing between languages which use the same (or almost the same) character set; one needs to use the frequency of three-letter groups ("trigrams").
(4) Your questions on punctuation and spaces: depends on your purpose (which we are not yet sure of). If purpose is language detection, the idea is to standardise the text; e.g. replace all runs of not (letter or apostrophe) with a single space, then remove any leading/trailing whitespace, than add 1 leading and 1 trailing space -- more precision is gained by treating start/end of word bigrams as trigrams. Note that as usual in all text processing you should decode your input into unicode immediately and work with unicode thereafter.
|
Python - letter frequency count and translation
|
I am using Python 3.1, but I can downgrade if needed.
I have an ASCII file containing a short story written in one of the languages the alphabet of which can be represented with upper and or lower ASCII. I wish to:
1) Detect an encoding to the best of my abilities, get some sort of confidence metric (would vary depending on the length of the file, right?)
2) Automatically translate the whole thing using some free online service or a library.
Additional question: What if the text is written in a language where it takes 2 or more bytes to represent one letter and the byte order mark is not there to help me?
Finally, how do I deal with punctuation and misc characters such as space? It will occur more frequently than some letters, right? How about the fact that punctuation and characters can be sometimes mixed - there might be two representations of a comma, two representations for what looks like an "a", etc.?
Yes, I have read the article by Joel Spolsky on Unicode. Please help me with at least some of these items.
Thank you!
P.S. This is not a homework, but it is for self-educational purposes. I prefer using a letter frequency library that is open-source and readable as opposed to the one that is closed, efficient, but gets the job done well.
|
[
"Essentially there are three main tasks to implement the described application:\n\n1a) Identify the character encoding of the input text\n1b) Identify the language of the input text\n2) Get the text translated the text, by way of one of the online services' API\n\nFor 1a, you may want to take a look at decodeh.py, aside from the script itself, it provides many very useful resources regarding character sets and encoding at large. CharDet, mentioned in other answer also seems to be worthy of consideration.\nOnce the character encoding is known, as you suggest, you may solve 1b) by calculating the character frequency profile of the text, and matching it with known frequencies. While simple, this approach typically provide a decent precision ratio, although it may be weak on shorter texts and also on texts which follow particular patterns; for example a text in French with many references to units in the metric system will have an unusually high proportion of the letters M, K and C.\nA complementary and very similar approach, use bi-grams (sequences of two letters) and tri-grams (three letters) and the corresponding tables of frequency distribution references in various languages.\nOther language detection methods involve tokenizing the text, i.e. considering the words within the text. NLP resources include tables with the most used words in various languages. Such words are typically articles, possessive adjectives, adverbs and the like.\nAn alternative solution to the language detection is to rely on the online translation service to figure this out for us. What is important is to supply the translation service with text in a character encoding it understands, providing it the language may be superfluous.\nFinally, as many practical NLP applications, you may decide to implement multiple solutions. By using a strategy design pattern, one can apply several filters/classifiers/steps in a particular order, and exit this logic at different points depending on the situation. For example, if a simple character/bigram frequency matches the text to English (with a small deviation), one may just stop there. Otherwise, if the guessed language is French or German, perform another test, etc. etc.\n",
"If you have an ASCII file then I can tell you with 100% confidence that it is encoded in ASCII. Beyond that try chardet. But knowing the encoding isn't necessarily enough to determine what language it's in.\nAs for multibyte encodings, The only reliable way to handle it is to hope that it has characters in the Latin alphabet and look for which half of the pair has the NULL. Otherwise treat it as UTF-8 unless you know better (Shift-JIS, GB2312, etc.).\nOh, and UTF-8. UTF-8, UTF-8, UTF-8. I don't think I can stress that enough. And in case I haven't... UTF-8.\n",
"Character frequency is pretty straight forward\nI just noticed that you are using Python3.1 so this is even easier\n>>> from collections import Counter\n>>> Counter(\"Μεταλλικα\")\nCounter({'α': 2, 'λ': 2, 'τ': 1, 'ε': 1, 'ι': 1, 'κ': 1, 'Μ': 1})\n\nFor older versions of Python:\n>>> from collections import defaultdict\n>>> letter_freq=defaultdict(int)\n>>> unistring = \"Μεταλλικα\"\n>>> for uc in unistring: letter_freq[uc]+=1\n... \n>>> letter_freq\ndefaultdict(<class 'int'>, {'τ': 1, 'α': 2, 'ε': 1, 'ι': 1, 'λ': 2, 'κ': 1, 'Μ': 1})\n\n",
"I have provided some conditional answers however your question is a little vague and inconsistent. Please edit your question to provide answers to my questions below. \n(1) You say that the file is ASCII but you want to detect an encoding? Huh? Isn't the answer \"ascii\"?? If you really need to detect an encoding, use chardet\n(2) Automatically translate what? encoding? language? If language, do you know what the input language is or are you trying to detect that also? To detect language, try guess-language ... note that it needs a tweak for better detection of Japanese. See this SO topic which notes the Japanese problem and also highlights that for ANY language-guesser, you need to remove all HTML/XML/Javascript/etc noise from your text otherwise it will heavily bias the result towards ASCII-only languages like English (or Catalan!).\n(3) You are talking about a \"letter-frequency library\" ... you are going to use this library to do what? If language guessing, it appears that using frequency of single letters is not much help distinguishing between languages which use the same (or almost the same) character set; one needs to use the frequency of three-letter groups (\"trigrams\").\n(4) Your questions on punctuation and spaces: depends on your purpose (which we are not yet sure of). If purpose is language detection, the idea is to standardise the text; e.g. replace all runs of not (letter or apostrophe) with a single space, then remove any leading/trailing whitespace, than add 1 leading and 1 trailing space -- more precision is gained by treating start/end of word bigrams as trigrams. Note that as usual in all text processing you should decode your input into unicode immediately and work with unicode thereafter.\n"
] |
[
3,
2,
2,
1
] |
[] |
[] |
[
"character_encoding",
"nlp",
"python",
"translation"
] |
stackoverflow_0002233355_character_encoding_nlp_python_translation.txt
|
Q:
How to delete list elements while cycling the list itself without duplicate it
I lost a little bit of time in this Python for statement:
class MyListContainer:
def __init__(self):
self.list = []
def purge(self):
for object in self.list:
if (object.my_cond()):
self.list.remove(object)
return self.list
container = MyListContainer()
# now suppose both obj.my_cond() return True
obj1 = MyCustomObject(par)
obj2 = MyCustomObject(other_par)
container.list = [obj1, obj2]
# returning not an empty list but [obj2]
container.purge()
It doesn't work as I expected because when the cycle in "purge" delete the first object in list the second one is shifted to the beginning of the list and the cycle is ended.
I solved duplicating self.list before the for cycle:
...
local_list = self.list[:]
for object in local_list:
...
I suppose that the for statement stop working because I'm changing the length of the original list. Can someone clarify this point ?
And is there a more "elegant" way to solve this problem ? If I have more than few elements inside the list, duplicating it every time does not seem a good idea.
Maybe the filter() function is the right one but i whish to have some other approach if any.
I'm a newbie.
To summarize your useful answers:
Never edit a list you are looping
Duplicate the list or use list comprehensions
Duplicating a list could not waste your memory or in this case who's mind about it
A:
Don't try. Just don't. Make a copy or generate a new list.
A:
Just make yourself a new list:
def purge(self):
self.list = [object for object in self.list if not object.my_cond()]
return self.list
Reserve any optimization until you've profiled and found that this method really is the bottleneck of your application. (I bet it won't be.)
A:
In python variables are actually labels to data. Duplicating a list is, for the most part, making a new set of pointers to the data from the first list. Don't feel too bad about it.
List comprehensions are your friend.
e.g.
>>> a = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [ x for x in a if x % 2 == 0 ]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
A:
Filter (or list comprehension) IS the way to go. If you want to do it inplace, something like this would work:
purge = []
for i,object in enumerate(self.list):
if object.mycond()
purge.append(i)
for i in reversed(purge):
del self.list[i]
Or alternatively, the purge list can be made with a comprehension, a shortcut version looks like:
for i in reversed([ i for (i,o) in enumerate(self.list) if o.mycond() ]):
del self.list[i]
A:
Your second solution in which you duplicate the list is the right way to go. Afterward you can just replace the old list with the duplicate if need be.
A:
It's perfectly safe to shorten the list in place if you do it in reverse!
>>> a=range(20)
>>> for i in reversed(range(len(a))):
... if a[i]%2: del a[i]
...
>>> a
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Another way is to reassign the whole slice
>>> a=range(20)
>>> a[:]=(x for x in a if not x%2)
>>> a
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
If the items in the list are unique, this works too
>>> a=range(20)
>>> for item in reversed(a):
... if item%2: a.remove(item)
...
>>> a
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Here is some more explanation in response to yuri's comment
Suppose we have
>>> a=[0,1,2,3,4,5]
Now trying naively to delete the 3rd and 4th items
>>> del a[3]
>>> del a[4]
>>> a
[0, 1, 2, 4] # didn't work because the position of all the item with index >=3 was changed
However if we do the del's in the opposite order
>>> a=[0,1,2,3,4,5]
>>> del a[4]
>>> del a[3]
>>> a
[0, 1, 2, 5] # this is the desired result
Now extend that idea over a for loop with a removal condition, and you see that removal from the live list is possible
|
How to delete list elements while cycling the list itself without duplicate it
|
I lost a little bit of time in this Python for statement:
class MyListContainer:
def __init__(self):
self.list = []
def purge(self):
for object in self.list:
if (object.my_cond()):
self.list.remove(object)
return self.list
container = MyListContainer()
# now suppose both obj.my_cond() return True
obj1 = MyCustomObject(par)
obj2 = MyCustomObject(other_par)
container.list = [obj1, obj2]
# returning not an empty list but [obj2]
container.purge()
It doesn't work as I expected because when the cycle in "purge" delete the first object in list the second one is shifted to the beginning of the list and the cycle is ended.
I solved duplicating self.list before the for cycle:
...
local_list = self.list[:]
for object in local_list:
...
I suppose that the for statement stop working because I'm changing the length of the original list. Can someone clarify this point ?
And is there a more "elegant" way to solve this problem ? If I have more than few elements inside the list, duplicating it every time does not seem a good idea.
Maybe the filter() function is the right one but i whish to have some other approach if any.
I'm a newbie.
To summarize your useful answers:
Never edit a list you are looping
Duplicate the list or use list comprehensions
Duplicating a list could not waste your memory or in this case who's mind about it
|
[
"Don't try. Just don't. Make a copy or generate a new list.\n",
"Just make yourself a new list:\ndef purge(self):\n self.list = [object for object in self.list if not object.my_cond()]\n return self.list\n\nReserve any optimization until you've profiled and found that this method really is the bottleneck of your application. (I bet it won't be.)\n",
"In python variables are actually labels to data. Duplicating a list is, for the most part, making a new set of pointers to the data from the first list. Don't feel too bad about it.\nList comprehensions are your friend.\ne.g.\n>>> a = range(20)\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n>>> [ x for x in a if x % 2 == 0 ]\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n\n",
"Filter (or list comprehension) IS the way to go. If you want to do it inplace, something like this would work:\npurge = []\nfor i,object in enumerate(self.list):\n if object.mycond()\n purge.append(i)\nfor i in reversed(purge):\n del self.list[i]\n\nOr alternatively, the purge list can be made with a comprehension, a shortcut version looks like:\nfor i in reversed([ i for (i,o) in enumerate(self.list) if o.mycond() ]):\n del self.list[i]\n\n",
"Your second solution in which you duplicate the list is the right way to go. Afterward you can just replace the old list with the duplicate if need be.\n",
"It's perfectly safe to shorten the list in place if you do it in reverse!\n>>> a=range(20)\n>>> for i in reversed(range(len(a))):\n... if a[i]%2: del a[i]\n... \n>>> a\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n\nAnother way is to reassign the whole slice\n>>> a=range(20)\n>>> a[:]=(x for x in a if not x%2)\n>>> a\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n\nIf the items in the list are unique, this works too\n>>> a=range(20)\n>>> for item in reversed(a):\n... if item%2: a.remove(item)\n... \n>>> a\n[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n\nHere is some more explanation in response to yuri's comment\nSuppose we have\n>>> a=[0,1,2,3,4,5]\n\nNow trying naively to delete the 3rd and 4th items\n>>> del a[3]\n>>> del a[4]\n>>> a\n[0, 1, 2, 4] # didn't work because the position of all the item with index >=3 was changed\n\nHowever if we do the del's in the opposite order\n>>> a=[0,1,2,3,4,5]\n>>> del a[4]\n>>> del a[3]\n>>> a\n[0, 1, 2, 5] # this is the desired result\n\nNow extend that idea over a for loop with a removal condition, and you see that removal from the live list is possible\n"
] |
[
5,
3,
2,
2,
0,
0
] |
[
"indeces = []\nminus = 0\n\nfor i in range(self.list):\n if cond(self.list[i]):\n indeces.append(i)\n\nfor i in indeces:\n self.list = self.list[:(i-minus)].extend(self.list[i-minus+1:])\n\n"
] |
[
-1
] |
[
"cycle",
"list",
"python"
] |
stackoverflow_0002233388_cycle_list_python.txt
|
Q:
Can I port my existing python apps on ASE?
I learned that the Android Scripting Environment (ASE) supports python code. Can I take my existing python programs and run them on android?
Apart from the GUI, what else will I need to adapt? How can I find the list of supported python libraries for ASE?
A:
As of yet, there is no support for a gui on ASE apart from some simple input and display dialogs. Look at /sdcard/ase/extras/python to find libraries already available. You can add new libraries by copying them there.
|
Can I port my existing python apps on ASE?
|
I learned that the Android Scripting Environment (ASE) supports python code. Can I take my existing python programs and run them on android?
Apart from the GUI, what else will I need to adapt? How can I find the list of supported python libraries for ASE?
|
[
"As of yet, there is no support for a gui on ASE apart from some simple input and display dialogs. Look at /sdcard/ase/extras/python to find libraries already available. You can add new libraries by copying them there.\n"
] |
[
4
] |
[] |
[] |
[
"android",
"android_scripting",
"ase",
"python"
] |
stackoverflow_0002233631_android_android_scripting_ase_python.txt
|
Q:
How do I prevent duplicating code with pylons html table updated via ajax?
I have a pylons web-page with a table. I have created python functions in the template which help with the construction of the table html. One of these functions takes an 'item' and generates an html row while also adding css zebra striping. The other def generates the header row's html.
This works perfectly for loading the initial table using the context variable 'items'. However, when I try to update the table via ajax, I pull new table contents off the server in JSON format. My 'items' are then Javascript objects in a Javascript array. I can no longer use the pylons 'getHeaderHtml()' and 'getRowHtml(item)'. So the handling of my zebra striping as well as the formatting of the html must be duplicated? There has to be a better way, right?
A:
One possibility would be to actually generate the AJAX HTML server-side (instead of generating JSON), and insert it right into the DOM tree (instead of parsing the JSON and generating the HTML on the client). Then you could use the same functions on the server side to generate the AJAX rows before they are shipped off. An advantage here is that you don't have to worry about parsing anything in the browser, so the JavaScript could become much simpler, and potentially faster.
|
How do I prevent duplicating code with pylons html table updated via ajax?
|
I have a pylons web-page with a table. I have created python functions in the template which help with the construction of the table html. One of these functions takes an 'item' and generates an html row while also adding css zebra striping. The other def generates the header row's html.
This works perfectly for loading the initial table using the context variable 'items'. However, when I try to update the table via ajax, I pull new table contents off the server in JSON format. My 'items' are then Javascript objects in a Javascript array. I can no longer use the pylons 'getHeaderHtml()' and 'getRowHtml(item)'. So the handling of my zebra striping as well as the formatting of the html must be duplicated? There has to be a better way, right?
|
[
"One possibility would be to actually generate the AJAX HTML server-side (instead of generating JSON), and insert it right into the DOM tree (instead of parsing the JSON and generating the HTML on the client). Then you could use the same functions on the server side to generate the AJAX rows before they are shipped off. An advantage here is that you don't have to worry about parsing anything in the browser, so the JavaScript could become much simpler, and potentially faster.\n"
] |
[
1
] |
[] |
[] |
[
"ajax",
"html_table",
"pylons",
"python"
] |
stackoverflow_0002234153_ajax_html_table_pylons_python.txt
|
Q:
how do I iterate over a "gslist" in Python?
Let's say I get a glib gpointer to a glib gslist and would like to iterate over the latter, how would I do it?
I don't even know how to get to the gslist with the gpointer for starters!
Update: I found a workaround - the python bindings in this instance wasn't complete so I had to find another solution.
A:
How is glib exposed to Python in your application? Via SWIG, ctypes or something else?
You should basically use glib's own functions to iterate over a list. Something like g_slist_foreach. Just pass it the pointer and its other parameters to do the job. Again, this heavily depends on how you access glib in your Python application.
|
how do I iterate over a "gslist" in Python?
|
Let's say I get a glib gpointer to a glib gslist and would like to iterate over the latter, how would I do it?
I don't even know how to get to the gslist with the gpointer for starters!
Update: I found a workaround - the python bindings in this instance wasn't complete so I had to find another solution.
|
[
"How is glib exposed to Python in your application? Via SWIG, ctypes or something else? \nYou should basically use glib's own functions to iterate over a list. Something like g_slist_foreach. Just pass it the pointer and its other parameters to do the job. Again, this heavily depends on how you access glib in your Python application.\n"
] |
[
0
] |
[] |
[] |
[
"glib",
"python"
] |
stackoverflow_0002234056_glib_python.txt
|
Q:
building dynamic forms in django
I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label.
How do I build a form dynamically in my view from the data in the db?
Thanks
A:
Here are the slides from a talk I gave at EuroDjangoCon about doing precisely this: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth
A:
Django does a great job auto-generating forms from your model definitions.
The first step might be to create a Django model that mirrors your existing database.
Regarding the checkbox/textfield stuff:
Django has a great separation between fields and widgets. You may have a IntegerField that stores numbers, but you can vary the widget that is displayed to the user when they want to edit that number. In some cases you might have an input box, in others a textarea, or perhaps a dropdown. The field will take care of details such as type conversion and validation, the widget determines what the form field looks like.
Certain field types have default widgets associated with them, but you can override them.
Also, note that there is a difference between form fields and model fields.
To do it dynamically, can add items to the self.fields SortedDict on the fly. I.E:
from django.forms.forms import Form
from django.forms.fields import CharField
class FunkyForm(Form):
def __init__(self, *args, **kwargs):
super(FunkyForm, self).__init__(*args, **kwargs)
for item in range(5):
self.fields['test_field_%s' % item] = CharField(max_length=255)
Will give a you a form class that instantiates with 5 dynamically generated CharFields.
|
building dynamic forms in django
|
I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label.
How do I build a form dynamically in my view from the data in the db?
Thanks
|
[
"Here are the slides from a talk I gave at EuroDjangoCon about doing precisely this: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth\n",
"Django does a great job auto-generating forms from your model definitions.\nThe first step might be to create a Django model that mirrors your existing database.\nRegarding the checkbox/textfield stuff:\nDjango has a great separation between fields and widgets. You may have a IntegerField that stores numbers, but you can vary the widget that is displayed to the user when they want to edit that number. In some cases you might have an input box, in others a textarea, or perhaps a dropdown. The field will take care of details such as type conversion and validation, the widget determines what the form field looks like.\nCertain field types have default widgets associated with them, but you can override them.\nAlso, note that there is a difference between form fields and model fields.\n\nTo do it dynamically, can add items to the self.fields SortedDict on the fly. I.E:\nfrom django.forms.forms import Form\nfrom django.forms.fields import CharField\nclass FunkyForm(Form):\n def __init__(self, *args, **kwargs):\n super(FunkyForm, self).__init__(*args, **kwargs)\n for item in range(5):\n self.fields['test_field_%s' % item] = CharField(max_length=255)\n\nWill give a you a form class that instantiates with 5 dynamically generated CharFields. \n"
] |
[
11,
5
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002234117_django_django_forms_python.txt
|
Q:
Can I catch error in a list comprehensions to be sure to loop all the list items
I've got a list comprehensions which filter a list:
l = [obj for obj in objlist if not obj.mycond()]
but the object method mycond() can raise an Exception I must intercept. I need to collect all the errors at the end of the loop to show which object has created any problems and at the same time I want to be sure to loop all the list elements.
My solution was:
errors = []
copy = objlist[:]
for obj in copy:
try:
if (obj.mycond()):
# avoiding to touch the list in the loop directly
objlist.remove(obj)
except MyException as err:
errors = [err]
if (errors):
#do something
return objlist
In this post (How to delete list elements while cycling the list itself without duplicate it) I ask if there is a better method to cycle avoiding the list duplicate.
The community answer me to avoid in place list modification and use a list comprehensions that is applicable if I ignore the Exception problem.
Is there an alternative solution in your point of view ? Can I manage Exception in that manner using list comprehensions? In this kind of situation and using big lists (what I must consider big ?) I must find another alternative ?
A:
I would use a little auxiliary function:
def f(obj, errs):
try: return not obj.mycond()
except MyException as err: errs.append((obj, err))
errs = []
l = [obj for obj in objlist if f(obj, errs)]
if errs:
emiterrorinfo(errs)
Note that this way you have in errs all the errant objects and the specific exception corresponding to each of them, so the diagnosis can be precise and complete; as well as the l you require, and your objlist still intact for possible further use. No list copy was needed, nor any changes to obj's class, and the code's overall structure is very simple.
A:
A couple of comments:
First of all, the list comprehension syntax [expression for var in iterable] DOES create a copy. If you do not want to create a copy of the list, then use the generator expression (expression for var in iterable).
How do generators work? Essentially by calling next(obj) on the object repeatedly until a GeneratorExit exception is raised.
Based on your original code, it seems that you are still needing the filtered list as output.
So you can emulate that with little performance loss:
l = []
for obj in objlist:
try:
if not obj.mycond()
l.append(obj)
except Exception:
pass
However, you could re-engineer that all with a generator function:
def FilterObj(objlist):
for obj in objlist:
try:
if not obj.mycond()
yield obj
except Exception:
pass
In that way, you can safely iterate over it without caching a list in the meantime:
for obj in FilterObj(objlist):
obj.whatever()
A:
Instead of copying the list and removing elements, start with a blank list and add members as necessary. Something like this:
errors = []
newlist = []
for obj in objlist:
try:
if not obj.mycond():
newlist.append(obj)
except MyException as err:
errors.append(err)
if (errors):
#do something
return newlist
The syntax isn't as pretty, but it'll do more or less the same thing that the list comprehension does without any unnecessary removals.
Adding or removing elements to or from anywhere other than the end of a list will be slow because when you remove something, it needs to go through every item that comes after it and subtract one from its index, and same thing for adding something except it'll need to add to the index. update the position of all the elements after it.
A:
you could define a method of obj that calls obj.mycond() but also catches the exception
class obj:
def __init__(self):
self.errors = []
def mycond(self):
#whatever you have here
def errorcatcher():
try:
return self.mycond()
except MyException as err:
self.errors.append(err)
return False # or true, depending upon what you want
l = [obj for obj in objlist if not obj.errorcatcher()]
errors = [obj.errors for obj in objlist if obj.errors]
if errors:
#do something
|
Can I catch error in a list comprehensions to be sure to loop all the list items
|
I've got a list comprehensions which filter a list:
l = [obj for obj in objlist if not obj.mycond()]
but the object method mycond() can raise an Exception I must intercept. I need to collect all the errors at the end of the loop to show which object has created any problems and at the same time I want to be sure to loop all the list elements.
My solution was:
errors = []
copy = objlist[:]
for obj in copy:
try:
if (obj.mycond()):
# avoiding to touch the list in the loop directly
objlist.remove(obj)
except MyException as err:
errors = [err]
if (errors):
#do something
return objlist
In this post (How to delete list elements while cycling the list itself without duplicate it) I ask if there is a better method to cycle avoiding the list duplicate.
The community answer me to avoid in place list modification and use a list comprehensions that is applicable if I ignore the Exception problem.
Is there an alternative solution in your point of view ? Can I manage Exception in that manner using list comprehensions? In this kind of situation and using big lists (what I must consider big ?) I must find another alternative ?
|
[
"I would use a little auxiliary function:\ndef f(obj, errs):\n try: return not obj.mycond()\n except MyException as err: errs.append((obj, err))\n\nerrs = []\nl = [obj for obj in objlist if f(obj, errs)]\nif errs:\n emiterrorinfo(errs)\n\nNote that this way you have in errs all the errant objects and the specific exception corresponding to each of them, so the diagnosis can be precise and complete; as well as the l you require, and your objlist still intact for possible further use. No list copy was needed, nor any changes to obj's class, and the code's overall structure is very simple.\n",
"A couple of comments:\nFirst of all, the list comprehension syntax [expression for var in iterable] DOES create a copy. If you do not want to create a copy of the list, then use the generator expression (expression for var in iterable).\nHow do generators work? Essentially by calling next(obj) on the object repeatedly until a GeneratorExit exception is raised.\nBased on your original code, it seems that you are still needing the filtered list as output.\nSo you can emulate that with little performance loss:\nl = []\nfor obj in objlist:\n try:\n if not obj.mycond()\n l.append(obj)\n except Exception:\n pass\n\nHowever, you could re-engineer that all with a generator function:\ndef FilterObj(objlist):\n for obj in objlist:\n try:\n if not obj.mycond()\n yield obj\n except Exception:\n pass\n\nIn that way, you can safely iterate over it without caching a list in the meantime:\nfor obj in FilterObj(objlist):\n obj.whatever()\n\n",
"Instead of copying the list and removing elements, start with a blank list and add members as necessary. Something like this:\nerrors = []\nnewlist = []\n\nfor obj in objlist:\n try:\n if not obj.mycond():\n newlist.append(obj)\n except MyException as err:\n errors.append(err)\nif (errors):\n #do something\n\nreturn newlist\n\nThe syntax isn't as pretty, but it'll do more or less the same thing that the list comprehension does without any unnecessary removals. \nAdding or removing elements to or from anywhere other than the end of a list will be slow because when you remove something, it needs to go through every item that comes after it and subtract one from its index, and same thing for adding something except it'll need to add to the index. update the position of all the elements after it.\n",
"you could define a method of obj that calls obj.mycond() but also catches the exception\nclass obj:\n\n def __init__(self):\n self.errors = []\n\n def mycond(self):\n #whatever you have here\n\n def errorcatcher():\n try:\n return self.mycond()\n except MyException as err:\n self.errors.append(err)\n return False # or true, depending upon what you want\n\nl = [obj for obj in objlist if not obj.errorcatcher()]\n\nerrors = [obj.errors for obj in objlist if obj.errors]\n\nif errors:\n #do something\n\n"
] |
[
9,
1,
0,
0
] |
[] |
[] |
[
"cycle",
"exception",
"list",
"python"
] |
stackoverflow_0002233975_cycle_exception_list_python.txt
|
Q:
Where do stdout and stderr go when in curses mode?
Where do stdout and stderr go when curses is active?
import curses, sys
def test_streams():
print "stdout"
print >>sys.stderr, "stderr"
def curses_mode(stdscr):
test_streams()
test_streams()
curses.wrapper(curses_mode)
Actual output is
stdout
stderr
Update0
Expected output is
stdout
stderr
stdout
stderr
entering, and then exiting curses mode with no change to the final text shown in the terminal.
A:
Activating curses saves the terminal text screen's current contents and clears said screen; exiting curses restores the screen's contents (tossing away whatever's been put on screen during the reign of curses itself). Try with this variant of your code and you'll see better what's happening:
import curses, sys, time
def test_streams(wot):
print wot, "stdout"
print >>sys.stderr, wot, "stderr"
def curses_mode(stdscr):
test_streams("wrap")
time.sleep(1.0)
test_streams("before")
curses.wrapper(curses_mode)
test_streams("after")
You'll note the wrap stderr on the screen for a second (during the sleep) -- it's overwritten the stdout part -- then it disappears and you see the four before and after lines on the now-quiescent screen (you can add other sleeps to follow what's happening in even more details, if you care).
|
Where do stdout and stderr go when in curses mode?
|
Where do stdout and stderr go when curses is active?
import curses, sys
def test_streams():
print "stdout"
print >>sys.stderr, "stderr"
def curses_mode(stdscr):
test_streams()
test_streams()
curses.wrapper(curses_mode)
Actual output is
stdout
stderr
Update0
Expected output is
stdout
stderr
stdout
stderr
entering, and then exiting curses mode with no change to the final text shown in the terminal.
|
[
"Activating curses saves the terminal text screen's current contents and clears said screen; exiting curses restores the screen's contents (tossing away whatever's been put on screen during the reign of curses itself). Try with this variant of your code and you'll see better what's happening:\nimport curses, sys, time\n\ndef test_streams(wot):\n print wot, \"stdout\"\n print >>sys.stderr, wot, \"stderr\"\n\ndef curses_mode(stdscr):\n test_streams(\"wrap\")\n time.sleep(1.0)\n\ntest_streams(\"before\")\ncurses.wrapper(curses_mode)\ntest_streams(\"after\")\n\nYou'll note the wrap stderr on the screen for a second (during the sleep) -- it's overwritten the stdout part -- then it disappears and you see the four before and after lines on the now-quiescent screen (you can add other sleeps to follow what's happening in even more details, if you care).\n"
] |
[
6
] |
[] |
[] |
[
"curses",
"ncurses",
"python"
] |
stackoverflow_0002233006_curses_ncurses_python.txt
|
Q:
Django Group By relation's data
In Django,
I can do value(), and then distinct() to group by.
A
{
Foreign Key B
}
B
{
String name
}
However, is it possible to group using a related object's data? I.e. In the above relation, can I group A by B's name?
A:
I think you can order_by on the FKey model.
A.objects.order_by('B__name')
Iff you can't, You need to use the Django ORM's Annotation API, to make a new field and you will be able to order it accordingly:
A.objects.annotate(bname='B__name').order_by('bname')
|
Django Group By relation's data
|
In Django,
I can do value(), and then distinct() to group by.
A
{
Foreign Key B
}
B
{
String name
}
However, is it possible to group using a related object's data? I.e. In the above relation, can I group A by B's name?
|
[
"I think you can order_by on the FKey model.\nA.objects.order_by('B__name')\n\nIff you can't, You need to use the Django ORM's Annotation API, to make a new field and you will be able to order it accordingly:\nA.objects.annotate(bname='B__name').order_by('bname')\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_models",
"group_by",
"python"
] |
stackoverflow_0002234181_django_django_models_group_by_python.txt
|
Q:
Error message in python-mysql cursor: 1054 unknown column "x" in 'field list'
This is my first post! I also just started programming, so please bear with me!
I am trying to load a bunch of .csv files into a database, in order to later perform various reports on the data. I started off by creating a few tables in mysql with matching field names and data types to what will be loaded into the tables. I am manipulating the filename (in order to parse out the date to use as a field in my table) and cleaning up the data with python.
So my problem right now (haha...) is that I get this error message when I attempt the 'Insert Into' query to mysql.
Traceback (most recent call last):
File "C:\Program Files\Python\load_domains2.py", line 80, in <module>
cur.execute(sql)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'a1200e.com' in 'field list'")
'a1200e.com' refers to a specific domain name I'm inserting into that column. My query is as follows:
sql="""INSERT INTO temporary_load
(domain_name, session_count, search_count, click_count,
revenue, revenue_per_min, cost_per_click, traffic_date)
VALUES (%s, %d, %d, %d, %d, %d, %d, %s)""" %(cell[0],
int(cell[1]),
int(cell[2].replace (",","")),
int(cell[3].replace(",","")),
float(cell[4].replace("$","")),
float(cell[5].replace("$","")),
float(cell[6].replace("$","")),
parsed_date)
cur.execute(sql)
I am very new at all this, so I'm sure my code isn't at all efficient, but I just wanted to lay everything out so it's clear to me. What I don't understand is that I have ensured my table has correctly defined data types (corresponding to those in my query). Is there something I'm missing? I've been trying to work this out for a while, and don't know what could be wrong :/
Thanks so much!!!
Val
A:
Thomas is, as usual, absolutely correct: feel free to let MySQLdb handle the quoting issues.
In addition to that recommendation:
The csv module is your friend.
MySQLdb uses the "format" parameter style as detailed in PEP 249.
What does that mean for you?
All parameters, whatever type, should be passed to MySQLdb as strings (like this %s). MySQLdb will make sure that the values are properly converted to SQL literals.
By the way, MySQLdb has some good documentation.
Feel free to include more detail about your source data. That may make diagnosing the problem easier.
Here's one way to insert values to a MySQL database from a .csv file:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import MySQLdb
import os
def main():
db = MySQLdb.connect(db="mydb",passwd="mypasswd",) # connection string
filename = 'data.csv'
f = open(filename, "rb") # open your csv file
reader = csv.reader(f)
# assuming the first line of your csv file has column names
col_names = reader.next() # first line of .csv file
reader = csv.DictReader(f, col_names) # apply column names to row values
to_db = [] # this list holds values you will insert to db
for row in reader: # loop over remaining lines in .csv file
to_db.append((row['col1'],row['col2']))
# or if you prefer one-liners
#to_db = [(row['col1'],row['col2']) for row in reader]
f.close() # we're done with the file now
cursor = db.cursor()
cursor.executemany('''INSERT INTO mytable (col1,col2)
VALUES (%s, %s)''', to_db) # note the two arguments
cursor.close()
db.close()
if __name__ == "__main__":
main()
A:
You should be using DB-API quoting instead of including the data in the SQL query directly:
sql = """INSERT INTO temporary_load
(domain_name, session_count, search_count, click_count,
revenue, revenue_per_min, cost_per_click, traffic_date)
VALUES (%s, %d, %d, %d, %d, %d, %d, %s)"""
args = (cell[0],
int(cell[1]),
int(cell[2].replace (",","")),
int(cell[3].replace(",","")),
float(cell[4].replace("$","")),
float(cell[5].replace("$","")),
float(cell[6].replace("$","")),
parsed_date)
cur.execute(sql, args)
This makes the DB-API module quote the values appropriately, and resolves a whole host of issues that you might get when doing it by hand (and usually incorrectly.)
|
Error message in python-mysql cursor: 1054 unknown column "x" in 'field list'
|
This is my first post! I also just started programming, so please bear with me!
I am trying to load a bunch of .csv files into a database, in order to later perform various reports on the data. I started off by creating a few tables in mysql with matching field names and data types to what will be loaded into the tables. I am manipulating the filename (in order to parse out the date to use as a field in my table) and cleaning up the data with python.
So my problem right now (haha...) is that I get this error message when I attempt the 'Insert Into' query to mysql.
Traceback (most recent call last):
File "C:\Program Files\Python\load_domains2.py", line 80, in <module>
cur.execute(sql)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'a1200e.com' in 'field list'")
'a1200e.com' refers to a specific domain name I'm inserting into that column. My query is as follows:
sql="""INSERT INTO temporary_load
(domain_name, session_count, search_count, click_count,
revenue, revenue_per_min, cost_per_click, traffic_date)
VALUES (%s, %d, %d, %d, %d, %d, %d, %s)""" %(cell[0],
int(cell[1]),
int(cell[2].replace (",","")),
int(cell[3].replace(",","")),
float(cell[4].replace("$","")),
float(cell[5].replace("$","")),
float(cell[6].replace("$","")),
parsed_date)
cur.execute(sql)
I am very new at all this, so I'm sure my code isn't at all efficient, but I just wanted to lay everything out so it's clear to me. What I don't understand is that I have ensured my table has correctly defined data types (corresponding to those in my query). Is there something I'm missing? I've been trying to work this out for a while, and don't know what could be wrong :/
Thanks so much!!!
Val
|
[
"Thomas is, as usual, absolutely correct: feel free to let MySQLdb handle the quoting issues.\nIn addition to that recommendation:\n\nThe csv module is your friend.\nMySQLdb uses the \"format\" parameter style as detailed in PEP 249.\nWhat does that mean for you?\nAll parameters, whatever type, should be passed to MySQLdb as strings (like this %s). MySQLdb will make sure that the values are properly converted to SQL literals.\nBy the way, MySQLdb has some good documentation.\nFeel free to include more detail about your source data. That may make diagnosing the problem easier.\n\nHere's one way to insert values to a MySQL database from a .csv file:\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport csv\nimport MySQLdb\nimport os\n\ndef main():\n db = MySQLdb.connect(db=\"mydb\",passwd=\"mypasswd\",) # connection string\n\n filename = 'data.csv'\n f = open(filename, \"rb\") # open your csv file\n reader = csv.reader(f)\n # assuming the first line of your csv file has column names\n col_names = reader.next() # first line of .csv file\n reader = csv.DictReader(f, col_names) # apply column names to row values\n\n to_db = [] # this list holds values you will insert to db\n for row in reader: # loop over remaining lines in .csv file\n to_db.append((row['col1'],row['col2']))\n # or if you prefer one-liners\n #to_db = [(row['col1'],row['col2']) for row in reader]\n f.close() # we're done with the file now\n\n cursor = db.cursor()\n cursor.executemany('''INSERT INTO mytable (col1,col2) \n VALUES (%s, %s)''', to_db) # note the two arguments\n cursor.close()\n db.close()\n\nif __name__ == \"__main__\":\n main()\n\n",
"You should be using DB-API quoting instead of including the data in the SQL query directly:\nsql = \"\"\"INSERT INTO temporary_load\n (domain_name, session_count, search_count, click_count,\n revenue, revenue_per_min, cost_per_click, traffic_date)\n VALUES (%s, %d, %d, %d, %d, %d, %d, %s)\"\"\"\nargs = (cell[0],\n int(cell[1]),\n int(cell[2].replace (\",\",\"\")),\n int(cell[3].replace(\",\",\"\")),\n float(cell[4].replace(\"$\",\"\")),\n float(cell[5].replace(\"$\",\"\")),\n float(cell[6].replace(\"$\",\"\")),\n parsed_date)\ncur.execute(sql, args)\n\nThis makes the DB-API module quote the values appropriately, and resolves a whole host of issues that you might get when doing it by hand (and usually incorrectly.)\n"
] |
[
2,
1
] |
[] |
[] |
[
"mysql",
"mysql_error_1054",
"python"
] |
stackoverflow_0002226258_mysql_mysql_error_1054_python.txt
|
Q:
PyEval_CallObject failing in loop occasionally
I am struggling a bit with the Python C API. I am calling a python method to do some game AI at about 60hz. It works most of the time but every second or so the call to PyEval_CallObject results in a NULL return value. If I correctly detect the error and continue looping, all is well for the next second or so, whereupon the error occurs again.
I suspect I am doing something wrong with ref counting but I can't figure out what it is:
int script_do_ai(struct game_data_t* gd)
{
PyObject *pAiModule, *pResult;
float result=0.0;
pResult = NULL;
pAiModule = PyImport_Import(PyString_FromString("ai_script"));
Yeah, I'm importing the the module every iteration. Is that necessary? If I store pAiModule as a global, I get a hard crash after about a second.
pResult = PyEval_CallObject(PyObject_GetAttrString(pAiModule, "do_ai"),
Py_BuildValue("f", gd->important_float))
if (pResult != NULL)
{
PyArg_Parse(pResult, "f", &result);
Py_DECREF(pResult);
ConquerEnemies(result); //you get the idea
}
else //this happens every 75 or so iterations thru the loop
{
if (PyErr_ExceptionMatches(PyExc_SomeException)) //? not sure what to do here
{
I haven't been able to find out how to extract the exception yet, either...without testing for every exception
}
}
Am I even close to doing this right? Like I said, it mostly works but I'd really like to understand why I am getting an error.
Thank you in advance for any help.
A:
You can call PyImport_Import() as often as you like, but you'll just keep getting the same module object back. Python caches imports. Also, instead of creating a new Python string and leaking the reference (and thus the object), you should just use PyImport_ImportModule(), which takes a const char *.
PyImport_Import*() return a new reference, though, you should call Py_DECREF() on it when you're done. Storing the module in a global should not be a problem, as long as you own a reference to it (which you do, here.)
In your call to PyEval_CallObject() you aren't checking the result of Py_BuildValue() for errors, and you're also not calling Py_DECREF() when you're done with it, so you're leaking that object as well.
In order to convert a Python float to a C double, you should probably just call PyFloat_AsDouble() instead of mucking about with PyArg_Parse() (and keep in mind to test for exceptions)
Down to the actual error handling: PyErr_ExceptionMatches() is only useful when you actually want to test if the exception matches something. If you want to know if an exception occurred, or get the actual exception object, PyErr_Occurred() is what you should call. It returns the current exception type (not the actual exception object) as a borrowed reference, or NULL if none is set. If you want to just print a traceback to stderr, PyErr_Print() and PyErr_Clear() are what you want to use. For more fine-grained inspection of the actual error in your code, PyErr_Fetch() gets you the current exception object and the traceback associated with it (it gets you the same information as sys.exc_info() in Python code.) All things considered you rarely want to get that deeply into the exception handling in C code.
|
PyEval_CallObject failing in loop occasionally
|
I am struggling a bit with the Python C API. I am calling a python method to do some game AI at about 60hz. It works most of the time but every second or so the call to PyEval_CallObject results in a NULL return value. If I correctly detect the error and continue looping, all is well for the next second or so, whereupon the error occurs again.
I suspect I am doing something wrong with ref counting but I can't figure out what it is:
int script_do_ai(struct game_data_t* gd)
{
PyObject *pAiModule, *pResult;
float result=0.0;
pResult = NULL;
pAiModule = PyImport_Import(PyString_FromString("ai_script"));
Yeah, I'm importing the the module every iteration. Is that necessary? If I store pAiModule as a global, I get a hard crash after about a second.
pResult = PyEval_CallObject(PyObject_GetAttrString(pAiModule, "do_ai"),
Py_BuildValue("f", gd->important_float))
if (pResult != NULL)
{
PyArg_Parse(pResult, "f", &result);
Py_DECREF(pResult);
ConquerEnemies(result); //you get the idea
}
else //this happens every 75 or so iterations thru the loop
{
if (PyErr_ExceptionMatches(PyExc_SomeException)) //? not sure what to do here
{
I haven't been able to find out how to extract the exception yet, either...without testing for every exception
}
}
Am I even close to doing this right? Like I said, it mostly works but I'd really like to understand why I am getting an error.
Thank you in advance for any help.
|
[
"You can call PyImport_Import() as often as you like, but you'll just keep getting the same module object back. Python caches imports. Also, instead of creating a new Python string and leaking the reference (and thus the object), you should just use PyImport_ImportModule(), which takes a const char *.\nPyImport_Import*() return a new reference, though, you should call Py_DECREF() on it when you're done. Storing the module in a global should not be a problem, as long as you own a reference to it (which you do, here.)\nIn your call to PyEval_CallObject() you aren't checking the result of Py_BuildValue() for errors, and you're also not calling Py_DECREF() when you're done with it, so you're leaking that object as well.\nIn order to convert a Python float to a C double, you should probably just call PyFloat_AsDouble() instead of mucking about with PyArg_Parse() (and keep in mind to test for exceptions)\nDown to the actual error handling: PyErr_ExceptionMatches() is only useful when you actually want to test if the exception matches something. If you want to know if an exception occurred, or get the actual exception object, PyErr_Occurred() is what you should call. It returns the current exception type (not the actual exception object) as a borrowed reference, or NULL if none is set. If you want to just print a traceback to stderr, PyErr_Print() and PyErr_Clear() are what you want to use. For more fine-grained inspection of the actual error in your code, PyErr_Fetch() gets you the current exception object and the traceback associated with it (it gets you the same information as sys.exc_info() in Python code.) All things considered you rarely want to get that deeply into the exception handling in C code.\n"
] |
[
5
] |
[] |
[] |
[
"c",
"python",
"python_c_api"
] |
stackoverflow_0002234539_c_python_python_c_api.txt
|
Q:
Python design question
I'm a C programmer and I'm getting quite good with Python. But I still have some problems getting my mind around the OO awesomeness of Python.
Here is my current design problem:
The end "product" is a JSON data structure created in Python (and passed to Javascript code) containing different types of data like:
{ type:url, {urlpayloaddict) }
{ type:text, {textpayloaddict}
...
My Javascript knows how to parse and display each type of JSON response.
I'm happy with this design. My question comes from handling this data in the Python code.
I obtain my data from a variety of sources: MySQL, a table lookup, an API call to a web service...
Basically, should I make a super class responseElement and specialise it for each type of response, then pass around a list of these objects in the Python code OR should I simply pass around a list of dictionaries that contain the response data in key value pairs. The answer seems to result in significantly different implementations.
I'm a bit unsure if I'm getting too object happy ??
A:
In my mind, it basically goes like this: you should try to keep things the same where they are the same, and separate them where they're different.
If you're performing the exact same operations on and with the data, and it can all be represented in a common format, then there's no reason to have separate objects for it - translate it into a common format ASAP and Don't Repeat Yourself when it comes to implementing things that don't distinguish.
If each type/source of data requires specialized operations specific to it, and there isn't much in the way of overlap between such at the layer your Python code is dealing with, then keep things in separate objects so that you maintain a tight association between the specialized code and the specific data on which it is able to operate.
A:
Do the different response sources represent fundamentally different categories or classes of objects? They don't appear to, the way you've described it.
Thus, various encode/decode functions and passing around only one type seems the best solution for you.
That type can be a dict or your own class, if you have special methods to use on the data (but those methods would then not care what input and output encodings were), or you could put the encode/decode pairs into the class. (Decode would be a classmethod, returning a new instance.)
A:
Your receiver objects (which can perfectly well be instances of different classes, perhaps generated by a Factory pattern depending on the source of incoming data) should all have a common method that returns the appropriate dict (or other directly-JSON'able structure, such as a list that will turn into a JSON array).
Differently from what one answer states, this approach clearly doesn't require higher level code to know what exact kind of receiver it's dealing with (polymorphism will handle that for you in any OO language!) -- nor does the higher level code need to know "names of keys" (as, again, that other answer peculiarly states), as it can perfectly well treat the "JSON'able data" as a pretty opaque data token (as long as it's suitable to be the argument for a json.dumps later call!).
Building up and passing around a container of "plain old data" objects (produced and added to the container in various ways) for eventual serialization (or other such uniform treatment, but you can see JSON translation as a specific form of serialization) is a common OO pattern. No need to carry around anything richer or heavier than such POD data, after all, and in Python using dicts as the PODs is often a perfectly natural implementation choice.
A:
I've had success with the OOP approach. Consider a base class with a "ToJson" method and have each subclass implement it appropriately. Then your higher level code doesn't need to know any detail about how the data was obtained...it just knows it has to call "ToJson" on every object in the list you mentioned.
A dictionary would work too, but it requires your calling code to know names of keys, etc and won't scale as well.
OOP I say!
A:
Personally, I opt for the latter (passing around a list of data) wherever and whenever possible. I think OO is often misused/abused for certain things. I specifically avoid things like wrapping data in an object just for the sake of wrapping it in an object. So this, {'type':'url', 'data':{some_other_dict}} is better to me than:
class DataObject:
def __init__(self):
self.type = 'url'
self.data = {some_other_dict}
But, if you need to add specific functionality to this data, like the ability for it to sort its data.keys() and return them as a set, then creating an object makes more sense.
|
Python design question
|
I'm a C programmer and I'm getting quite good with Python. But I still have some problems getting my mind around the OO awesomeness of Python.
Here is my current design problem:
The end "product" is a JSON data structure created in Python (and passed to Javascript code) containing different types of data like:
{ type:url, {urlpayloaddict) }
{ type:text, {textpayloaddict}
...
My Javascript knows how to parse and display each type of JSON response.
I'm happy with this design. My question comes from handling this data in the Python code.
I obtain my data from a variety of sources: MySQL, a table lookup, an API call to a web service...
Basically, should I make a super class responseElement and specialise it for each type of response, then pass around a list of these objects in the Python code OR should I simply pass around a list of dictionaries that contain the response data in key value pairs. The answer seems to result in significantly different implementations.
I'm a bit unsure if I'm getting too object happy ??
|
[
"In my mind, it basically goes like this: you should try to keep things the same where they are the same, and separate them where they're different.\nIf you're performing the exact same operations on and with the data, and it can all be represented in a common format, then there's no reason to have separate objects for it - translate it into a common format ASAP and Don't Repeat Yourself when it comes to implementing things that don't distinguish.\nIf each type/source of data requires specialized operations specific to it, and there isn't much in the way of overlap between such at the layer your Python code is dealing with, then keep things in separate objects so that you maintain a tight association between the specialized code and the specific data on which it is able to operate.\n",
"Do the different response sources represent fundamentally different categories or classes of objects? They don't appear to, the way you've described it.\nThus, various encode/decode functions and passing around only one type seems the best solution for you.\nThat type can be a dict or your own class, if you have special methods to use on the data (but those methods would then not care what input and output encodings were), or you could put the encode/decode pairs into the class. (Decode would be a classmethod, returning a new instance.)\n",
"Your receiver objects (which can perfectly well be instances of different classes, perhaps generated by a Factory pattern depending on the source of incoming data) should all have a common method that returns the appropriate dict (or other directly-JSON'able structure, such as a list that will turn into a JSON array).\nDifferently from what one answer states, this approach clearly doesn't require higher level code to know what exact kind of receiver it's dealing with (polymorphism will handle that for you in any OO language!) -- nor does the higher level code need to know \"names of keys\" (as, again, that other answer peculiarly states), as it can perfectly well treat the \"JSON'able data\" as a pretty opaque data token (as long as it's suitable to be the argument for a json.dumps later call!).\nBuilding up and passing around a container of \"plain old data\" objects (produced and added to the container in various ways) for eventual serialization (or other such uniform treatment, but you can see JSON translation as a specific form of serialization) is a common OO pattern. No need to carry around anything richer or heavier than such POD data, after all, and in Python using dicts as the PODs is often a perfectly natural implementation choice.\n",
"I've had success with the OOP approach. Consider a base class with a \"ToJson\" method and have each subclass implement it appropriately. Then your higher level code doesn't need to know any detail about how the data was obtained...it just knows it has to call \"ToJson\" on every object in the list you mentioned.\nA dictionary would work too, but it requires your calling code to know names of keys, etc and won't scale as well.\nOOP I say!\n",
"Personally, I opt for the latter (passing around a list of data) wherever and whenever possible. I think OO is often misused/abused for certain things. I specifically avoid things like wrapping data in an object just for the sake of wrapping it in an object. So this, {'type':'url', 'data':{some_other_dict}} is better to me than:\nclass DataObject:\n def __init__(self):\n self.type = 'url'\n self.data = {some_other_dict}\n\nBut, if you need to add specific functionality to this data, like the ability for it to sort its data.keys() and return them as a set, then creating an object makes more sense.\n"
] |
[
5,
3,
2,
1,
1
] |
[] |
[] |
[
"json",
"oop",
"python"
] |
stackoverflow_0002234531_json_oop_python.txt
|
Q:
How to get path of Start Menu's Programs directory?
...for current user? for all users?
I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more portable approaches?
OUR_STARTMENU = os.environ['ALLUSERSPROFILE'] + '\Start Menu\Programs\Our Stuff'
thank you
A:
I've heard of 2 ways of doing this. First:
from win32com.shell import shell
shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_COMMON_STARTMENU)
Second, using the WScript.Shell object (source : http://www.mail-archive.com/python-win32@python.org/msg00992.html):
import win32com.client
objShell = win32com.client.Dispatch("WScript.Shell")
allUserProgramsMenu = objShell.SpecialFolders("AllUsersPrograms")
userMenu = objShell.SpecialFolders("StartMenu")
Another source: http://blogs.msdn.com/saveenr/archive/2005/12/28/creating-a-start-menu-shortcut-with-powershell-and-python.aspx
A:
Also, CSIDL_COMMON_STARTMENU is for all user startup and CSIDL_STARTMENU for current user startup.
A:
A friend, Luke Pinner of Environment.gov.au, gave a solution by email which uses a core module (python 2.5+). Believed to be multi-lingual as the return from the API call is unicode. Tested on Win7 with Japanese locale, and on another us-english machine by manually changing Start Menu to point to %USERPROFILE%\Startmenü
''' Get windows special folders without pythonwin
Example:
import specialfolders
start_programs = specialfolders.get(specialfolders.PROGRAMS)
Code is public domain, do with it what you will.
Luke Pinner - Environment.gov.au, 2010 February 10
'''
#Imports use _syntax to mask them from autocomplete IDE's
import ctypes as _ctypes
from ctypes.wintypes import HWND as _HWND, HANDLE as _HANDLE,DWORD as _DWORD,LPCWSTR as _LPCWSTR,MAX_PATH as _MAX_PATH, create_unicode_buffer as _cub
_SHGetFolderPath = _ctypes.windll.shell32.SHGetFolderPathW
#public special folder constants
DESKTOP= 0
PROGRAMS= 2
MYDOCUMENTS= 5
FAVORITES= 6
STARTUP= 7
RECENT= 8
SENDTO= 9
STARTMENU= 11
MYMUSIC= 13
MYVIDEOS= 14
NETHOOD= 19
FONTS= 20
TEMPLATES= 21
ALLUSERSSTARTMENU= 22
ALLUSERSPROGRAMS= 23
ALLUSERSSTARTUP= 24
ALLUSERSDESKTOP= 25
APPLICATIONDATA= 26
PRINTHOOD= 27
LOCALSETTINGSAPPLICATIONDATA= 28
ALLUSERSFAVORITES= 31
LOCALSETTINGSTEMPORARYINTERNETFILES=32
COOKIES= 33
LOCALSETTINGSHISTORY= 34
ALLUSERSAPPLICATIONDATA= 35
def get(intFolder):
_SHGetFolderPath.argtypes = [_HWND, _ctypes.c_int, _HANDLE, _DWORD, _LPCWSTR]
auPathBuffer = _cub(_MAX_PATH)
exit_code=_SHGetFolderPath(0, intFolder, 0, 0, auPathBuffer)
return auPathBuffer.value
|
How to get path of Start Menu's Programs directory?
|
...for current user? for all users?
I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more portable approaches?
OUR_STARTMENU = os.environ['ALLUSERSPROFILE'] + '\Start Menu\Programs\Our Stuff'
thank you
|
[
"I've heard of 2 ways of doing this. First:\nfrom win32com.shell import shell\nshell.SHGetSpecialFolderPath(0,shellcon.CSIDL_COMMON_STARTMENU)\n\nSecond, using the WScript.Shell object (source : http://www.mail-archive.com/python-win32@python.org/msg00992.html):\nimport win32com.client\nobjShell = win32com.client.Dispatch(\"WScript.Shell\")\nallUserProgramsMenu = objShell.SpecialFolders(\"AllUsersPrograms\")\nuserMenu = objShell.SpecialFolders(\"StartMenu\")\n\nAnother source: http://blogs.msdn.com/saveenr/archive/2005/12/28/creating-a-start-menu-shortcut-with-powershell-and-python.aspx\n",
"Also, CSIDL_COMMON_STARTMENU is for all user startup and CSIDL_STARTMENU for current user startup.\n",
"A friend, Luke Pinner of Environment.gov.au, gave a solution by email which uses a core module (python 2.5+). Believed to be multi-lingual as the return from the API call is unicode. Tested on Win7 with Japanese locale, and on another us-english machine by manually changing Start Menu to point to %USERPROFILE%\\Startmenü\n''' Get windows special folders without pythonwin\n Example:\n import specialfolders\n start_programs = specialfolders.get(specialfolders.PROGRAMS)\n\nCode is public domain, do with it what you will. \n\nLuke Pinner - Environment.gov.au, 2010 February 10\n'''\n\n#Imports use _syntax to mask them from autocomplete IDE's\nimport ctypes as _ctypes\nfrom ctypes.wintypes import HWND as _HWND, HANDLE as _HANDLE,DWORD as _DWORD,LPCWSTR as _LPCWSTR,MAX_PATH as _MAX_PATH, create_unicode_buffer as _cub\n_SHGetFolderPath = _ctypes.windll.shell32.SHGetFolderPathW\n\n#public special folder constants\nDESKTOP= 0\nPROGRAMS= 2\nMYDOCUMENTS= 5\nFAVORITES= 6\nSTARTUP= 7\nRECENT= 8\nSENDTO= 9\nSTARTMENU= 11\nMYMUSIC= 13\nMYVIDEOS= 14\nNETHOOD= 19\nFONTS= 20\nTEMPLATES= 21\nALLUSERSSTARTMENU= 22\nALLUSERSPROGRAMS= 23\nALLUSERSSTARTUP= 24\nALLUSERSDESKTOP= 25\nAPPLICATIONDATA= 26\nPRINTHOOD= 27\nLOCALSETTINGSAPPLICATIONDATA= 28\nALLUSERSFAVORITES= 31\nLOCALSETTINGSTEMPORARYINTERNETFILES=32\nCOOKIES= 33\nLOCALSETTINGSHISTORY= 34\nALLUSERSAPPLICATIONDATA= 35\n\ndef get(intFolder):\n _SHGetFolderPath.argtypes = [_HWND, _ctypes.c_int, _HANDLE, _DWORD, _LPCWSTR]\n auPathBuffer = _cub(_MAX_PATH)\n exit_code=_SHGetFolderPath(0, intFolder, 0, 0, auPathBuffer)\n return auPathBuffer.value\n\n"
] |
[
11,
2,
1
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0002216173_python_windows.txt
|
Q:
Drawing Hebrew text to and image using Image module (python)
This is an issue I already asked about and several got answers but the problem remained.
when I try to write in hebrew to an image using Image module I get instead of the hebrew lettring some other (ascii??) lettering. if I convert to unicode or ascii I get an error that it doesn't support. I got here a reference to a code that does what I want in chinese:
import sys
import Imag
import ImageDraw
import ImageFont
import _imaging
txt = '你好,世界!'
font = ImageFont.truetype('c:/test/simsun.ttc',24)
im = Image.new("RGBA",(300,200),(0,0,0))
draw = ImageDraw.Draw(im)
#draw.text( (0,50), u'你好,世界!', font=font)
draw.text( (0,50), unicode(txt,'UTF-8'), font=font)
but then I get an error:ImportError:
The _imagingft C module is not installed.
the same goes when I try to use standrad hebrew font 'arial.ttf' (with hebrew string ofcourse). as you can see I have imported _imaging succsefuly so the problem doesn't lay there as suggested by effbot.org.
it seem that the problem is with the Imagefont.truetype(...).
any help will be very appriciated
A:
Sounds like PIL was built without FreeType support. Install the FreeType dev files and rebuild PIL again.
A:
the problem was the PIL 1.1.7 doesn't work well with windows XP. the same code runs well under linux or with XP but with PIL 1.1.6
mystory is solved
|
Drawing Hebrew text to and image using Image module (python)
|
This is an issue I already asked about and several got answers but the problem remained.
when I try to write in hebrew to an image using Image module I get instead of the hebrew lettring some other (ascii??) lettering. if I convert to unicode or ascii I get an error that it doesn't support. I got here a reference to a code that does what I want in chinese:
import sys
import Imag
import ImageDraw
import ImageFont
import _imaging
txt = '你好,世界!'
font = ImageFont.truetype('c:/test/simsun.ttc',24)
im = Image.new("RGBA",(300,200),(0,0,0))
draw = ImageDraw.Draw(im)
#draw.text( (0,50), u'你好,世界!', font=font)
draw.text( (0,50), unicode(txt,'UTF-8'), font=font)
but then I get an error:ImportError:
The _imagingft C module is not installed.
the same goes when I try to use standrad hebrew font 'arial.ttf' (with hebrew string ofcourse). as you can see I have imported _imaging succsefuly so the problem doesn't lay there as suggested by effbot.org.
it seem that the problem is with the Imagefont.truetype(...).
any help will be very appriciated
|
[
"Sounds like PIL was built without FreeType support. Install the FreeType dev files and rebuild PIL again.\n",
"the problem was the PIL 1.1.7 doesn't work well with windows XP. the same code runs well under linux or with XP but with PIL 1.1.6\nmystory is solved\n"
] |
[
3,
1
] |
[] |
[] |
[
"bidirectional",
"hebrew",
"image",
"python"
] |
stackoverflow_0002182787_bidirectional_hebrew_image_python.txt
|
Q:
Having "Exception Value: The _imaging C module is not installed" with my Buildout/Python/Django/PIL on Mac OSX SL?
I'm using Buildout for my Django projects, with FeinCMS. I've got it setup great locally on my Mac OSX Snow Leopard, with no errors coming up at all when I use runserver. But when I upload an image with FeinCMS in the admin area it comes up with a
"Exception Value: The _imaging C module is not installed" error.
My traceback is here: http://dpaste.com/149492/
My buildout.cfg file looks like this:
[buildout]
parts =
zlib
libjpeg
PILwoTk
django-mptt
django-staticfiles
django
eggs =
PILwoTk
feincms
[zlib]
recipe = hexagonit.recipe.cmmi
url = http://www.zlib.net/zlib-1.2.3.tar.gz
configure-options = --shared
[libjpeg]
recipe = hexagonit.recipe.cmmi
url = http://www.ijg.org/files/jpegsrc.v8.tar.gz
[PILwoTk]
recipe = zc.recipe.egg:custom
find-links = http://download.zope.org/distribution/
include-dirs =
${zlib:location}/include
${libjpeg:location}/include
library-dirs =
${zlib:location}/lib
${libjpeg:location}/lib
rpath =
${zlib:location}/lib
${libjpeg:location}/lib
[django-mptt]
recipe = infrae.subversion
urls = http://django-mptt.googlecode.com/svn/trunk/mptt mptt
[django-staticfiles]
recipe = mercurialrecipe
repository = http://bitbucket.org/jezdez/django-staticfiles/
[django]
recipe = djangorecipe
version = 1.1.1
project = recoilmedia
eggs = ${buildout:eggs}
extra-paths =
${django-mptt:location}
${django-staticfiles:location}
I've asked on FeinCMS group, on Django IRC/group but with absolutely no help from anyone on what this can be. I've searched all over the net for solutions and still haven't found one that works. It's diving me up the wall, I've been stuck on it all day. Does anyone possibly know what the problem is?
A:
I have gone through the same thing today and found a solution. The problem is that PIL will look for 32-bit libjpeg and Snow Leopard will compile the library as x86_64 by default. This could be fixed by modifying your libjpeg section to look like this:
[libjpeg]
recipe = hexagonit.recipe.cmmi
url = http://www.ijg.org/files/jpegsrc.v8.tar.gz
environment =
CC=gcc -arch i386
You can check which library _imaging.so is using by running:
otool -L path/to/PIL/_imaging.so
It should output the line pointing to libjpeg.8.dylib in your buildout directory.
Edit: On a second thought, running buildout with CC="gcc -arch i386" bin/buildout will also works. If you want to compile a fat binary, remember to use GCC-4.0 and add CPP: CC="gcc-4.0 -arch i386 -arch ppc" CPP="gcc-4.0 -E" bin/buildout.
|
Having "Exception Value: The _imaging C module is not installed" with my Buildout/Python/Django/PIL on Mac OSX SL?
|
I'm using Buildout for my Django projects, with FeinCMS. I've got it setup great locally on my Mac OSX Snow Leopard, with no errors coming up at all when I use runserver. But when I upload an image with FeinCMS in the admin area it comes up with a
"Exception Value: The _imaging C module is not installed" error.
My traceback is here: http://dpaste.com/149492/
My buildout.cfg file looks like this:
[buildout]
parts =
zlib
libjpeg
PILwoTk
django-mptt
django-staticfiles
django
eggs =
PILwoTk
feincms
[zlib]
recipe = hexagonit.recipe.cmmi
url = http://www.zlib.net/zlib-1.2.3.tar.gz
configure-options = --shared
[libjpeg]
recipe = hexagonit.recipe.cmmi
url = http://www.ijg.org/files/jpegsrc.v8.tar.gz
[PILwoTk]
recipe = zc.recipe.egg:custom
find-links = http://download.zope.org/distribution/
include-dirs =
${zlib:location}/include
${libjpeg:location}/include
library-dirs =
${zlib:location}/lib
${libjpeg:location}/lib
rpath =
${zlib:location}/lib
${libjpeg:location}/lib
[django-mptt]
recipe = infrae.subversion
urls = http://django-mptt.googlecode.com/svn/trunk/mptt mptt
[django-staticfiles]
recipe = mercurialrecipe
repository = http://bitbucket.org/jezdez/django-staticfiles/
[django]
recipe = djangorecipe
version = 1.1.1
project = recoilmedia
eggs = ${buildout:eggs}
extra-paths =
${django-mptt:location}
${django-staticfiles:location}
I've asked on FeinCMS group, on Django IRC/group but with absolutely no help from anyone on what this can be. I've searched all over the net for solutions and still haven't found one that works. It's diving me up the wall, I've been stuck on it all day. Does anyone possibly know what the problem is?
|
[
"I have gone through the same thing today and found a solution. The problem is that PIL will look for 32-bit libjpeg and Snow Leopard will compile the library as x86_64 by default. This could be fixed by modifying your libjpeg section to look like this:\n[libjpeg]\nrecipe = hexagonit.recipe.cmmi\nurl = http://www.ijg.org/files/jpegsrc.v8.tar.gz\nenvironment =\n CC=gcc -arch i386\n\nYou can check which library _imaging.so is using by running:\notool -L path/to/PIL/_imaging.so\n\nIt should output the line pointing to libjpeg.8.dylib in your buildout directory.\nEdit: On a second thought, running buildout with CC=\"gcc -arch i386\" bin/buildout will also works. If you want to compile a fat binary, remember to use GCC-4.0 and add CPP: CC=\"gcc-4.0 -arch i386 -arch ppc\" CPP=\"gcc-4.0 -E\" bin/buildout.\n"
] |
[
2
] |
[] |
[] |
[
"buildout",
"django",
"python",
"python_imaging_library"
] |
stackoverflow_0002124306_buildout_django_python_python_imaging_library.txt
|
Q:
Subclass builtin List
I want to subclass the list type and have slicing return an object of the descendant type, however it is returning a list. What is the minimum code way to do this?
If there isn't a neat way to do it, I'll just include a list internally which is slightly more messy, but not unreasonable.
My code so far:
class Channel(list):
sample_rate = 0
def __init__(self, sample_rate, label=u"", data=[]):
list.__init__(self,data)
self.sample_rate = sample_rate
self.label = label
@property
def nyquist_rate(self):
return float(self.sample_rate) / 2.0
A:
I guess you should override the __getslice__ method to return an object of your type...
Maybe something like the following?
class MyList(list):
#your stuff here
def __getslice__(self, i, j):
return MyList(list.__getslice__(self, i, j))
|
Subclass builtin List
|
I want to subclass the list type and have slicing return an object of the descendant type, however it is returning a list. What is the minimum code way to do this?
If there isn't a neat way to do it, I'll just include a list internally which is slightly more messy, but not unreasonable.
My code so far:
class Channel(list):
sample_rate = 0
def __init__(self, sample_rate, label=u"", data=[]):
list.__init__(self,data)
self.sample_rate = sample_rate
self.label = label
@property
def nyquist_rate(self):
return float(self.sample_rate) / 2.0
|
[
"I guess you should override the __getslice__ method to return an object of your type...\nMaybe something like the following?\nclass MyList(list):\n #your stuff here\n\n def __getslice__(self, i, j):\n return MyList(list.__getslice__(self, i, j))\n\n"
] |
[
11
] |
[] |
[] |
[
"built_in",
"list",
"python",
"subclass"
] |
stackoverflow_0002235556_built_in_list_python_subclass.txt
|
Q:
How to split a list into a given number of sub-lists in python
Possible Duplicates:
splitting a list of arbitrary size into only roughly N-equal parts
How do you split a list into evenly sized chunks in Python?
I need to create a function that will split a list into a list of list, each containing an equal number of items (or as equal as possible).
e.g.
def split_lists(mainlist, splitcount):
....
mylist = [1,2,3,4,5,6]
split_list(mylist,2) will return a list of two lists of three elements - [[1,2,3][4,5,6]].
split_list(mylist,3) will return a list of three lists of two elements.
split_list(mylist,4) will return a list of two lists of two elements and two lists of one element.
I don't care which elements appear in which list, just that the list is divided up as evenly as possible.
A:
numpy.split does this already:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html
Examples:
>>> mylist = np.array([1,2,3,4,5,6])
split_list(mylist,2) will return a list of two lists of three elements
- [[1,2,3][4,5,6]].
>>> np.split(mylist, 2)
[array([1, 2, 3]), array([4, 5, 6])]
split_list(mylist,3) will return a list of three lists of two
elements.
>>> np.split(mylist, 3)
[array([1, 2]), array([3, 4]), array([5, 6])]
split_list(mylist,4) will return a list of two lists of two elements
and two lists of one element.
You may probably want to add an exception capture for the cases when the remainder of length(mylist)/n is not 0:
>>> np.split(mylist, 4)
ValueErrorTraceback (most recent call last)
----> 1 np.split(mylist, 4)
...
ValueError: array split does not result in an equal division
|
How to split a list into a given number of sub-lists in python
|
Possible Duplicates:
splitting a list of arbitrary size into only roughly N-equal parts
How do you split a list into evenly sized chunks in Python?
I need to create a function that will split a list into a list of list, each containing an equal number of items (or as equal as possible).
e.g.
def split_lists(mainlist, splitcount):
....
mylist = [1,2,3,4,5,6]
split_list(mylist,2) will return a list of two lists of three elements - [[1,2,3][4,5,6]].
split_list(mylist,3) will return a list of three lists of two elements.
split_list(mylist,4) will return a list of two lists of two elements and two lists of one element.
I don't care which elements appear in which list, just that the list is divided up as evenly as possible.
|
[
"numpy.split does this already: \n\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html\n\nExamples:\n>>> mylist = np.array([1,2,3,4,5,6])\n\n\nsplit_list(mylist,2) will return a list of two lists of three elements\n - [[1,2,3][4,5,6]].\n\n>>> np.split(mylist, 2)\n[array([1, 2, 3]), array([4, 5, 6])]\n\n\nsplit_list(mylist,3) will return a list of three lists of two\n elements.\n\n>>> np.split(mylist, 3)\n[array([1, 2]), array([3, 4]), array([5, 6])]\n\n\nsplit_list(mylist,4) will return a list of two lists of two elements\n and two lists of one element.\n\nYou may probably want to add an exception capture for the cases when the remainder of length(mylist)/n is not 0:\n>>> np.split(mylist, 4)\nValueErrorTraceback (most recent call last)\n----> 1 np.split(mylist, 4)\n...\nValueError: array split does not result in an equal division\n\n"
] |
[
6
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002235526_list_python.txt
|
Q:
Automate file download from http using python
I want to automatically save a file from a website. I don't know how to bypass the Download File prompt in python and save it directly to my c: drive.
Any help is appreciated,
Elliott
A:
Modules like urllib2 and urlgrabber don't have a "Download File" prompt.
A:
One idea is to use a module like mechanize to automate the query and the download.
Here you can find some documentation.
Usually when you post a question here at stackoverflow, it is a good idea to post an example at how you have tried to solve the problem, and then we will help you to improve it, rather than asking people to write the solution for you,
when you use mechanize, configure the UserAgent properly and respect the policy of the webmasters about scraping.
|
Automate file download from http using python
|
I want to automatically save a file from a website. I don't know how to bypass the Download File prompt in python and save it directly to my c: drive.
Any help is appreciated,
Elliott
|
[
"Modules like urllib2 and urlgrabber don't have a \"Download File\" prompt.\n",
"One idea is to use a module like mechanize to automate the query and the download.\nHere you can find some documentation.\n\nUsually when you post a question here at stackoverflow, it is a good idea to post an example at how you have tried to solve the problem, and then we will help you to improve it, rather than asking people to write the solution for you,\nwhen you use mechanize, configure the UserAgent properly and respect the policy of the webmasters about scraping.\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002235458_python.txt
|
Q:
Django: Can't set ForeignKey value to None from admin
I have a model Category which has a ForeignKey to a SimplePage model. null and blank are set to True. The problem is, when I edit a Category from the admin interface, I can't change the ForeignKey to --------- (Which looks like the admin's way of saying None.) The value can be None initially, and I can change it to an actual value through the admin, and I can change to another value, but once it has an actual value I can't change it back to None. (Through the admin, that is.)
Why is this?
UPDATE:
Here's the code for models.py:
from django.db import models
import tinymce.models
from photologue.models import Photo
from django.utils.translation import ugettext_lazy as _
import multilingual
class SimplePage(models.Model):
slug = models.SlugField(
_('Slug'),
unique=True,
help_text=_('''Unique identifier for URL. Only letters, digits, and -.\
e.g. history-oct-2000 or about''')
)
category = models.ForeignKey('Category',
related_name='items_including_main_page',
blank=True, null=True)
class Translation(multilingual.Translation):
title = models.CharField(_('Title'), max_length=42)
content = tinymce.models.HTMLField(_('Content'), blank=True)
class Admin:
list_display = ('title',)
search_fields = ('title', 'content')
class Meta:
verbose_name = _('Simple page')
verbose_name_plural = _('Simple pages')
__unicode__ = lambda self: self.title
class Category(models.Model):
main_page = models.OneToOneField(
SimplePage,
related_name='_SimplePage__category_which_has_this_as_title',
blank=True,
null=True)
get_title = lambda self: self.main_page.title if self.main_page else u''
get_items = lambda self: \
self.items_including_main_page.exclude(id__exact=self.main_page.id)
__unicode__ = lambda self: self.get_title() or u'Titleless Category'
class Admin:
pass
class Meta:
verbose_name = _('Category')
verbose_name_plural = _('Categories')
And admin.py:
from sitehelpers.models import *
from django.contrib import admin
import multilingual
class SimplePageAdmin(multilingual.ModelAdmin):
pass
admin.site.register(SimplePage, SimplePageAdmin)
admin.site.register(Category)
A:
Maybe that's because you have OneToOne relationship defined also in category and you can't therefore break this relationship. Try to remove it and see, if you can set category in SimplePage to None.
A:
gruszczy above is right, each side of o2o relation cannot be null after it was assigned, because django won't let you have orphan object in DB.
|
Django: Can't set ForeignKey value to None from admin
|
I have a model Category which has a ForeignKey to a SimplePage model. null and blank are set to True. The problem is, when I edit a Category from the admin interface, I can't change the ForeignKey to --------- (Which looks like the admin's way of saying None.) The value can be None initially, and I can change it to an actual value through the admin, and I can change to another value, but once it has an actual value I can't change it back to None. (Through the admin, that is.)
Why is this?
UPDATE:
Here's the code for models.py:
from django.db import models
import tinymce.models
from photologue.models import Photo
from django.utils.translation import ugettext_lazy as _
import multilingual
class SimplePage(models.Model):
slug = models.SlugField(
_('Slug'),
unique=True,
help_text=_('''Unique identifier for URL. Only letters, digits, and -.\
e.g. history-oct-2000 or about''')
)
category = models.ForeignKey('Category',
related_name='items_including_main_page',
blank=True, null=True)
class Translation(multilingual.Translation):
title = models.CharField(_('Title'), max_length=42)
content = tinymce.models.HTMLField(_('Content'), blank=True)
class Admin:
list_display = ('title',)
search_fields = ('title', 'content')
class Meta:
verbose_name = _('Simple page')
verbose_name_plural = _('Simple pages')
__unicode__ = lambda self: self.title
class Category(models.Model):
main_page = models.OneToOneField(
SimplePage,
related_name='_SimplePage__category_which_has_this_as_title',
blank=True,
null=True)
get_title = lambda self: self.main_page.title if self.main_page else u''
get_items = lambda self: \
self.items_including_main_page.exclude(id__exact=self.main_page.id)
__unicode__ = lambda self: self.get_title() or u'Titleless Category'
class Admin:
pass
class Meta:
verbose_name = _('Category')
verbose_name_plural = _('Categories')
And admin.py:
from sitehelpers.models import *
from django.contrib import admin
import multilingual
class SimplePageAdmin(multilingual.ModelAdmin):
pass
admin.site.register(SimplePage, SimplePageAdmin)
admin.site.register(Category)
|
[
"Maybe that's because you have OneToOne relationship defined also in category and you can't therefore break this relationship. Try to remove it and see, if you can set category in SimplePage to None.\n",
"gruszczy above is right, each side of o2o relation cannot be null after it was assigned, because django won't let you have orphan object in DB.\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"orm",
"python"
] |
stackoverflow_0002220838_django_orm_python.txt
|
Q:
Interchange of Position of Two Keyword Arguments Throws Error
I have an odd problem. I know that in Python, kwargs follow args, so I checked for that and it's not the problem. What is the problem is this:
Fine:
def __init__(self, sample_rate, label=u"", data=[] ):
TypeError: __init__() got multiple values for keyword argument 'data':
def __init__(self, sample_rate, data=[], label=u""):
The calling line that throws the error looks like this:
def __getslice__(self, start, stop):
return Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))
The full code:
class Channel(list):
sample_rate = 0
def __init__(self, sample_rate, data=[], label=u"" ):
list.__init__(self,data)
self.sample_rate = sample_rate
self.label = label
@property
def nyquist_rate(self):
return float(self.sample_rate) / 2.0
def __getslice__(self, start, stop):
return Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))
Thank you!
A:
You are calling the code with
Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))
Note that the second parameter has no keyword, so the interpreter assumes this is the data parameter (because that's the order they are defined in the function). If you add label= it should solve it.
But, you have a more important error in your code: Never use [] as a default value. The reason is this code is evaluated at function definition time. every time you call this code with no data parameter, you'll get the same list as a default value. and it might not be empty after the first time! This is true for all mutable datatypes. The correct way to do this, is to use None as a default value and inside the function (code that runs each time) init a new [], if the parameter value is None.
(This gocha is also explained well by David Goodger, in Default Parameter Values)
A:
In the second version (def __init__(self, sample_rate, data=[], label=u""):), the second positional argument (when called, that means not counting self) is data, but in __getslice__, the second argument that you pass is label. So you should either keep label as the second argument, or change the function call to this:
return Channel(self.sample_rate, label=self.label, data=list.__getslice__(self,start,stop))
A:
The problem is that in your calling code, you have two positional arguments:
return Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))
# sample_rate (pos) data (pos) data (kw)
In Python 2.x, there is no distinction between positional and keyword arguments in the function definition. When a function is called, positional arguments from the function invocation are used to fill arguments left to right, then all keyword arguments are bound. In your case, data is bound both by a positional and a keyword arguments. It works in the other case because then the second positional argument is used for label, and data only gets the keyword argument.
|
Interchange of Position of Two Keyword Arguments Throws Error
|
I have an odd problem. I know that in Python, kwargs follow args, so I checked for that and it's not the problem. What is the problem is this:
Fine:
def __init__(self, sample_rate, label=u"", data=[] ):
TypeError: __init__() got multiple values for keyword argument 'data':
def __init__(self, sample_rate, data=[], label=u""):
The calling line that throws the error looks like this:
def __getslice__(self, start, stop):
return Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))
The full code:
class Channel(list):
sample_rate = 0
def __init__(self, sample_rate, data=[], label=u"" ):
list.__init__(self,data)
self.sample_rate = sample_rate
self.label = label
@property
def nyquist_rate(self):
return float(self.sample_rate) / 2.0
def __getslice__(self, start, stop):
return Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))
Thank you!
|
[
"You are calling the code with\nChannel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))\n\nNote that the second parameter has no keyword, so the interpreter assumes this is the data parameter (because that's the order they are defined in the function). If you add label= it should solve it.\nBut, you have a more important error in your code: Never use [] as a default value. The reason is this code is evaluated at function definition time. every time you call this code with no data parameter, you'll get the same list as a default value. and it might not be empty after the first time! This is true for all mutable datatypes. The correct way to do this, is to use None as a default value and inside the function (code that runs each time) init a new [], if the parameter value is None.\n(This gocha is also explained well by David Goodger, in Default Parameter Values)\n",
"In the second version (def __init__(self, sample_rate, data=[], label=u\"\"):), the second positional argument (when called, that means not counting self) is data, but in __getslice__, the second argument that you pass is label. So you should either keep label as the second argument, or change the function call to this:\nreturn Channel(self.sample_rate, label=self.label, data=list.__getslice__(self,start,stop))\n\n",
"The problem is that in your calling code, you have two positional arguments:\nreturn Channel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))\n# sample_rate (pos) data (pos) data (kw)\n\nIn Python 2.x, there is no distinction between positional and keyword arguments in the function definition. When a function is called, positional arguments from the function invocation are used to fill arguments left to right, then all keyword arguments are bound. In your case, data is bound both by a positional and a keyword arguments. It works in the other case because then the second positional argument is used for label, and data only gets the keyword argument.\n"
] |
[
4,
4,
2
] |
[] |
[] |
[
"keyword_argument",
"python"
] |
stackoverflow_0002235895_keyword_argument_python.txt
|
Q:
How to get enumerated results from a query in Django?
I have a query that orders a table according to a particular field. The table is related to one competition, so knowing the position is important.
As the table can grow to have a lot of rows, I have paginate it (25 rows per page) using generic views, but the problem I've got is to present the numbered position on the table. This information is generated using a order_by clause.
Result.objects.all().order_by('field')
As I am using generic views to be able to easily paginate, I don't have any view function that allow me to tweak the results, for example using an enumerate
At first, I thought of using forloop.counter to enumerate the positions without the table, but of course the probelm i when you're presenting page 100, you'll still get the numbers as 1,2,3,4,5...25, instead of 2500, 2501, 2502...
I've been seen the annotate() method, to see if I can add to each result the position it occupies on the total, but seems that it only add statistical data like the man and so on...
Is there any way of adding to each result of a query the position it occupies?
A:
If you're in your template, you can use something like:
{{ forloop.counter0|add:page.start_index }}
Where start_index on pagination's page object gives you the 1-based starting index for that page. Of course, the other way around is probably more readable...
{{ page.start_index|add:forloop.counter0 }}
A:
If it's not about identifying rows in the frontend, why not use the primary key of current table?
|
How to get enumerated results from a query in Django?
|
I have a query that orders a table according to a particular field. The table is related to one competition, so knowing the position is important.
As the table can grow to have a lot of rows, I have paginate it (25 rows per page) using generic views, but the problem I've got is to present the numbered position on the table. This information is generated using a order_by clause.
Result.objects.all().order_by('field')
As I am using generic views to be able to easily paginate, I don't have any view function that allow me to tweak the results, for example using an enumerate
At first, I thought of using forloop.counter to enumerate the positions without the table, but of course the probelm i when you're presenting page 100, you'll still get the numbers as 1,2,3,4,5...25, instead of 2500, 2501, 2502...
I've been seen the annotate() method, to see if I can add to each result the position it occupies on the total, but seems that it only add statistical data like the man and so on...
Is there any way of adding to each result of a query the position it occupies?
|
[
"If you're in your template, you can use something like:\n{{ forloop.counter0|add:page.start_index }}\n\nWhere start_index on pagination's page object gives you the 1-based starting index for that page. Of course, the other way around is probably more readable...\n{{ page.start_index|add:forloop.counter0 }}\n\n",
"If it's not about identifying rows in the frontend, why not use the primary key of current table?\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002236010_django_python.txt
|
Q:
Position charts on Django
I'm trying to do something similar to this, in Django. This is part of the page of Anna:
Pos NickName Points
--- --------- ------
1 The best 1000
...
35 Roger 550
36 Anna 545
37 Paul 540
It's a chart showing the scoring system, and it intends to show the first position, as well as the relative position of the presented player.
Showing the first one it's easy, as it's only making a query to the database and extracting the first one:
best = Score.objects.all().order_by('-points')[0]
But I'm having problems getting the ones close to the presented player (Anna, in this case). I don't want to go searching through the complete list, as the complete list of players can be quite long.
Maybe there's a way to know the position a register occupies in an ordered list...
Any ideas on how to achieve it?
A:
Get the COUNT() of records that have a higher points.
|
Position charts on Django
|
I'm trying to do something similar to this, in Django. This is part of the page of Anna:
Pos NickName Points
--- --------- ------
1 The best 1000
...
35 Roger 550
36 Anna 545
37 Paul 540
It's a chart showing the scoring system, and it intends to show the first position, as well as the relative position of the presented player.
Showing the first one it's easy, as it's only making a query to the database and extracting the first one:
best = Score.objects.all().order_by('-points')[0]
But I'm having problems getting the ones close to the presented player (Anna, in this case). I don't want to go searching through the complete list, as the complete list of players can be quite long.
Maybe there's a way to know the position a register occupies in an ordered list...
Any ideas on how to achieve it?
|
[
"Get the COUNT() of records that have a higher points.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002236181_django_python.txt
|
Q:
Emulate floating point string conversion behaviour of Linux on Windows
I've encountered an annoying problem in outputting a floating point number. When I format 11.545 with a precision of 2 decimal points on Windows it outputs "11.55", as I would expect. However, when I do the same on Linux the output is "11.54"!
I originally encountered the problem in Python, but further investigation showed that the difference is in the underlying C runtime library. (The architecture is x86-x64 in both cases.) Running the following line of C produces the different results on Windows and Linux, same as it does in Python.
printf("%.2f", 11.545);
To shed more light on this I printed the number to 20 decimal places ("%.20f"):
Windows: 11.54500000000000000000
Linux: 11.54499999999999992895
I know that 11.545 cannot be stored precisely as a binary number. So what appears to be happening is that Linux outputs the number it's actually stored with the best possible precision, while Windows outputs the simplest decimal representation of it, ie. tries to guess what the user most likely meant.
My question is: is there any (reasonable) way to emulate the Linux behaviour on Windows?
(While the Windows behaviour is certainly the intuitive one, in my case I actually need to compare the output of a Windows program with that of a Linux program and the Windows one is the only one I can change. By the way, I tried to look at the Windows source of printf, but the actual function that does the float->string conversion is _cfltcvt_l and its source doesn't appear to be available.)
EDIT: the plot thickens! The theory about this being caused by an imprecise representation might be wrong, because 0.125 does have an exact binary representation and it's still different when output with '%.2f' % 0.125:
Windows: 0.13
Linux: 0.12
However, round(0.125, 2) returns 0.13 on both Windows and Linux.
A:
First of all it sounds like Windows has it wrong right in this case (not that this really matters). The C Standard requires that the value output by %.2f is rounded to the appropriate number of digits. The best known algorithm for this is dtoa implemented by David M. Gay. You can probably port this to Windows or find a native implementation.
If you haven't already read "How to Print Floating-Point Numbers Accurately" by Steele and White, find a copy and read it. It is definitely an enlightening read. Make sure to find the original from the late 70's. I think that I purchased mine from ACM or IEEE at some point.
A:
I don't think Windows is doing anything especially clever (like trying to reinterpret the float in base 10) here: I'd guess that it's simply computing the first 17 significant digits accurately (which would give '11.545000000000000') and then tacking extra zeros on the end to make up the requested number of places after the point.
As others have said, the different results for 0.125 come from Windows using round-half-up and Linux using round-half-to-even.
Note that for Python 3.1 (and Python 2.7, when it appears), the result of formatting a float will be platform independent (except possibly on unusual platforms).
A:
The decimal module gives you access to several rounding modes:
import decimal
fs = ['11.544','11.545','11.546']
def convert(f,nd):
# we want 'nd' beyond the dec point
nd = f.find('.') + nd
c1 = decimal.getcontext().copy()
c1.rounding = decimal.ROUND_HALF_UP
c1.prec = nd
d1 = c1.create_decimal(f)
c2 = decimal.getcontext().copy()
c2.rounding = decimal.ROUND_HALF_DOWN
c2.prec = nd
d2 = c2.create_decimal(f)
print d1, d2
for f in fs:
convert(f,2)
You can construct a decimal from an int or a string. In your case feed it a string with more digits than you want and truncate by setting context.prec.
Here is a link to a pymotw post w/ a detailed overview of the decimal module:
http://broadcast.oreilly.com/2009/08/pymotw-decimal---fixed-and-flo.html
A:
Consider comparing floating point numbers with some tolerance/epsilon instead. This is much more robust than trying to match exactly.
What I mean is, except saying that two floats are equal when:
f1 == f2
Say they're equal when:
fabs(f1 - f2) < eps
For some small eps. More details on this issue can be found here.
A:
You could try subtracting (or adding for a negative number) a small delta that will have no effect on the rounding for numbers far enough away from the precision.
For example, if you're rounding with %.2f, try this version on Windows:
printf("%.2f", 11.545 - 0.001);
Floating point numbers are notoriously problematic if you don't know what's happening under the covers. In that case, your best bet is to write (or use) a decimal type library to alleviate the problems.
The example program:
#include <stdio.h>
int main (void) {
printf("%.20f\n", 11.545);
printf("%.2f\n", 11.545);
printf("%.2f\n", 11.545 + 0.001);
return 0;
}
outputs this in my Cygwin environment:
11.54499999999999992895
11.54
11.55
which is okay for your specific case (it's going the wrong way but should hopefully apply in the other direction as well: you need to test it) but you should check your entire possible input range if you want to be certain this will work for all your cases.
Update:
Evgeny, based on your comment:
It works for this specific case, but not as a general solution. For instance if the number I want to format is 0.545 instead of 11.545 then '%.2f' % (0.545 - 0.001) returns "0.54", while '%.2f' % 0.545 on Linux correctly returns "0.55".
that's why I said you would have to check the entire range to see if it would work, and why I stated a decimal data type would be preferable.
If you want decimal accuracy, that's what you'll have to do. But you might want to consider the cases in that range where Linux goes the other way too (as per your comment) - there may be situation where Linux and Windows disagree in the opposite direction to what you've found - a decimal type probably won't solve that.
You may need to make your comparison tools a little more intelligent inasmuch as they can ignore a difference of 1 in the final fractional place.
A:
You may be able to do subtract a tiny amount from the value to force the rounding down
print "%.2f"%(11.545-1e-12)
|
Emulate floating point string conversion behaviour of Linux on Windows
|
I've encountered an annoying problem in outputting a floating point number. When I format 11.545 with a precision of 2 decimal points on Windows it outputs "11.55", as I would expect. However, when I do the same on Linux the output is "11.54"!
I originally encountered the problem in Python, but further investigation showed that the difference is in the underlying C runtime library. (The architecture is x86-x64 in both cases.) Running the following line of C produces the different results on Windows and Linux, same as it does in Python.
printf("%.2f", 11.545);
To shed more light on this I printed the number to 20 decimal places ("%.20f"):
Windows: 11.54500000000000000000
Linux: 11.54499999999999992895
I know that 11.545 cannot be stored precisely as a binary number. So what appears to be happening is that Linux outputs the number it's actually stored with the best possible precision, while Windows outputs the simplest decimal representation of it, ie. tries to guess what the user most likely meant.
My question is: is there any (reasonable) way to emulate the Linux behaviour on Windows?
(While the Windows behaviour is certainly the intuitive one, in my case I actually need to compare the output of a Windows program with that of a Linux program and the Windows one is the only one I can change. By the way, I tried to look at the Windows source of printf, but the actual function that does the float->string conversion is _cfltcvt_l and its source doesn't appear to be available.)
EDIT: the plot thickens! The theory about this being caused by an imprecise representation might be wrong, because 0.125 does have an exact binary representation and it's still different when output with '%.2f' % 0.125:
Windows: 0.13
Linux: 0.12
However, round(0.125, 2) returns 0.13 on both Windows and Linux.
|
[
"First of all it sounds like Windows has it wrong right in this case (not that this really matters). The C Standard requires that the value output by %.2f is rounded to the appropriate number of digits. The best known algorithm for this is dtoa implemented by David M. Gay. You can probably port this to Windows or find a native implementation.\nIf you haven't already read \"How to Print Floating-Point Numbers Accurately\" by Steele and White, find a copy and read it. It is definitely an enlightening read. Make sure to find the original from the late 70's. I think that I purchased mine from ACM or IEEE at some point.\n",
"I don't think Windows is doing anything especially clever (like trying to reinterpret the float in base 10) here: I'd guess that it's simply computing the first 17 significant digits accurately (which would give '11.545000000000000') and then tacking extra zeros on the end to make up the requested number of places after the point.\nAs others have said, the different results for 0.125 come from Windows using round-half-up and Linux using round-half-to-even.\nNote that for Python 3.1 (and Python 2.7, when it appears), the result of formatting a float will be platform independent (except possibly on unusual platforms).\n",
"The decimal module gives you access to several rounding modes:\nimport decimal\n\nfs = ['11.544','11.545','11.546']\n\ndef convert(f,nd):\n # we want 'nd' beyond the dec point\n nd = f.find('.') + nd\n c1 = decimal.getcontext().copy()\n c1.rounding = decimal.ROUND_HALF_UP\n c1.prec = nd\n d1 = c1.create_decimal(f)\n c2 = decimal.getcontext().copy()\n c2.rounding = decimal.ROUND_HALF_DOWN\n c2.prec = nd \n d2 = c2.create_decimal(f)\n print d1, d2\n\nfor f in fs:\n convert(f,2)\n\nYou can construct a decimal from an int or a string. In your case feed it a string with more digits than you want and truncate by setting context.prec. \nHere is a link to a pymotw post w/ a detailed overview of the decimal module:\nhttp://broadcast.oreilly.com/2009/08/pymotw-decimal---fixed-and-flo.html\n",
"Consider comparing floating point numbers with some tolerance/epsilon instead. This is much more robust than trying to match exactly.\nWhat I mean is, except saying that two floats are equal when:\nf1 == f2\n\nSay they're equal when:\nfabs(f1 - f2) < eps\n\nFor some small eps. More details on this issue can be found here.\n",
"You could try subtracting (or adding for a negative number) a small delta that will have no effect on the rounding for numbers far enough away from the precision.\nFor example, if you're rounding with %.2f, try this version on Windows:\nprintf(\"%.2f\", 11.545 - 0.001);\n\nFloating point numbers are notoriously problematic if you don't know what's happening under the covers. In that case, your best bet is to write (or use) a decimal type library to alleviate the problems.\n\nThe example program:\n#include <stdio.h>\nint main (void) {\n printf(\"%.20f\\n\", 11.545);\n printf(\"%.2f\\n\", 11.545);\n printf(\"%.2f\\n\", 11.545 + 0.001);\n return 0;\n}\n\noutputs this in my Cygwin environment:\n11.54499999999999992895\n11.54\n11.55\n\nwhich is okay for your specific case (it's going the wrong way but should hopefully apply in the other direction as well: you need to test it) but you should check your entire possible input range if you want to be certain this will work for all your cases.\n\nUpdate:\nEvgeny, based on your comment:\n\nIt works for this specific case, but not as a general solution. For instance if the number I want to format is 0.545 instead of 11.545 then '%.2f' % (0.545 - 0.001) returns \"0.54\", while '%.2f' % 0.545 on Linux correctly returns \"0.55\".\n\nthat's why I said you would have to check the entire range to see if it would work, and why I stated a decimal data type would be preferable.\nIf you want decimal accuracy, that's what you'll have to do. But you might want to consider the cases in that range where Linux goes the other way too (as per your comment) - there may be situation where Linux and Windows disagree in the opposite direction to what you've found - a decimal type probably won't solve that.\nYou may need to make your comparison tools a little more intelligent inasmuch as they can ignore a difference of 1 in the final fractional place.\n",
"You may be able to do subtract a tiny amount from the value to force the rounding down\nprint \"%.2f\"%(11.545-1e-12)\n\n"
] |
[
2,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"c",
"floating_point",
"precision",
"printf",
"python"
] |
stackoverflow_0002234303_c_floating_point_precision_printf_python.txt
|
Q:
Problem deploying Django-Mingus with Flup and Cherokee. Strange admin behaviour
I have a django-mingus blog running perfectly fine with the integrated development web server of django. It's installed in a virtualenv.
Once deployed using the django app wizard of cherokee 0.99.42 the admin pannel is displaying a strange behaviour. Sometimes all apps are displayed in the admin pannel sometime only a subset of the apps are displayed. It's always the same apps that disapear from the main admin view.
The manage.py runfcgi command is launched through the python interpreter installed in the virtualenv.
Do you have a method to track that kind of problem ? Could it be related to environment variable that are not set correctly ?
EDIT:
Could this be a circular import problem ?
2nd EDIT:
The same problem occur with nginx.
Adding Debug=True to the ./manage.py runfcgi command make the setup stable.
A:
I dropped all tables from the database, upgraded to last version of django-mingus after having deleted some dependencies to get them clean installed and I launched the scgi process using a shell script that activate the virtual environment before.
Now everything seems to be stable.
|
Problem deploying Django-Mingus with Flup and Cherokee. Strange admin behaviour
|
I have a django-mingus blog running perfectly fine with the integrated development web server of django. It's installed in a virtualenv.
Once deployed using the django app wizard of cherokee 0.99.42 the admin pannel is displaying a strange behaviour. Sometimes all apps are displayed in the admin pannel sometime only a subset of the apps are displayed. It's always the same apps that disapear from the main admin view.
The manage.py runfcgi command is launched through the python interpreter installed in the virtualenv.
Do you have a method to track that kind of problem ? Could it be related to environment variable that are not set correctly ?
EDIT:
Could this be a circular import problem ?
2nd EDIT:
The same problem occur with nginx.
Adding Debug=True to the ./manage.py runfcgi command make the setup stable.
|
[
"I dropped all tables from the database, upgraded to last version of django-mingus after having deleted some dependencies to get them clean installed and I launched the scgi process using a shell script that activate the virtual environment before.\nNow everything seems to be stable.\n"
] |
[
0
] |
[] |
[] |
[
"cherokee",
"django",
"python",
"scgi"
] |
stackoverflow_0002175377_cherokee_django_python_scgi.txt
|
Q:
Will Python use all processors in thread mode?
While developing a Django app deployed on Apache mod_wsgi I found that in case of multithreading (Python threads; mod_wsgi processes=1 threads=8) Python won't use all available processors. With the multiprocessing approach (mod_wsgi processes=8 threads=1) all is fine and I can load my machine at full.
So the question: is this Python behavior normal? I doubt it because using 1 process with few threads is the default mod_wsgi approach.
The system is:
2xIntel Xeon 5XXX series (8 cores (16 with hyperthreading)) on FreeBSD 7.2 AMD64 and Python 2.6.4
Thanks all for answers.
We all found that this behavior is normal because of GIL. Here is a good explanation:
http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/
or stackoverflow GIL discussion: What is a global interpreter lock (GIL)?.
A:
Will Python use all processors in thread mode? No.
Python won't use all available processors; is this Python behavior normal? Yes, it's normal because of the GIL.
For a discussion see http://mail.python.org/pipermail/python-3000/2007-May/007414.html.
You may find that having a couple (or 4) of threads per core/process can still improve performance if there is some blocking, for example waiting for a response from the database would cause that process to block other connections otherwise.
A:
Will python use all processors in thread mode? No.
It this normal? Yes, this is normal. Python makes no effort to locate all your cores.
"1 process with few threads is default mod_wsgi approach". But that's not optimal or even desirable. That's just a default. Don't read anything into it.
If you want to use all your computer's resources, make the OS handle it. Use processes.
The distinction between multi-processing and multi-threading is hard to measure for the most part. Using processes or threads barely matters. It's usually simpler to use processes, since there's trivial OS support for this.
Bottom Line
Use multiple processes, that allows the OS (and Apache) to make as much use as possible of the system.
Threads share a limited set of I/O resources for the Process they're part of, and web page serving is I/O bound. Processes have independent I/O resources and will more easily max out your processor.
A:
There is still hope. The GIL is only an implementation artifact of the C Python implementation that you download from python.org. Jython and IronPython are two other implementations of Python, and they have no GIL, so you may have better threading results with one of them.
A:
I don't know if it is still the case, but there is a global lock in the Python interpreter, which prevents the use of all processor resources from a single interpreter, even when using multi threading. IIRC, the global lock has to do with I/O.
It seems you are watching the result of this lock, so, personally, I would use multiple processes with a single thread.
A:
Yes. Python is not really multi-threaded. Instead, there is a global lock and each thread gets to execute a few operations in turn. This makes it much more simple to write MT applications in Python since there can't be any problems with stale caches, etc.
So one Python process can only ever occupy a single CPU. To fully utilize a multi-core system, you must run several Python processes.
|
Will Python use all processors in thread mode?
|
While developing a Django app deployed on Apache mod_wsgi I found that in case of multithreading (Python threads; mod_wsgi processes=1 threads=8) Python won't use all available processors. With the multiprocessing approach (mod_wsgi processes=8 threads=1) all is fine and I can load my machine at full.
So the question: is this Python behavior normal? I doubt it because using 1 process with few threads is the default mod_wsgi approach.
The system is:
2xIntel Xeon 5XXX series (8 cores (16 with hyperthreading)) on FreeBSD 7.2 AMD64 and Python 2.6.4
Thanks all for answers.
We all found that this behavior is normal because of GIL. Here is a good explanation:
http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/
or stackoverflow GIL discussion: What is a global interpreter lock (GIL)?.
|
[
"Will Python use all processors in thread mode? No.\nPython won't use all available processors; is this Python behavior normal? Yes, it's normal because of the GIL.\nFor a discussion see http://mail.python.org/pipermail/python-3000/2007-May/007414.html.\nYou may find that having a couple (or 4) of threads per core/process can still improve performance if there is some blocking, for example waiting for a response from the database would cause that process to block other connections otherwise.\n",
"\nWill python use all processors in thread mode? No.\nIt this normal? Yes, this is normal. Python makes no effort to locate all your cores.\n\"1 process with few threads is default mod_wsgi approach\". But that's not optimal or even desirable. That's just a default. Don't read anything into it.\n\nIf you want to use all your computer's resources, make the OS handle it. Use processes.\nThe distinction between multi-processing and multi-threading is hard to measure for the most part. Using processes or threads barely matters. It's usually simpler to use processes, since there's trivial OS support for this.\nBottom Line\nUse multiple processes, that allows the OS (and Apache) to make as much use as possible of the system.\nThreads share a limited set of I/O resources for the Process they're part of, and web page serving is I/O bound. Processes have independent I/O resources and will more easily max out your processor.\n",
"There is still hope. The GIL is only an implementation artifact of the C Python implementation that you download from python.org. Jython and IronPython are two other implementations of Python, and they have no GIL, so you may have better threading results with one of them.\n",
"I don't know if it is still the case, but there is a global lock in the Python interpreter, which prevents the use of all processor resources from a single interpreter, even when using multi threading. IIRC, the global lock has to do with I/O.\nIt seems you are watching the result of this lock, so, personally, I would use multiple processes with a single thread.\n",
"Yes. Python is not really multi-threaded. Instead, there is a global lock and each thread gets to execute a few operations in turn. This makes it much more simple to write MT applications in Python since there can't be any problems with stale caches, etc.\nSo one Python process can only ever occupy a single CPU. To fully utilize a multi-core system, you must run several Python processes.\n"
] |
[
10,
4,
3,
1,
1
] |
[] |
[] |
[
"django",
"multiprocessing",
"multithreading",
"performance",
"python"
] |
stackoverflow_0002236321_django_multiprocessing_multithreading_performance_python.txt
|
Q:
PHP / cURL problem opening remote file
We have a script which pulls some XML from a remote server. If this script is running on any server other than production, it works.
Upload it to production however, and it fails. It is using cURL for the request but it doesn't matter how we do it - fopen, file_get_contents, sockets - it just times out. This also happens if I use a Python script to request the URL.
The same script, supplied with another URL to query, works - every time. Obviously it doesn't return the XML we're looking for but it DOES return SOMETHINg - it CAN connect to the remote server.
If this URL is requested via the command line using, for example, curl or wget, again, data is returned. It's not the data we're looking for (in fact, it returns an empty root element) but something DOES come back.
Interestingly, if we strip out query string elements from the URL (the full URL has 7 query string elements and runs to about 450 characters in total) the script will return the same empty XML response. Certain combinations of the query string will once again cause the script to time out.
This, as you can imagine, has me utterly baffled - it seems to work in every circumstance EXCEPT the one it needs to work in. We can get a response on our dev servers, we can get a response on the command line, we can get a response if we drop certain QS elements - we just can't get the response we want with the correct URL on the LIVE server.
Does anyone have any suggestions at all? I'm at my wits end!
A:
Run Wireshark and see how far the request goes. Could be a firewall issue, a DNS resolution problem, among other things.
Also, try bumping your curl timeout to something much higher, like 300s, and see how it goes.
|
PHP / cURL problem opening remote file
|
We have a script which pulls some XML from a remote server. If this script is running on any server other than production, it works.
Upload it to production however, and it fails. It is using cURL for the request but it doesn't matter how we do it - fopen, file_get_contents, sockets - it just times out. This also happens if I use a Python script to request the URL.
The same script, supplied with another URL to query, works - every time. Obviously it doesn't return the XML we're looking for but it DOES return SOMETHINg - it CAN connect to the remote server.
If this URL is requested via the command line using, for example, curl or wget, again, data is returned. It's not the data we're looking for (in fact, it returns an empty root element) but something DOES come back.
Interestingly, if we strip out query string elements from the URL (the full URL has 7 query string elements and runs to about 450 characters in total) the script will return the same empty XML response. Certain combinations of the query string will once again cause the script to time out.
This, as you can imagine, has me utterly baffled - it seems to work in every circumstance EXCEPT the one it needs to work in. We can get a response on our dev servers, we can get a response on the command line, we can get a response if we drop certain QS elements - we just can't get the response we want with the correct URL on the LIVE server.
Does anyone have any suggestions at all? I'm at my wits end!
|
[
"Run Wireshark and see how far the request goes. Could be a firewall issue, a DNS resolution problem, among other things.\nAlso, try bumping your curl timeout to something much higher, like 300s, and see how it goes.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"curl",
"php",
"python",
"xml"
] |
stackoverflow_0002236864_apache_curl_php_python_xml.txt
|
Q:
Passing arguments to the generic views Django queryset
I would like to make a queryset on a generic view in this way:
category_info = {
'queryset' : ModelObject.objects.filter(category=category_id)
}
where the category_id will be stated on the URL
(r'^category/(?P<category_id>\d+)$', 'object_list', category_info )
But I don't know how to take the data from the URL and pass it to the category info...
A:
You'll have to define your own view and return the generic view from within:
urls.py:
(r'^category/(?P<category_id>\d+)$', 'myapp.views.category_list')
myapp/views.py
from django.views.generic.list_detail import object_list
def category_list(request, category_id):
queryset = ModelObject.objects.filter(category=category_id)
return object_list(request, queryset=queryset)
You can also customise the generic view further, using the parameters mentioned in the documentation. (You may like to also verify that the category exists, throwing a 404 when it doesn't)
|
Passing arguments to the generic views Django queryset
|
I would like to make a queryset on a generic view in this way:
category_info = {
'queryset' : ModelObject.objects.filter(category=category_id)
}
where the category_id will be stated on the URL
(r'^category/(?P<category_id>\d+)$', 'object_list', category_info )
But I don't know how to take the data from the URL and pass it to the category info...
|
[
"You'll have to define your own view and return the generic view from within:\nurls.py:\n(r'^category/(?P<category_id>\\d+)$', 'myapp.views.category_list')\n\nmyapp/views.py\nfrom django.views.generic.list_detail import object_list\ndef category_list(request, category_id):\n queryset = ModelObject.objects.filter(category=category_id)\n return object_list(request, queryset=queryset)\n\nYou can also customise the generic view further, using the parameters mentioned in the documentation. (You may like to also verify that the category exists, throwing a 404 when it doesn't)\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002236886_django_python.txt
|
Q:
How can I write to the textfile with "while"?
while 1:
text_file = open("write_it.txt", "w")
word = input("Please add to a text file: ")
What else do I need to add to make my code run properly?
A:
This should work:
text_file = open("write_it.txt", "w")
while 1:
word = input("Please add to a text file: ")
if not word:
break
text_file.write(word)
text_file.close()
A:
Not sure, but that open statement inside of the while couldn't be affecting its behaviour?
Have you tried just moving it out of while loop?
|
How can I write to the textfile with "while"?
|
while 1:
text_file = open("write_it.txt", "w")
word = input("Please add to a text file: ")
What else do I need to add to make my code run properly?
|
[
"This should work:\ntext_file = open(\"write_it.txt\", \"w\")\nwhile 1:\n word = input(\"Please add to a text file: \")\n if not word:\n break\n text_file.write(word)\ntext_file.close()\n\n",
"Not sure, but that open statement inside of the while couldn't be affecting its behaviour?\nHave you tried just moving it out of while loop?\n"
] |
[
3,
0
] |
[] |
[] |
[
"file_io",
"python"
] |
stackoverflow_0002237154_file_io_python.txt
|
Q:
Easiest way to display a pdf, ps or dvi file from python in linux
I have created an application with python and wxpython.
I would like to display a help file in pdf, ps or dvi format in GNU/Linux.
Could use the distribution pdf viewer, but not so easy when you don't know which they have.
Any ideas on how to solve this?
A:
Invoke xdg-open against the file.
A:
Try also evince.
|
Easiest way to display a pdf, ps or dvi file from python in linux
|
I have created an application with python and wxpython.
I would like to display a help file in pdf, ps or dvi format in GNU/Linux.
Could use the distribution pdf viewer, but not so easy when you don't know which they have.
Any ideas on how to solve this?
|
[
"Invoke xdg-open against the file.\n",
"Try also evince.\n"
] |
[
4,
1
] |
[] |
[] |
[
"linux",
"pdf",
"python",
"wxpython"
] |
stackoverflow_0002235090_linux_pdf_python_wxpython.txt
|
Q:
Use Python logging to determine where a method was called from
I'm trying to debug a Python Django app.
I've got additional fields being added to a model.
I've tracked this down to one method:
django.db.models.options.add_field()
The only place this method is called is:
django.db.models.fields.init.contribute_to_class()
def contribute_to_class(self, cls, name):
self.set_attributes_from_name(name)
cls._meta.add_field(self)
if self.choices:
setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self))
I'm trying to use Logging to determine where the additions to the User model are occurring.
Is there anyway to that I can set a logging message that will record where this contribute_to_class() method was called from?
A:
Use traceback module.
|
Use Python logging to determine where a method was called from
|
I'm trying to debug a Python Django app.
I've got additional fields being added to a model.
I've tracked this down to one method:
django.db.models.options.add_field()
The only place this method is called is:
django.db.models.fields.init.contribute_to_class()
def contribute_to_class(self, cls, name):
self.set_attributes_from_name(name)
cls._meta.add_field(self)
if self.choices:
setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self))
I'm trying to use Logging to determine where the additions to the User model are occurring.
Is there anyway to that I can set a logging message that will record where this contribute_to_class() method was called from?
|
[
"Use traceback module.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"logging",
"python"
] |
stackoverflow_0002237355_django_logging_python.txt
|
Q:
Using sub filters/queries in Google App Engine
I'm trying to use figure out how to sub query a query that uses a filter. From what I've figured out so far while using .filter() it changes the original query, that leads to a second .filter() would also have to match the first filter.
I would like to make something like this:
modules = data.Modules.all().filter('page = ', page.key())
modules.filter('name = ', 'Test')
modules.filter('name = ', 'Test2')
I can't get the "Test2" filter to work. The only solution I have at the moment is to make all new queries.
data.Modules.all().filter('page = ', page.key()).filter('name = ', "Test").get()
data.Modules.all().filter('page = ', page.key()).filter('name = ', "Test2").get()
Or write the same as an GQL. But for me it seams quite stupid way to go.
I've looked at using ancestors, but I don't quite understand it and honestly don't know if that's the way to go.
Any ideas?
..fredrik
A:
It appears that what you're trying to do is an OR query, which isn't supported in App Engine. You can use an IN query, which simulates this by doing multiple queries for you.
The reason the first thing you tried doesn't work is that you're trying to filter your query so that your results match both "Test" and "Test2", which obviously will never be true for a non-list property.
|
Using sub filters/queries in Google App Engine
|
I'm trying to use figure out how to sub query a query that uses a filter. From what I've figured out so far while using .filter() it changes the original query, that leads to a second .filter() would also have to match the first filter.
I would like to make something like this:
modules = data.Modules.all().filter('page = ', page.key())
modules.filter('name = ', 'Test')
modules.filter('name = ', 'Test2')
I can't get the "Test2" filter to work. The only solution I have at the moment is to make all new queries.
data.Modules.all().filter('page = ', page.key()).filter('name = ', "Test").get()
data.Modules.all().filter('page = ', page.key()).filter('name = ', "Test2").get()
Or write the same as an GQL. But for me it seams quite stupid way to go.
I've looked at using ancestors, but I don't quite understand it and honestly don't know if that's the way to go.
Any ideas?
..fredrik
|
[
"It appears that what you're trying to do is an OR query, which isn't supported in App Engine. You can use an IN query, which simulates this by doing multiple queries for you.\nThe reason the first thing you tried doesn't work is that you're trying to filter your query so that your results match both \"Test\" and \"Test2\", which obviously will never be true for a non-list property.\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002237224_google_app_engine_python.txt
|
Q:
How can I record live video with gstreamer without dropping frames?
I'm trying to use gstreamer 0.10 from Python to simultaneously display a v4l2 video source and record it to xvid-in-avi. Over a long period of time the computer would be fast enough to do this but if another program uses the disk it drops frames. That's bad enough, but on playback there are bursts of movement in the video where frames were dropped instead of displaying the frames we were able to encode at a lower framerate.
The pipeline is v4l2src ! capsfilter ! tee ! queue ! xvidenc ! avimux ! filesink and the tee also sinks to a queue ! xvimagesink sync=false. I've tried adding videorate in front of xvidenc but that seems to make things worse.
I've considered spooling the uncompressed video to disk in this pipeline and encoding it in a background thread. What else could I do to solve this problem? Is xvidenc or avimux doing the wrong thing with dropped frames? Could I dramatically increase the size of the queue preceding my encoder?
A:
tee will block if either output blocks, so it's probably your bottleneck. I suggest to write the stream that takes longer to encode to disk and encode from there.
A:
and you need to write xvimagesink, not xvimagesync
|
How can I record live video with gstreamer without dropping frames?
|
I'm trying to use gstreamer 0.10 from Python to simultaneously display a v4l2 video source and record it to xvid-in-avi. Over a long period of time the computer would be fast enough to do this but if another program uses the disk it drops frames. That's bad enough, but on playback there are bursts of movement in the video where frames were dropped instead of displaying the frames we were able to encode at a lower framerate.
The pipeline is v4l2src ! capsfilter ! tee ! queue ! xvidenc ! avimux ! filesink and the tee also sinks to a queue ! xvimagesink sync=false. I've tried adding videorate in front of xvidenc but that seems to make things worse.
I've considered spooling the uncompressed video to disk in this pipeline and encoding it in a background thread. What else could I do to solve this problem? Is xvidenc or avimux doing the wrong thing with dropped frames? Could I dramatically increase the size of the queue preceding my encoder?
|
[
"tee will block if either output blocks, so it's probably your bottleneck. I suggest to write the stream that takes longer to encode to disk and encode from there.\n",
"and you need to write xvimagesink, not xvimagesync\n"
] |
[
5,
2
] |
[] |
[] |
[
"gstreamer",
"linux",
"python"
] |
stackoverflow_0000677641_gstreamer_linux_python.txt
|
Q:
TDD - beginner problems and stumbling blocks
While I've written unit tests for most of the code I've done, I only recently got my hands on a copy of TDD by example by Kent Beck. I have always regretted certain design decisions I made since they prevented the application from being 'testable'. I read through the book and while some of it looks alien, I felt that I could manage it and decided to try it out on my current project which is basically a client/server system where the two pieces communicate via. USB. One on the gadget and the other on the host. The application is in Python.
I started off and very soon got entangled in a mess of rewrites and tiny tests which I later figured didn't really test anything. I threw away most of them and and now have a working application for which the tests have all coagulated into just 2.
Based on my experiences, I have a few questions which I'd like to ask. I gained some information from New to TDD: Are there sample applications with tests to show how to do TDD? but have some specific questions which I'd like answers to/discussion on.
Kent Beck uses a list which he adds to and strikes out from to guide the development process. How do you make such a list? I initially had a few items like "server should start up", "server should abort if channel is not available" etc. but they got mixed and finally now, it's just something like "client should be able to connect to server" (which subsumed server startup etc.).
How do you handle rewrites? I initially selected a half duplex system based on named pipes so that I could develop the application logic on my own machine and then later add the USB communication part. It them moved to become a socket based thing and then moved from using raw sockets to using the Python SocketServer module. Each time things changed, I found that I had to rewrite considerable parts of the tests which was annoying. I'd figured that the tests would be a somewhat invariable guide during my development. They just felt like more code to handle.
I needed a client and a server to communicate through the channel to test either side. I could mock one of the sides to test the other but then the whole channel wouldn't be tested and I worry that I'd miss that. This detracted from the whole red/green/refactor rhythm. Is this just lack of experience or am I doing something wrong?
The "Fake it till you make it" left me with a lot of messy code that I later spent a lot of time to refactor and clean up. Is this the way things work?
At the end of the session, I now have my client and server running with around 3 or 4 unit tests. It took me around a week to do it. I think I could have done it in a day if I were using the unit tests after code way. I fail to see the gain.
I'm looking for comments and advice from people who have implemented large non trivial projects completely (or almost completely) using this methodology. It makes sense to me to follow the way after I have something already running and want to add a new feature but doing it from scratch seems to tiresome and not worth the effort.
P.S. : Please let me know if this should be community wiki and I'll mark it like that.
Update 0 : All the answers were equally helpful. I picked the one I did because it resonated with my experiences the most.
Update 1: Practice Practice Practice!
A:
As a preliminary comment, TDD takes practice. When I look back at the tests I wrote when I began TDD, I see lots of issues, just like when I look at code I wrote a few year ago. Keep doing it, and just like you begin to recognize good code from bad, the same things will happen with your tests - with patience.
How do you make such a list? I
initially had a few items like "server
should start up", "server should abort
if channel is not available" etc. but
they got mixed and finally now, it's
just something like "client should be
able to connect to server"
"The list" can be rather informal (that's the case in Beck's book) but when you move into making the items into tests, try to write the statements in a "[When something happens to this] then [this condition should be true on that]" format. This will force you to think more about what it is you are verifying, how you would verify it and translates directly into tests - or if it doesn't it should give you a clue about which piece of functionality is missing. Think use case / scenario. For instance "server should start up" is unclear, because nobody is initiating an action.
Each time things changed, I found that
I had to rewrite considerable parts of
the tests which was annoying. I'd
figured that the tests would be a
somewhat invariable guide during my
development. They just felt like more
code to handle.
First, yes, tests are more code, and requires maintenance - and writing maintainable tests takes practice. I agree with S. Lott, if you need to change your tests a lot, you are probably testing "too deep". Ideally you want to test at the level of the public interface, which is not likely to change, and not at the level of the implementation detail, which could evolve. But part of the exercise is about coming up with a design, so you should expect to get some of it wrong and have to move/refactor your tests as well.
I could mock one of the sides to test
the other but then the whole channel
wouldn't be tested and I worry that
I'd miss that.
Not totally sure about that one. From the sound of it, using a mock was the right idea: take one side, mock the other one, and check that each side works, assuming the other one is implemented properly. Testing the whole system together is integration testing, which you also want to do, but is typically not part of the TDD process.
The "Fake it till you make it" left me
with a lot of messy code that I later
spent a lot of time to refactor and
clean up. Is this the way things work?
You should spend a lot of time refactoring while doing TDD. On the other hand, when you fake it, it's temporary, and your immediate next step should be to un-fake it. Typically you shouldn't have multiple tests passing because you faked it - you should be focusing on one piece at a time, and work on refactoring it ASAP.
I think I could have done it in a day
if I were using the unit tests after
code way. I fail to see the gain.
Again, it takes practice, and you should get faster over time. Also, sometimes TDD is more fruitful than others, I find that in some situations, when I know exactly the code I want to write, it's just faster to write a good part of the code, and then write tests.
Besides Beck, one book I enjoyed is The Art of Unit Testing, by Roy Osherove. It's not a TDD book, and it is .Net-oriented, but you might want to give it a look anyways: a good part is about how to write maintainable tests, tests quality and related questions. I found that the book resonated with my experience after having written tests and sometimes struggled to do it right...
So my advice is, don't throw the towel too fast, and give it some time. You might also want to give it a shot on something easier - testing server communication related things doesn't sound like the easiest project to start with!
A:
Kent Beck uses a list ... finally now, it's just something like "client should be able to connect to server" (which subsumed server startup etc.).
Often a bad practice.
Separate tests for each separate layer of the architecture are good.
Consolidated tests tend to obscure architectural issues.
However, only test the public functions. Not every function.
And don't invest a lot of time optimizing your testing. Redundancy in the tests doesn't hurt as much as it does in the working application. If things change and one test works, but another test breaks, perhaps then you can refactor your tests. Not before.
2. How do you handle rewrites? ... I found that I had to rewrite considerable parts of the tests.
You're testing at too low a level of detail. Test the outermost, public, visible interface. The part that's supposed to be unchanging.
And
Yes, significant architectural change means significant testing change.
And
The test code is how you prove things work. It is almost as important as the application itself. Yes, it's more code. Yes, you must manage it.
3. I needed a client and a server to communicate through the channel to test either side. I could mock one of the sides to test the other but then the whole channel wouldn't be tested ...
There are unit tests. With mocks.
There are integration tests, which test the whole thing.
Don't confuse them.
You can use unit test tools to do integration tests, but they're different things.
And you need to do both.
4. The "Fake it till you make it" left me with a lot of messy code that I later spent a lot of time to refactor and clean up. Is this the way things work?
Yes. That's exactly how it works. In the long run, some people find this more effective than straining their brains trying to do all the design up front. Some people don't like this and want to do all the design up front; you're free to do a lot of design up front if you want to.
I've found that refactoring is a good thing and design up front is too hard. Maybe it's because I've been coding for almost 40 years and my brain is wearing out.
5. I fail to see the gain.
All the true geniuses find that testing slows them down.
The rest of us can't be sure our code works until we have a complete set of tests that prove that it works.
If you don't need proof that your code works, you don't need testing.
A:
Q. Kent Beck uses a list which he adds to and strikes out from to guide the development process. How do you make such a list? I initially had a few items like "server should start up", "server should abort if channel is not available" etc. but they got mixed and finally now, it's just something like "client should be able to connect to server" (which subsumed server startup etc.).
I start by picking anything I might check. In your example, you chose "server starts".
Server starts
Now I look for any simpler test I might want to write. Something with less variation, and fewer moving parts. I might consider "configured server correctly", for example.
Configured server correctly
Server starts
Really, though, "server starts" depends on "configured server correctly", so I make that link clear.
Configured server correctly
Server starts if configured correctly
Now I look for variations. I ask, "What could go wrong?" I could configure the server incorrectly. How many different ways that matter? Each of those makes a test. How might the server not start even though I configured it correctly? Each case of that makes a test.
Q. How do you handle rewrites? I initially selected a half duplex system based on named pipes so that I could develop the application logic on my own machine and then later add the USB communication part. It them moved to become a socket based thing and then moved from using raw sockets to using the Python SocketServer module. Each time things changed, I found that I had to rewrite considerable parts of the tests which was annoying. I'd figured that the tests would be a somewhat invariable guide during my development. They just felt like more code to handle.
When I change behavior, I find it reasonable to change the tests, and even to change them first! If I have to change tests that don't directly check the behavior I'm in the process of changing, though, that's a sign that my tests depend on too many different behaviors. Those are integration tests, which I think are a scam. (Google "Integration tests are a scam")
Q. I needed a client and a server to communicate through the channel to test either side. I could mock one of the sides to test the other but then the whole channel wouldn't be tested and I worry that I'd miss that. This detracted from the whole red/green/refactor rhythm. Is this just lack of experience or am I doing something wrong?
If I build a client, a server, and a channel, then I try to check each in isolation. I start with the client, and when I test-drive it, I decide how the server and channel need to behave. Then I implement the channel and server each to match the behavior I need. When checking the client, I stub the channel; when checking the server, I mock the channel; when checking the channel, I stub and mock both client and server. I hope this makes sense to you, since I have to make some serious assumptions about the nature of this client, server, and channel.
Q. The "Fake it till you make it" left me with a lot of messy code that I later spent a lot of time to refactor and clean up. Is this the way things work?
If you let your "fake it" code get very messy before cleaning it up, then you might have spent too long faking it. That said, I find that even though I end up cleaning up more code with TDD, the overall rhythm feels much better. This comes from practice.
Q. At the end of the session, I now have my client and server running with around 3 or 4 unit tests. It took me around a week to do it. I think I could have done it in a day if I were using the unit tests after code way. I fail to see the gain.
I have to say that unless your client and server are very, very simple, you need more than 3 or 4 tests each to check them thoroughly. I will guess that your tests check (or at least execute) a number of different behaviors at once, and that might account for the effort it took you to write them.
Also, don't measure the learning curve. My first real TDD experience consisted of re-writing 3 months' worth of work in 9, 14-hour days. I had 125 tests that took 12 minutes to run. I had no idea what I was doing, and it felt slow, but it felt steady, and the results were fantastic. I essentially re-wrote in 3 weeks what originally took 3 months to get wrong. If I wrote it now, I could probably do it in 3-5 days. The difference? My test suite would have 500 tests that take 1-2 seconds to run. That came with practice.
A:
As a novice programmer, the thing I found tricky about test-driven development was the idea that testing should come first.
To the novice, that’s not actually true. Design comes first. (Interfaces, objects and classes, methods, whatever’s appropriate to your language.) Then you write your tests to that. Then you write the code that actually does stuff.
It’s been a while since I looked at the book, but Beck seems to write as if the design of the code just sort of happens unconsciously in your head. For experienced programmers, that may be true, but for noobs like me, nuh-uh.
I found the first few chapters of Code Complete really useful for thinking about design. They emphasise the fact that your design may well change, even once you’re down at the nitty gritty level of implementation. When that happens, you may well have to re-write your tests, because they were based on the same assumptions as your design.
Coding is hard. Let’s go shopping.
A:
For point one, see a question I asked a while back relating to your first point.
Rather than handle the other points in turn, I'll offer some global advice. Practice. It took me a good while and a few 'dodgy' projects (personal though) to actual get TDD. Just Google for much more compelling reasons on why TDD is so good.
Despite the tests driving the design of my code, I still get a whiteboard and scribble out some design. From this, at least you have some idea of what you are meant to be doing. Then I produce the list of tests per fixture that I think I need. Once you start working, more features and tests get added to the list.
One thing that stood out from your question is the act of rewriting your tests again. This sounds like you are carrying out behavioural tests, rather than state. In other words, the tests sound too closely tied to your code. Thus, a simple change that doesn't effect the output will break some tests. Unit testing (at least good unit testing) too, is a skill to master.
I recommend the Google Testing Blog quite heavily because some of the articles on there made my testing for TDD projects much better.
A:
The the named pipes were put behind the right interface, changing how that interface is implemented (from named pipes to sockets to another sockets library) should only impact tests for the component that implements that interface. So cutting things up more/differently would have helped... That interface the sockets are behind will likely evolve to.
I started doing TDD maybe 6 months ago? I am still learning myself. I can say over time my tests and code have gotten much better, so keep it up. I really recommend the book XUnit Design Patterns as well.
A:
How do you make such a list to add to
and strike out from to guide the
development process? I initially had a
few items like "server should start
up", "server should abort if channel
is not available"
Items in TDD TODO lists are finer grained than that, they aim at testing one behavior of one method only, for instance:
test successful client connection
test client connection error type 1
test client connection error type 2
test successful client communication
test client communication fails when not connected
You could build a list of tests (positive and negative) for every example you gave. Moreover, when unit testing you do not establish any connection between the server and the client. You just invoke methods in isolation, ... This answers question 3.
How do you handle rewrites?
If the unit test tests behavior and not implementation, then they do not have to be rewritten. If unit test code really creates a named pipe to communicate with production code and, then obviously the tests have to be modified when switching from pipe to socket.
Unit tests shall stay away from external resources such as filesystems, networks, databases because they are slow, can be unavailable ... see these Unit Testing rules.
This implies the lowest level function are not unit tested, they will be tested with integration tests, where the whole system is tested end-to-end.
|
TDD - beginner problems and stumbling blocks
|
While I've written unit tests for most of the code I've done, I only recently got my hands on a copy of TDD by example by Kent Beck. I have always regretted certain design decisions I made since they prevented the application from being 'testable'. I read through the book and while some of it looks alien, I felt that I could manage it and decided to try it out on my current project which is basically a client/server system where the two pieces communicate via. USB. One on the gadget and the other on the host. The application is in Python.
I started off and very soon got entangled in a mess of rewrites and tiny tests which I later figured didn't really test anything. I threw away most of them and and now have a working application for which the tests have all coagulated into just 2.
Based on my experiences, I have a few questions which I'd like to ask. I gained some information from New to TDD: Are there sample applications with tests to show how to do TDD? but have some specific questions which I'd like answers to/discussion on.
Kent Beck uses a list which he adds to and strikes out from to guide the development process. How do you make such a list? I initially had a few items like "server should start up", "server should abort if channel is not available" etc. but they got mixed and finally now, it's just something like "client should be able to connect to server" (which subsumed server startup etc.).
How do you handle rewrites? I initially selected a half duplex system based on named pipes so that I could develop the application logic on my own machine and then later add the USB communication part. It them moved to become a socket based thing and then moved from using raw sockets to using the Python SocketServer module. Each time things changed, I found that I had to rewrite considerable parts of the tests which was annoying. I'd figured that the tests would be a somewhat invariable guide during my development. They just felt like more code to handle.
I needed a client and a server to communicate through the channel to test either side. I could mock one of the sides to test the other but then the whole channel wouldn't be tested and I worry that I'd miss that. This detracted from the whole red/green/refactor rhythm. Is this just lack of experience or am I doing something wrong?
The "Fake it till you make it" left me with a lot of messy code that I later spent a lot of time to refactor and clean up. Is this the way things work?
At the end of the session, I now have my client and server running with around 3 or 4 unit tests. It took me around a week to do it. I think I could have done it in a day if I were using the unit tests after code way. I fail to see the gain.
I'm looking for comments and advice from people who have implemented large non trivial projects completely (or almost completely) using this methodology. It makes sense to me to follow the way after I have something already running and want to add a new feature but doing it from scratch seems to tiresome and not worth the effort.
P.S. : Please let me know if this should be community wiki and I'll mark it like that.
Update 0 : All the answers were equally helpful. I picked the one I did because it resonated with my experiences the most.
Update 1: Practice Practice Practice!
|
[
"As a preliminary comment, TDD takes practice. When I look back at the tests I wrote when I began TDD, I see lots of issues, just like when I look at code I wrote a few year ago. Keep doing it, and just like you begin to recognize good code from bad, the same things will happen with your tests - with patience. \n\nHow do you make such a list? I\n initially had a few items like \"server\n should start up\", \"server should abort\n if channel is not available\" etc. but\n they got mixed and finally now, it's\n just something like \"client should be\n able to connect to server\"\n\n\"The list\" can be rather informal (that's the case in Beck's book) but when you move into making the items into tests, try to write the statements in a \"[When something happens to this] then [this condition should be true on that]\" format. This will force you to think more about what it is you are verifying, how you would verify it and translates directly into tests - or if it doesn't it should give you a clue about which piece of functionality is missing. Think use case / scenario. For instance \"server should start up\" is unclear, because nobody is initiating an action.\n\nEach time things changed, I found that\n I had to rewrite considerable parts of\n the tests which was annoying. I'd\n figured that the tests would be a\n somewhat invariable guide during my\n development. They just felt like more\n code to handle.\n\nFirst, yes, tests are more code, and requires maintenance - and writing maintainable tests takes practice. I agree with S. Lott, if you need to change your tests a lot, you are probably testing \"too deep\". Ideally you want to test at the level of the public interface, which is not likely to change, and not at the level of the implementation detail, which could evolve. But part of the exercise is about coming up with a design, so you should expect to get some of it wrong and have to move/refactor your tests as well.\n\nI could mock one of the sides to test\n the other but then the whole channel\n wouldn't be tested and I worry that\n I'd miss that.\n\nNot totally sure about that one. From the sound of it, using a mock was the right idea: take one side, mock the other one, and check that each side works, assuming the other one is implemented properly. Testing the whole system together is integration testing, which you also want to do, but is typically not part of the TDD process.\n\nThe \"Fake it till you make it\" left me\n with a lot of messy code that I later\n spent a lot of time to refactor and\n clean up. Is this the way things work?\n\nYou should spend a lot of time refactoring while doing TDD. On the other hand, when you fake it, it's temporary, and your immediate next step should be to un-fake it. Typically you shouldn't have multiple tests passing because you faked it - you should be focusing on one piece at a time, and work on refactoring it ASAP.\n\nI think I could have done it in a day\n if I were using the unit tests after\n code way. I fail to see the gain.\n\nAgain, it takes practice, and you should get faster over time. Also, sometimes TDD is more fruitful than others, I find that in some situations, when I know exactly the code I want to write, it's just faster to write a good part of the code, and then write tests.\nBesides Beck, one book I enjoyed is The Art of Unit Testing, by Roy Osherove. It's not a TDD book, and it is .Net-oriented, but you might want to give it a look anyways: a good part is about how to write maintainable tests, tests quality and related questions. I found that the book resonated with my experience after having written tests and sometimes struggled to do it right...\nSo my advice is, don't throw the towel too fast, and give it some time. You might also want to give it a shot on something easier - testing server communication related things doesn't sound like the easiest project to start with!\n",
"\n\nKent Beck uses a list ... finally now, it's just something like \"client should be able to connect to server\" (which subsumed server startup etc.).\n\n\nOften a bad practice.\nSeparate tests for each separate layer of the architecture are good.\nConsolidated tests tend to obscure architectural issues.\nHowever, only test the public functions. Not every function.\nAnd don't invest a lot of time optimizing your testing. Redundancy in the tests doesn't hurt as much as it does in the working application. If things change and one test works, but another test breaks, perhaps then you can refactor your tests. Not before.\n\n2. How do you handle rewrites? ... I found that I had to rewrite considerable parts of the tests.\n\nYou're testing at too low a level of detail. Test the outermost, public, visible interface. The part that's supposed to be unchanging.\nAnd\nYes, significant architectural change means significant testing change.\nAnd\nThe test code is how you prove things work. It is almost as important as the application itself. Yes, it's more code. Yes, you must manage it.\n\n3. I needed a client and a server to communicate through the channel to test either side. I could mock one of the sides to test the other but then the whole channel wouldn't be tested ...\n\nThere are unit tests. With mocks.\nThere are integration tests, which test the whole thing.\nDon't confuse them. \nYou can use unit test tools to do integration tests, but they're different things.\nAnd you need to do both.\n\n4. The \"Fake it till you make it\" left me with a lot of messy code that I later spent a lot of time to refactor and clean up. Is this the way things work?\n\nYes. That's exactly how it works. In the long run, some people find this more effective than straining their brains trying to do all the design up front. Some people don't like this and want to do all the design up front; you're free to do a lot of design up front if you want to.\nI've found that refactoring is a good thing and design up front is too hard. Maybe it's because I've been coding for almost 40 years and my brain is wearing out.\n\n5. I fail to see the gain.\n\nAll the true geniuses find that testing slows them down.\nThe rest of us can't be sure our code works until we have a complete set of tests that prove that it works.\nIf you don't need proof that your code works, you don't need testing.\n",
"\nQ. Kent Beck uses a list which he adds to and strikes out from to guide the development process. How do you make such a list? I initially had a few items like \"server should start up\", \"server should abort if channel is not available\" etc. but they got mixed and finally now, it's just something like \"client should be able to connect to server\" (which subsumed server startup etc.).\n\nI start by picking anything I might check. In your example, you chose \"server starts\". \n\nServer starts\n\nNow I look for any simpler test I might want to write. Something with less variation, and fewer moving parts. I might consider \"configured server correctly\", for example.\n\nConfigured server correctly\nServer starts\n\nReally, though, \"server starts\" depends on \"configured server correctly\", so I make that link clear.\n\nConfigured server correctly\nServer starts if configured correctly\n\nNow I look for variations. I ask, \"What could go wrong?\" I could configure the server incorrectly. How many different ways that matter? Each of those makes a test. How might the server not start even though I configured it correctly? Each case of that makes a test.\n\nQ. How do you handle rewrites? I initially selected a half duplex system based on named pipes so that I could develop the application logic on my own machine and then later add the USB communication part. It them moved to become a socket based thing and then moved from using raw sockets to using the Python SocketServer module. Each time things changed, I found that I had to rewrite considerable parts of the tests which was annoying. I'd figured that the tests would be a somewhat invariable guide during my development. They just felt like more code to handle.\n\nWhen I change behavior, I find it reasonable to change the tests, and even to change them first! If I have to change tests that don't directly check the behavior I'm in the process of changing, though, that's a sign that my tests depend on too many different behaviors. Those are integration tests, which I think are a scam. (Google \"Integration tests are a scam\")\n\nQ. I needed a client and a server to communicate through the channel to test either side. I could mock one of the sides to test the other but then the whole channel wouldn't be tested and I worry that I'd miss that. This detracted from the whole red/green/refactor rhythm. Is this just lack of experience or am I doing something wrong?\n\nIf I build a client, a server, and a channel, then I try to check each in isolation. I start with the client, and when I test-drive it, I decide how the server and channel need to behave. Then I implement the channel and server each to match the behavior I need. When checking the client, I stub the channel; when checking the server, I mock the channel; when checking the channel, I stub and mock both client and server. I hope this makes sense to you, since I have to make some serious assumptions about the nature of this client, server, and channel.\n\nQ. The \"Fake it till you make it\" left me with a lot of messy code that I later spent a lot of time to refactor and clean up. Is this the way things work?\n\nIf you let your \"fake it\" code get very messy before cleaning it up, then you might have spent too long faking it. That said, I find that even though I end up cleaning up more code with TDD, the overall rhythm feels much better. This comes from practice.\n\nQ. At the end of the session, I now have my client and server running with around 3 or 4 unit tests. It took me around a week to do it. I think I could have done it in a day if I were using the unit tests after code way. I fail to see the gain.\n\nI have to say that unless your client and server are very, very simple, you need more than 3 or 4 tests each to check them thoroughly. I will guess that your tests check (or at least execute) a number of different behaviors at once, and that might account for the effort it took you to write them.\nAlso, don't measure the learning curve. My first real TDD experience consisted of re-writing 3 months' worth of work in 9, 14-hour days. I had 125 tests that took 12 minutes to run. I had no idea what I was doing, and it felt slow, but it felt steady, and the results were fantastic. I essentially re-wrote in 3 weeks what originally took 3 months to get wrong. If I wrote it now, I could probably do it in 3-5 days. The difference? My test suite would have 500 tests that take 1-2 seconds to run. That came with practice.\n",
"As a novice programmer, the thing I found tricky about test-driven development was the idea that testing should come first.\nTo the novice, that’s not actually true. Design comes first. (Interfaces, objects and classes, methods, whatever’s appropriate to your language.) Then you write your tests to that. Then you write the code that actually does stuff.\nIt’s been a while since I looked at the book, but Beck seems to write as if the design of the code just sort of happens unconsciously in your head. For experienced programmers, that may be true, but for noobs like me, nuh-uh.\nI found the first few chapters of Code Complete really useful for thinking about design. They emphasise the fact that your design may well change, even once you’re down at the nitty gritty level of implementation. When that happens, you may well have to re-write your tests, because they were based on the same assumptions as your design.\nCoding is hard. Let’s go shopping.\n",
"For point one, see a question I asked a while back relating to your first point.\nRather than handle the other points in turn, I'll offer some global advice. Practice. It took me a good while and a few 'dodgy' projects (personal though) to actual get TDD. Just Google for much more compelling reasons on why TDD is so good.\nDespite the tests driving the design of my code, I still get a whiteboard and scribble out some design. From this, at least you have some idea of what you are meant to be doing. Then I produce the list of tests per fixture that I think I need. Once you start working, more features and tests get added to the list.\nOne thing that stood out from your question is the act of rewriting your tests again. This sounds like you are carrying out behavioural tests, rather than state. In other words, the tests sound too closely tied to your code. Thus, a simple change that doesn't effect the output will break some tests. Unit testing (at least good unit testing) too, is a skill to master. \nI recommend the Google Testing Blog quite heavily because some of the articles on there made my testing for TDD projects much better. \n",
"The the named pipes were put behind the right interface, changing how that interface is implemented (from named pipes to sockets to another sockets library) should only impact tests for the component that implements that interface. So cutting things up more/differently would have helped... That interface the sockets are behind will likely evolve to.\nI started doing TDD maybe 6 months ago? I am still learning myself. I can say over time my tests and code have gotten much better, so keep it up. I really recommend the book XUnit Design Patterns as well.\n",
"\nHow do you make such a list to add to\n and strike out from to guide the\n development process? I initially had a\n few items like \"server should start\n up\", \"server should abort if channel\n is not available\" \n\nItems in TDD TODO lists are finer grained than that, they aim at testing one behavior of one method only, for instance:\n\ntest successful client connection\ntest client connection error type 1\ntest client connection error type 2\ntest successful client communication\ntest client communication fails when not connected\n\nYou could build a list of tests (positive and negative) for every example you gave. Moreover, when unit testing you do not establish any connection between the server and the client. You just invoke methods in isolation, ... This answers question 3. \n\nHow do you handle rewrites?\n\nIf the unit test tests behavior and not implementation, then they do not have to be rewritten. If unit test code really creates a named pipe to communicate with production code and, then obviously the tests have to be modified when switching from pipe to socket.\nUnit tests shall stay away from external resources such as filesystems, networks, databases because they are slow, can be unavailable ... see these Unit Testing rules. \nThis implies the lowest level function are not unit tested, they will be tested with integration tests, where the whole system is tested end-to-end. \n"
] |
[
10,
8,
3,
2,
1,
1,
1
] |
[] |
[] |
[
"python",
"tdd",
"testdrivendesign"
] |
stackoverflow_0002066593_python_tdd_testdrivendesign.txt
|
Q:
Subtract two dates to give a timedelta
I'm trying to get a value from one of my database values, which will be given by subtracting the purchase date from today's date. I've written my code this way:
delta = datetime.now() - item.purchase_date
But this gives me this error:
unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
If I use datetime.datetime.now() this doesn't work. What am I missing. Thanks.
A:
you need to use date.today or datetime.now().date() instead of datetime.now:
>>> import datetime
>>> datetime.date.today()
datetime.date(2010, 2, 10)
>>> datetime.datetime.now().date()
datetime.date(2010, 2, 10)
|
Subtract two dates to give a timedelta
|
I'm trying to get a value from one of my database values, which will be given by subtracting the purchase date from today's date. I've written my code this way:
delta = datetime.now() - item.purchase_date
But this gives me this error:
unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
If I use datetime.datetime.now() this doesn't work. What am I missing. Thanks.
|
[
"you need to use date.today or datetime.now().date() instead of datetime.now:\n>>> import datetime\n>>> datetime.date.today()\ndatetime.date(2010, 2, 10)\n>>> datetime.datetime.now().date()\ndatetime.date(2010, 2, 10)\n\n"
] |
[
20
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0002238008_datetime_python.txt
|
Q:
Applying a decorator to every method in a class?
I have decorator @login_testuser applied to method test_1():
class TestCase(object):
@login_testuser
def test_1(self):
print "test_1()"
Is there a way I can apply @login_testuser on every method of the class prefixed with "test_"?
In other words, the decorator would apply to test_1(), test_2() methods below, but not on setUp().
class TestCase(object):
def setUp(self):
pass
def test_1(self):
print "test_1()"
def test_2(self):
print "test_2()"
A:
In Python 2.6, a class decorator is definitely the way to go. e.g., here's a pretty general one for these kind of tasks:
import inspect
def decallmethods(decorator, prefix='test_'):
def dectheclass(cls):
for name, m in inspect.getmembers(cls, inspect.isfunction):
if name.startswith(prefix):
setattr(cls, name, decorator(m))
return cls
return dectheclass
@decallmethods(login_testuser)
class TestCase(object):
def setUp(self):
pass
def test_1(self):
print("test_1()")
def test_2(self):
print("test_2()")
will get you what you desire. In Python 2.5 or worse, the @decallmethods syntax doesn't work for class decoration, but with otherwise exactly the same code you can replace it with the following statement right after the end of the class TestCase statement:
TestCase = decallmethods(login_testuser)(TestCase)
A:
Sure. Iterate all attributes of the class. Check each one for being a method and if the name starts with "test_". Then replace it with the function returned from your decorator
Something like:
from inspect import ismethod, getmembers
for name, obj in getmembers(TestCase, ismethod):
if name.startswith("test_"):
setattr(TestCase, name, login_testuser(obj))
A:
Are you sure you wouldn't be better off by putting login_testuser's code into setUp instead? That's what setUp is for: it's run before every test method.
A:
Yes, you can loop over the class's dir/__dict__ or have a metaclass that does so, identifying if the attributes start with "test". However, this will create less straightforward, explicit code than writing the decorator explicitly.
|
Applying a decorator to every method in a class?
|
I have decorator @login_testuser applied to method test_1():
class TestCase(object):
@login_testuser
def test_1(self):
print "test_1()"
Is there a way I can apply @login_testuser on every method of the class prefixed with "test_"?
In other words, the decorator would apply to test_1(), test_2() methods below, but not on setUp().
class TestCase(object):
def setUp(self):
pass
def test_1(self):
print "test_1()"
def test_2(self):
print "test_2()"
|
[
"In Python 2.6, a class decorator is definitely the way to go. e.g., here's a pretty general one for these kind of tasks:\nimport inspect\n\ndef decallmethods(decorator, prefix='test_'):\n def dectheclass(cls):\n for name, m in inspect.getmembers(cls, inspect.isfunction):\n if name.startswith(prefix):\n setattr(cls, name, decorator(m))\n return cls\n return dectheclass\n\n\n@decallmethods(login_testuser)\nclass TestCase(object):\n def setUp(self):\n pass\n\n def test_1(self):\n print(\"test_1()\")\n\n def test_2(self):\n print(\"test_2()\")\n\nwill get you what you desire. In Python 2.5 or worse, the @decallmethods syntax doesn't work for class decoration, but with otherwise exactly the same code you can replace it with the following statement right after the end of the class TestCase statement:\nTestCase = decallmethods(login_testuser)(TestCase)\n\n",
"Sure. Iterate all attributes of the class. Check each one for being a method and if the name starts with \"test_\". Then replace it with the function returned from your decorator\nSomething like:\nfrom inspect import ismethod, getmembers\nfor name, obj in getmembers(TestCase, ismethod):\n if name.startswith(\"test_\"):\n setattr(TestCase, name, login_testuser(obj))\n\n",
"Are you sure you wouldn't be better off by putting login_testuser's code into setUp instead? That's what setUp is for: it's run before every test method.\n",
"Yes, you can loop over the class's dir/__dict__ or have a metaclass that does so, identifying if the attributes start with \"test\". However, this will create less straightforward, explicit code than writing the decorator explicitly.\n"
] |
[
26,
5,
2,
0
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002237624_decorator_python.txt
|
Q:
AttributeError in tkinter gui programming
I want to display my calculated output in a Gui window in python. I am trying with Tkinter. But I'm having problems displaying the output on Tkinter level widget. I am putting input data as address information in text field of Tkinter window and want latitude, longitude of that inputed address to the text label. Can anyone please help me out of this? I am just quite new to this Tkinter.
code is below:
def initialize(self):
self.grid()
self.entry = Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
button = Tkinter.Button(self,text=u"Get Geo information !",command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="black",bg="white")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
def OnButtonClick(self):
outf = open(out_file,'w')
outf_failed = open(out_file_failed,'w')
#inf = open(addr_file,'r')
inf = codecs.open(addr_file, 'r', 'iso-8859-1')
for address in inf:
#get latitude and longitude of address
data = geocode(address)
#output results and log to file
if len(data)>1:
self.labelVariable.set( self.entryVariable.get()+" (Latitude )", data['lat'] )
self.labelVariable.set( self.entryVariable.get()+" (Longitude )", data['lng'] )
outf.write(address.strip()+data['lat']+','+data['lng']+'\n')
outf.flush()
else:
self.labelVariable.set( self.entryVariable.get()+" Geocoding of '"+addr_file+"' failed with error code "+data['code'] )
outf_failed.write(address)
outf_failed.flush()
time.sleep(sleep_time)
#clean up
inf.close()
outf.close()
outf_failed.close()
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('Your Location')
app.mainloop()
And I got error:
File "F:\JavaWorkspace\Test\src\gui_geo_location.py", line 94, in OnButtonClick
self.labelVariable.set( self.entryVariable.get()+" (Latitude )", data['lat'] )
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1721, in __getattr__
return getattr(self.tk, attr)
AttributeError: entryVariable
Here is my __init__ method:
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entry = Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
button = Tkinter.Button(self,text=u"Get Geo information !",command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="black",bg="white")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
A:
On line 94 in F:\JavaWorkspace\Test\src\gui_geo_location.py, you're using self.entryVariable but that object does not have an entryVariable attribute.
Based on your __init__, it seems you haven't defined entryVariable anywhere. Try adding:
self.entryVariable = Tkinter.StringVar()
to your __init__ method. See this page for more information.
|
AttributeError in tkinter gui programming
|
I want to display my calculated output in a Gui window in python. I am trying with Tkinter. But I'm having problems displaying the output on Tkinter level widget. I am putting input data as address information in text field of Tkinter window and want latitude, longitude of that inputed address to the text label. Can anyone please help me out of this? I am just quite new to this Tkinter.
code is below:
def initialize(self):
self.grid()
self.entry = Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
button = Tkinter.Button(self,text=u"Get Geo information !",command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="black",bg="white")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
def OnButtonClick(self):
outf = open(out_file,'w')
outf_failed = open(out_file_failed,'w')
#inf = open(addr_file,'r')
inf = codecs.open(addr_file, 'r', 'iso-8859-1')
for address in inf:
#get latitude and longitude of address
data = geocode(address)
#output results and log to file
if len(data)>1:
self.labelVariable.set( self.entryVariable.get()+" (Latitude )", data['lat'] )
self.labelVariable.set( self.entryVariable.get()+" (Longitude )", data['lng'] )
outf.write(address.strip()+data['lat']+','+data['lng']+'\n')
outf.flush()
else:
self.labelVariable.set( self.entryVariable.get()+" Geocoding of '"+addr_file+"' failed with error code "+data['code'] )
outf_failed.write(address)
outf_failed.flush()
time.sleep(sleep_time)
#clean up
inf.close()
outf.close()
outf_failed.close()
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('Your Location')
app.mainloop()
And I got error:
File "F:\JavaWorkspace\Test\src\gui_geo_location.py", line 94, in OnButtonClick
self.labelVariable.set( self.entryVariable.get()+" (Latitude )", data['lat'] )
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1721, in __getattr__
return getattr(self.tk, attr)
AttributeError: entryVariable
Here is my __init__ method:
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entry = Tkinter.Entry(self)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
button = Tkinter.Button(self,text=u"Get Geo information !",command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w",fg="black",bg="white")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
|
[
"On line 94 in F:\\JavaWorkspace\\Test\\src\\gui_geo_location.py, you're using self.entryVariable but that object does not have an entryVariable attribute.\nBased on your __init__, it seems you haven't defined entryVariable anywhere. Try adding:\nself.entryVariable = Tkinter.StringVar()\n\nto your __init__ method. See this page for more information.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0002237700_python_tkinter.txt
|
Q:
What is the pythonic way to unpack tuples?
This is ugly. What's a more Pythonic way to do it?
import datetime
t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
A:
Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
A:
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
|
What is the pythonic way to unpack tuples?
|
This is ugly. What's a more Pythonic way to do it?
import datetime
t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
|
[
"Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:\nt = (2010, 10, 2, 11, 4, 0, 2, 41, 0)\ndt = datetime.datetime(*t[0:7])\n\nThis is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):\n>>> range(3, 6) # normal call with separate arguments\n[3, 4, 5]\n>>> args = [3, 6]\n>>> range(*args) # call with arguments unpacked from a list\n[3, 4, 5]\n\n",
"Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists\n dt = datetime.datetime(*t[:7])\n\n"
] |
[
155,
15
] |
[] |
[] |
[
"python",
"tuples"
] |
stackoverflow_0002238355_python_tuples.txt
|
Q:
How do I properly work with unicode characters in python to keep from getting errors?
I'm working on a python plugin for Google Quick Search Box, and it's doing some odd things with non-ascii characters. It seems like the code works fine up until I try constructing a string containing the non-ascii characters (ü has been my test character). I am using the following code snippet for the construction, with new_task as the variable that is being input from GQSB.
the_sig = ("%sapi_key%sauth_token%smethod%sname%sparse%stimeline%s" %
(api_secret, api_key, the_token, method, new_task, doParse, timeline))
It's giving me this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
I am understanding correctly, this is because I am trying to string together a unicode character inside an ascii string. Everything I could find told me to declare the encoding at the top with this:
# -*- coding: iso-8859-15 -*-
Which I have. And when I pull the code snippet that constructs the string into a new script, it works just fine. But for some reason, int he context of the rest of the code, it fails, every time. The only thing I can think of is that it is because it's inside it's own class, but that doesn't make any sense to me.
The full code can be found on GitHub here
Thanks in advance for any help. I am stumped on this one.
A:
There are a few things you should do to fix this.
Convert all string literal that contain non-ASCII characters to Unicode literals. Example: u'über'.
Do intermediate processing on Unicode. In other words, if you receive an encoded string (no matter the encoding), decode it to Unicode before working on it. Example:
s = utf8_string.decode('utf8') + latin1_string.decode('latin1')
When outputting the string or sending it somewhere, encode it with an encoding that your receiver understands. Example: send(s.encode('utf8')).
Complete example:
input1 = get_possibly_nonascii_input().decode('iso-8859-1')
input2 = get_possibly_nonascii_input().decode('iso-8859-1')
input3 = u'üvw'
s = u'%s -> %s' % (input3, (input1 + input2).upper())
send_output(s.encode('utf8'))
A:
I guess you're using Python 2.x.
The file encoding declaration specifies how string literals are read by the interpreter.
You should handle all strings as unicode values, not str ones. If you read a str from the outside world, you should decode it to unicode explicitely. The same applies to outputting strings.
# -*- coding: utf-8 -*-
u_dia_str = '\xc3\xbc' # str
lambda_unicode = u'λ' # unicode
# input value
u_dia = u_dia_str.decode('utf-8')
sig_unicode = u'%s%s' % (u_dia, lambda_unicode)
# => u'üλ'
# output value
sig_str = sig_unicode.encode('utf-8')
# => '\xc3\xbc\xce\xbb'
A:
This is a bit beyond my expertise, but I think # -*- coding: iso-8859-15 -*- at the top declares the text encoding that your Python source file is saved in.
Is it really saved in iso-8859-15?
|
How do I properly work with unicode characters in python to keep from getting errors?
|
I'm working on a python plugin for Google Quick Search Box, and it's doing some odd things with non-ascii characters. It seems like the code works fine up until I try constructing a string containing the non-ascii characters (ü has been my test character). I am using the following code snippet for the construction, with new_task as the variable that is being input from GQSB.
the_sig = ("%sapi_key%sauth_token%smethod%sname%sparse%stimeline%s" %
(api_secret, api_key, the_token, method, new_task, doParse, timeline))
It's giving me this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
I am understanding correctly, this is because I am trying to string together a unicode character inside an ascii string. Everything I could find told me to declare the encoding at the top with this:
# -*- coding: iso-8859-15 -*-
Which I have. And when I pull the code snippet that constructs the string into a new script, it works just fine. But for some reason, int he context of the rest of the code, it fails, every time. The only thing I can think of is that it is because it's inside it's own class, but that doesn't make any sense to me.
The full code can be found on GitHub here
Thanks in advance for any help. I am stumped on this one.
|
[
"There are a few things you should do to fix this.\n\nConvert all string literal that contain non-ASCII characters to Unicode literals. Example: u'über'.\nDo intermediate processing on Unicode. In other words, if you receive an encoded string (no matter the encoding), decode it to Unicode before working on it. Example:\ns = utf8_string.decode('utf8') + latin1_string.decode('latin1')\n\nWhen outputting the string or sending it somewhere, encode it with an encoding that your receiver understands. Example: send(s.encode('utf8')).\n\nComplete example:\ninput1 = get_possibly_nonascii_input().decode('iso-8859-1')\ninput2 = get_possibly_nonascii_input().decode('iso-8859-1')\ninput3 = u'üvw'\n\ns = u'%s -> %s' % (input3, (input1 + input2).upper())\n\nsend_output(s.encode('utf8'))\n\n",
"I guess you're using Python 2.x.\nThe file encoding declaration specifies how string literals are read by the interpreter.\nYou should handle all strings as unicode values, not str ones. If you read a str from the outside world, you should decode it to unicode explicitely. The same applies to outputting strings.\n# -*- coding: utf-8 -*-\nu_dia_str = '\\xc3\\xbc' # str\nlambda_unicode = u'λ' # unicode\n\n# input value\nu_dia = u_dia_str.decode('utf-8')\n\nsig_unicode = u'%s%s' % (u_dia, lambda_unicode)\n# => u'üλ'\n\n# output value\nsig_str = sig_unicode.encode('utf-8')\n# => '\\xc3\\xbc\\xce\\xbb'\n\n",
"This is a bit beyond my expertise, but I think # -*- coding: iso-8859-15 -*- at the top declares the text encoding that your Python source file is saved in.\nIs it really saved in iso-8859-15?\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"ascii",
"encoding",
"python",
"unicode"
] |
stackoverflow_0002239017_ascii_encoding_python_unicode.txt
|
Q:
Python: simple CLI GUI
A simple question on a python module. Let's say I have the following code:
for i in range(1000):
print i
It'll output something along the lines of:
1
2
'Snip'
999
Is it possible to have the program output all the numbers on the same line? I'm not talking about "1, 2, 3 .." rather I want the line value to change to the current i
A:
If you want to draw a GUI inside a terminal, you'll have to use the curses module.
A:
If you want the character to be overwritten/replaced each time, you may need to use a terminal control library like 'curses'. Here's a Python how-to article to get you started.
A:
For a simple case the following code works just fine:
sys.stdout.write(str(i)+'\r')
sys.stdout.flush()
A:
import os
for i in range(1000):
print i
os.system("clear")
edit: as mentioned in the comment below, change "clear" to "cls" if using windows.
A:
Text printed to stdout can't be dynamically changed. You need to use a panel.
http://docs.python.org/library/curses.panel.html
Initialize a new panel, and then use Panel.set_userptr(obj) in your loop.
|
Python: simple CLI GUI
|
A simple question on a python module. Let's say I have the following code:
for i in range(1000):
print i
It'll output something along the lines of:
1
2
'Snip'
999
Is it possible to have the program output all the numbers on the same line? I'm not talking about "1, 2, 3 .." rather I want the line value to change to the current i
|
[
"If you want to draw a GUI inside a terminal, you'll have to use the curses module.\n",
"If you want the character to be overwritten/replaced each time, you may need to use a terminal control library like 'curses'. Here's a Python how-to article to get you started.\n",
"For a simple case the following code works just fine:\nsys.stdout.write(str(i)+'\\r')\nsys.stdout.flush()\n\n",
"import os\n\nfor i in range(1000):\n print i\n os.system(\"clear\")\n\nedit: as mentioned in the comment below, change \"clear\" to \"cls\" if using windows.\n",
"Text printed to stdout can't be dynamically changed. You need to use a panel.\nhttp://docs.python.org/library/curses.panel.html\nInitialize a new panel, and then use Panel.set_userptr(obj) in your loop.\n"
] |
[
3,
3,
2,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002239476_python.txt
|
Q:
Python win32com: Internet Explorer COM object ? (used to work?)
I have this very simple program:
from win32com import client
ie=client.Dispatch("InternetExplorer.Application")
This used to work (I think I broke something when I re-used 'makepy.py' to try and add in constants for IE).
It still works on another machine where I haven't been so slap-dash with 'makepy.py'.
Here's what I get in an interactive Python session on the non-working machine:
>>> ie
>>> <win32com.gen_py.Microsoft Internet Controls.IWebBrowser2 instance at 0x14701432
>
>>> ie.Visible=True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python26\lib\site-packages\win32com\client\__init__.py", line 471, in
__setattr__
self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
And the same on a working machine:
>>> from win32com import client
>>> ie=client.Dispatch("InternetExplorer.Application")
>>> ie
>>> <ComObject InternetExplorer.Application>
>>> ie.Visible=1 # This then brings up IE correctly.
How do I get this working again ? Or am I using the wrong way of launching IE ?
Thanks !
A:
Went into here:
Python26\Lib\site-packages\win32com\gen_py
Renamed the .py and .pyc file to .py_ and .pyc_ files :
85CC894D-5673-4868-9A22-9E15B7E694D3x0x1x1.pyc
Restarted Python: now get the Internet Explorer. phew...
|
Python win32com: Internet Explorer COM object ? (used to work?)
|
I have this very simple program:
from win32com import client
ie=client.Dispatch("InternetExplorer.Application")
This used to work (I think I broke something when I re-used 'makepy.py' to try and add in constants for IE).
It still works on another machine where I haven't been so slap-dash with 'makepy.py'.
Here's what I get in an interactive Python session on the non-working machine:
>>> ie
>>> <win32com.gen_py.Microsoft Internet Controls.IWebBrowser2 instance at 0x14701432
>
>>> ie.Visible=True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python26\lib\site-packages\win32com\client\__init__.py", line 471, in
__setattr__
self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
And the same on a working machine:
>>> from win32com import client
>>> ie=client.Dispatch("InternetExplorer.Application")
>>> ie
>>> <ComObject InternetExplorer.Application>
>>> ie.Visible=1 # This then brings up IE correctly.
How do I get this working again ? Or am I using the wrong way of launching IE ?
Thanks !
|
[
"Went into here:\nPython26\\Lib\\site-packages\\win32com\\gen_py\n\nRenamed the .py and .pyc file to .py_ and .pyc_ files :\n85CC894D-5673-4868-9A22-9E15B7E694D3x0x1x1.pyc\n\nRestarted Python: now get the Internet Explorer. phew...\n"
] |
[
1
] |
[] |
[] |
[
"automation",
"com",
"internet_explorer",
"python",
"winapi"
] |
stackoverflow_0002239199_automation_com_internet_explorer_python_winapi.txt
|
Q:
Is it better to use "is" or "==" for number comparison in Python?
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python?
Examples:
>>> a = 1
>>> a is 1
True
>>> a == 1
True
>>> a is 0
False
>>> a == 0
False
A:
Use ==.
Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.
A:
Others have answered your question, but I'll go into a little bit more detail:
Python's is compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to == in Java). So, there are some times when using is makes sense - the most common one being checking for None. Eg, foo is None. But, in general, it isn't what you want.
==, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:
>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False
And this is true because classes can define the method they use to test for equality:
>>> class AlwaysEqual(object):
... def __eq__(self, other):
... return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True
But they cannot define the method used for testing identity (ie, they can't override is).
A:
>>> a = 255556
>>> a == 255556
True
>>> a is 255556
False
I think that should answer it ;-)
The reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is, they are not the same.
A:
That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.
>>> a = 2104214124
>>> b = 2104214124
>>> a == b
True
>>> a is b
False
So you should always use == to compare numbers.
A:
== is what you want, "is" just happens to work on your examples.
A:
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==
|
Is it better to use "is" or "==" for number comparison in Python?
|
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python?
Examples:
>>> a = 1
>>> a is 1
True
>>> a == 1
True
>>> a is 0
False
>>> a == 0
False
|
[
"Use ==. \nSometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.\n",
"Others have answered your question, but I'll go into a little bit more detail:\nPython's is compares identity - it asks the question \"is this one thing actually the same object as this other thing\" (similar to == in Java). So, there are some times when using is makes sense - the most common one being checking for None. Eg, foo is None. But, in general, it isn't what you want.\n==, on the other hand, asks the question \"is this one thing logically equivalent to this other thing\". For example:\n>>> [1, 2, 3] == [1, 2, 3]\nTrue\n>>> [1, 2, 3] is [1, 2, 3]\nFalse\n\nAnd this is true because classes can define the method they use to test for equality:\n>>> class AlwaysEqual(object):\n... def __eq__(self, other):\n... return True\n...\n>>> always_equal = AlwaysEqual()\n>>> always_equal == 42\nTrue\n>>> always_equal == None\nTrue\n\nBut they cannot define the method used for testing identity (ie, they can't override is).\n",
">>> a = 255556\n>>> a == 255556\nTrue\n>>> a is 255556\nFalse\n\nI think that should answer it ;-)\nThe reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is, they are not the same.\n",
"That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.\n>>> a = 2104214124\n>>> b = 2104214124\n>>> a == b\nTrue\n>>> a is b\nFalse\n\nSo you should always use == to compare numbers.\n",
"== is what you want, \"is\" just happens to work on your examples.\n",
">>> 2 == 2.0\nTrue\n>>> 2 is 2.0\nFalse\n\nUse ==\n"
] |
[
118,
33,
20,
8,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002239737_python.txt
|
Q:
Python equiv. of PHP foreach []?
I am fetching rows from the database and wish to populate a multi-dimensional dictionary.
The php version would be roughly this:
foreach($query as $rows):
$values[$rows->id][] = $rows->name;
endforeach;
return $values;
I can't seem to find out the following issues:
What is the python way to add keys to a dictionary using an automatically numbering e.g. $values[]
How do I populate a Python dictionary using variables; using, for example, values[id] = name, will not add keys, but override existing.
I totally have no idea how to achieve this, as I am a Python beginner (programming in general, actually).
A:
values = collections.defaultdict(list)
for rows in query:
values[rows.id].append(rows.name)
return values
A:
Just a general note:
Python's dictionaries are mappings without order, while adding numerical keys would allow "sequential" access, in case of iteration there's no guarantee that order will coincide with the natural order of keys.
It's better not to translate from PHP to Python (or any other language), but rather right code idiomatic to that particular language. Have a look at the many open-source code that does the same/similar things, you might even find a useful module (library).
A:
all_rows=[]
for row in query:
all_rows.append(row['col'])
print(all_rows)
A:
You can do:
from collections import defaultdict
values = defaultdict(list)
for row in query:
values[row.id].append(row.name)
return values
Edit: forgot to return the values.
|
Python equiv. of PHP foreach []?
|
I am fetching rows from the database and wish to populate a multi-dimensional dictionary.
The php version would be roughly this:
foreach($query as $rows):
$values[$rows->id][] = $rows->name;
endforeach;
return $values;
I can't seem to find out the following issues:
What is the python way to add keys to a dictionary using an automatically numbering e.g. $values[]
How do I populate a Python dictionary using variables; using, for example, values[id] = name, will not add keys, but override existing.
I totally have no idea how to achieve this, as I am a Python beginner (programming in general, actually).
|
[
"values = collections.defaultdict(list)\nfor rows in query:\n values[rows.id].append(rows.name)\nreturn values\n\n",
"Just a general note:\n\nPython's dictionaries are mappings without order, while adding numerical keys would allow \"sequential\" access, in case of iteration there's no guarantee that order will coincide with the natural order of keys.\nIt's better not to translate from PHP to Python (or any other language), but rather right code idiomatic to that particular language. Have a look at the many open-source code that does the same/similar things, you might even find a useful module (library).\n\n",
" all_rows=[] \n for row in query:\n all_rows.append(row['col'])\n print(all_rows)\n\n",
"You can do:\nfrom collections import defaultdict\n\nvalues = defaultdict(list)\nfor row in query:\n values[row.id].append(row.name)\n\nreturn values\n\nEdit: forgot to return the values.\n"
] |
[
8,
4,
2,
1
] |
[] |
[] |
[
"dictionary",
"key",
"python"
] |
stackoverflow_0002239771_dictionary_key_python.txt
|
Q:
How to set file/directory ownership/permissions in a Samba share on Windows using Python/.NET?
I need to create directories and files in a Samba share on Windows, from a Python script. I can (and do) also use .NET 3.5 from Python. I would like to create these directories and files with certain owners and permissions. Can I achieve this somehow?
A:
You can use CACLS.exe to display or modify Access Control Lists (ACLs) for files and folders. You can call this from Python with something like:
result = os.popen("cacls " + '"' + theDirPath + '"')
There is a good example of a Python script which sets up permissions here
|
How to set file/directory ownership/permissions in a Samba share on Windows using Python/.NET?
|
I need to create directories and files in a Samba share on Windows, from a Python script. I can (and do) also use .NET 3.5 from Python. I would like to create these directories and files with certain owners and permissions. Can I achieve this somehow?
|
[
"You can use CACLS.exe to display or modify Access Control Lists (ACLs) for files and folders. You can call this from Python with something like:\nresult = os.popen(\"cacls \" + '\"' + theDirPath + '\"')\nThere is a good example of a Python script which sets up permissions here \n"
] |
[
0
] |
[] |
[] |
[
".net",
"python",
"samba",
"windows"
] |
stackoverflow_0002239762_.net_python_samba_windows.txt
|
Q:
Does anyone know of a Urwid like environment that is cross-platform for Python 3.x?
I would like it to run on Linux, OS X, and Windows (XP/Vista/7).
Thanks for any input.
A:
Your best bet is probably to use 2to3 to convert Urwid itself.
A:
I believe you're out of luck until Urwid itself is ported to Python 3 (and according to this post from last month, "the real work to port to python 3 hasn't
started yet").
A:
Help port Urwid to Python 3! That is most likely more work that just running 2to3 on it, though.
|
Does anyone know of a Urwid like environment that is cross-platform for Python 3.x?
|
I would like it to run on Linux, OS X, and Windows (XP/Vista/7).
Thanks for any input.
|
[
"Your best bet is probably to use 2to3 to convert Urwid itself.\n",
"I believe you're out of luck until Urwid itself is ported to Python 3 (and according to this post from last month, \"the real work to port to python 3 hasn't \nstarted yet\").\n",
"Help port Urwid to Python 3! That is most likely more work that just running 2to3 on it, though. \n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"cross_platform",
"python",
"python_3.x"
] |
stackoverflow_0002226913_cross_platform_python_python_3.x.txt
|
Q:
simple auth system in django failing
I'm writing a simple auth system to login (and logout) users. The username is an email address, which looks up an email field.
I'm using:
user = User.objects.get(email__exact=email)
# if user obj exists
if user:
# if authenticate
if authenticate(user, email, password):
# create session
request.session['user'] = user
# redir
return HttpResponseRedirect('/home/')
else:
return HttpResponseRedirect('/home/login/')
# no user obj found? (no email found actually)
else:
# redir
return HttpResponseRedirect('/home/')
to find if a user exists, however if a user is not found Django throws an error:
User matching query does not exist.
All I want to do is see if that query matches a result. How do I count rows?
A:
Use filter() instead of get().
A:
I think this is probably more what you want:
try:
user = User.objects.get(email__exact=email)
if authenticate(user, email, password):
request.session['user'] = user
return HttpResponseRedirect('/home/')
else:
return HttpResponseRedirect('/home/login/')
except User.DoesNotExist: # A user with the e-mail provided was not found
return HttpResponseRedirect('/home/')
Personally I think that's cleaner than Ignacio's method, but it's a matter of taste really.
Finally, the last part of your question ("How do I count rows?"):
get only ever returns an object, and raises an exception if no objects match the criteria you passed in, or if multiple objects match the criteria. To get the number of objects in a QuerySet, you can just call len on it:
q = User.objects.filter(email = 'foo@bar.com')
print len(q)
Or, call count():
print User.objects.filter(email = 'foo@bar.com').count()
The former method (len) will be quicker if you've already evaluated the QuerySet (since it's just counting the number of items in a list, effectively); the latter (count()) will be faster if you've not evaluated the QuerySet, since Django will perform a SELECT COUNT(*) behind the scenes, and you avoid loading all the data into memory.
As an aside - why are you directing them to /home/ if the e-mail address isn't matched, and to /home/login/ if their credentials fail? I would have thought it makes more sense to redirect them to the same place for those two cases.
|
simple auth system in django failing
|
I'm writing a simple auth system to login (and logout) users. The username is an email address, which looks up an email field.
I'm using:
user = User.objects.get(email__exact=email)
# if user obj exists
if user:
# if authenticate
if authenticate(user, email, password):
# create session
request.session['user'] = user
# redir
return HttpResponseRedirect('/home/')
else:
return HttpResponseRedirect('/home/login/')
# no user obj found? (no email found actually)
else:
# redir
return HttpResponseRedirect('/home/')
to find if a user exists, however if a user is not found Django throws an error:
User matching query does not exist.
All I want to do is see if that query matches a result. How do I count rows?
|
[
"Use filter() instead of get().\n",
"I think this is probably more what you want:\ntry:\n user = User.objects.get(email__exact=email)\n if authenticate(user, email, password):\n request.session['user'] = user\n return HttpResponseRedirect('/home/')\n else:\n return HttpResponseRedirect('/home/login/')\nexcept User.DoesNotExist: # A user with the e-mail provided was not found\n return HttpResponseRedirect('/home/')\n\nPersonally I think that's cleaner than Ignacio's method, but it's a matter of taste really.\nFinally, the last part of your question (\"How do I count rows?\"):\nget only ever returns an object, and raises an exception if no objects match the criteria you passed in, or if multiple objects match the criteria. To get the number of objects in a QuerySet, you can just call len on it:\nq = User.objects.filter(email = 'foo@bar.com')\nprint len(q)\n\nOr, call count():\nprint User.objects.filter(email = 'foo@bar.com').count()\n\nThe former method (len) will be quicker if you've already evaluated the QuerySet (since it's just counting the number of items in a list, effectively); the latter (count()) will be faster if you've not evaluated the QuerySet, since Django will perform a SELECT COUNT(*) behind the scenes, and you avoid loading all the data into memory.\nAs an aside - why are you directing them to /home/ if the e-mail address isn't matched, and to /home/login/ if their credentials fail? I would have thought it makes more sense to redirect them to the same place for those two cases.\n"
] |
[
2,
1
] |
[] |
[] |
[
"authentication",
"django",
"python"
] |
stackoverflow_0002238594_authentication_django_python.txt
|
Q:
Does the Python "open" function save its content in memory or in a temp file?
For the following Python code:
fp = open('output.txt', 'wb')
# Very big file, writes a lot of lines, n is a very large number
for i in range(1, n):
fp.write('something' * n)
fp.close()
The writing process above can last more than 30 min. Sometimes I get the error MemoryError. Is the content of the file before closing stored in memory or written in a temp file? If it's in a temporary file, what is its general location on a Linux OS?
Edit:
Added fp.write in a for loop
A:
It's stored in the operating system's disk cache in memory until it is flushed to disk, either implicitly due to timing or space issues, or explicitly via fp.flush().
A:
There will be write buffering in the Linux kernel, but at (ir)regular intervals they will be flushed to disk. Running out of such buffer space should never cause an application-level memory error; the buffers should empty before that happens, pausing the application while doing so.
A:
Building on ataylor's comment to the question:
You might want to nest your loop. Something like
for i in range(1,n):
for each in range n:
fp.write('something')
fp.close()
That way, the only thing that gets put into memory is the string "something", not "something" * n.
A:
If you a writing out a large file for which the writes might fail you a better off flushing the file to disk yourself at regular intervals using fp.flush(). This way the file will be in a location of your choosing that you can easily get to rather than being at the mercy of the OS:
fp = open('output.txt', 'wb')
counter = 0
for line in many_lines:
file.write(line)
counter += 1
if counter > 999:
fp.flush()
fp.close()
This will flush the file to disk every 1000 lines.
A:
If you write line by line, it should not be a problem. You should show the code of what you are doing before the write. For a start you can try to delete objects where not necessary, use fp.flush() etc..
A:
File writing should never give a memory error; with all probability, you have some bug in another place.
If you have a loop, and a memory error, then I would look if you are "leaking" references to objects.
Something like:
def do_something(a, b = []):
b.append(a)
return b
fp = open('output.txt', 'wb')
for i in range(1, n):
something = do_something(i)
fp.write(something)
fp.close()
I am now picking just an example, but in your actual case the reference leak may be much more difficult to find; however this case will just leak memory inside do_something because of the way Python handles default parameters of functions.
|
Does the Python "open" function save its content in memory or in a temp file?
|
For the following Python code:
fp = open('output.txt', 'wb')
# Very big file, writes a lot of lines, n is a very large number
for i in range(1, n):
fp.write('something' * n)
fp.close()
The writing process above can last more than 30 min. Sometimes I get the error MemoryError. Is the content of the file before closing stored in memory or written in a temp file? If it's in a temporary file, what is its general location on a Linux OS?
Edit:
Added fp.write in a for loop
|
[
"It's stored in the operating system's disk cache in memory until it is flushed to disk, either implicitly due to timing or space issues, or explicitly via fp.flush().\n",
"There will be write buffering in the Linux kernel, but at (ir)regular intervals they will be flushed to disk. Running out of such buffer space should never cause an application-level memory error; the buffers should empty before that happens, pausing the application while doing so.\n",
"Building on ataylor's comment to the question: \nYou might want to nest your loop. Something like \nfor i in range(1,n):\n for each in range n:\n fp.write('something')\nfp.close()\n\nThat way, the only thing that gets put into memory is the string \"something\", not \"something\" * n.\n",
"If you a writing out a large file for which the writes might fail you a better off flushing the file to disk yourself at regular intervals using fp.flush(). This way the file will be in a location of your choosing that you can easily get to rather than being at the mercy of the OS:\nfp = open('output.txt', 'wb')\ncounter = 0\nfor line in many_lines:\n file.write(line)\n counter += 1\n if counter > 999:\n fp.flush()\nfp.close()\n\nThis will flush the file to disk every 1000 lines.\n",
"If you write line by line, it should not be a problem. You should show the code of what you are doing before the write. For a start you can try to delete objects where not necessary, use fp.flush() etc..\n",
"File writing should never give a memory error; with all probability, you have some bug in another place.\nIf you have a loop, and a memory error, then I would look if you are \"leaking\" references to objects.\nSomething like:\ndef do_something(a, b = []):\n b.append(a)\n return b\n\nfp = open('output.txt', 'wb') \n\nfor i in range(1, n): \n something = do_something(i)\n fp.write(something)\n\nfp.close()\n\nI am now picking just an example, but in your actual case the reference leak may be much more difficult to find; however this case will just leak memory inside do_something because of the way Python handles default parameters of functions.\n"
] |
[
5,
3,
3,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002239888_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.