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:
Potential use of Python decorator or other refactorization: iterative optimization
Forgive me for yet another question on Python decorators. I did read through many of them, but I wonder what the best solution to the specific following problem is.
I have written several functions that do some form of gradient descent in numpy/scipy. Given a matrix X, I try to iteratively minimize some distance, d(X, AS), as functions of A and S. Each algorithm follows the same basic procedure, but each has a different update rule. For example, here were two of my functions (note the only difference is in the update rule):
def algo1(X, A=None, S=None, K=2, maxiter=10, c=0.1):
M, N = X.shape
if A is None:
A = matrix(rand(M, K))
if S is None:
S = matrix(rand(K, N))
for iter in range(maxiter):
# Begin update rule.
A = multiply(A, (X*S.T + c)/(A*S*S.T + c))
S = multiply(S, (A.T*X + c)/(A.T*A*S + c))
# End update rule.
for k in range(K):
na = norm(A[:,k])
A[:,k] /= na
S[k,:] *= na
return A, S
... and the other:
def algo2(X, A=None, S=None, K=2, maxiter=10, c=0.1):
M, N = X.shape
O = matrix(ones([M, N]))
if A is None:
A = matrix(rand(M, K))
if S is None:
S = matrix(rand(K, N))
for iter in range(maxiter):
# Begin update rule.
A = multiply(A, ((X/(A*S))*S.T + c)/(O*S.T + c))
S = multiply(S, (A.T*(X/(A*S)) + c)/(A.T*O + c))
# End update rule.
for k in range(K):
na = norm(A[:,k])
A[:,k] /= na
S[k,:] *= na
return A, S
Both functions are successful on their own. Obviously, these functions are asking to be refactored. The unit of code that differs is the update rule. So here is my attempt at refactoring:
@iterate
def algo1(X, A=None, S=None, K=2, maxiter=10, c=0.1):
A = multiply(A, (X*S.T + c)/(A*S*S.T + c))
S = multiply(S, (A.T*X + c)/(A.T*A*S + c))
@iterate
def algo2(X, A=None, S=None, K=2, maxiter=10, c=0.1):
A = multiply(A, ((X/(A*S))*S.T + c)/(O*S.T + c))
S = multiply(S, (A.T*(X/(A*S)) + c)/(A.T*O + c))
Here are some potential function calls:
A, S = algo1(X)
A, S = algo1(X, A0, S0, maxiter=50, c=0.2)
A, S = algo1(X, K=10, maxiter=40)
Questions:
What technique is best suited for refactoring this code? Function decorators?
If so, how would you write iterate? What confuses me, in particular, are the arguments/parameters, e.g., with vs. without default values, accessing them in the decorator and "wrapper", etc. For example, the update rules themselves do not require K, but the initialization code does, so I wonder if my function signatures are correct.
EDIT: Thank you for the help. More questions:
Is it true that a wrapper (e.g., inner) is only necessary when parameters are being passed? Because I see decorator examples without wrappers, and no parameters are passed, and they work just fine.
From reading the Python docs some more, functools appears useful; is its main purpose to preserve the metadata of the original function (e.g., algo1.__name__ and algo1.__doc__)?
With the signatures def algo1(X, A, S, c) and def inner(X, A=None, S=None, K=2, maxiter=10, c=0.1), the call algo1(X, maxiter=20) still works. Syntactically, I'm not sure why that is. For learning purposes, could you clarify (or cite a reference)? Thanks!
A:
The following should work well as the decorator you want to use:
import functools
def iterate(update):
@functools.wraps(update)
def inner(X, A=None, S=None, K=2, maxiter=10, c=0.1):
M, N = X.shape
O = matrix(ones([M, N]))
if A is None:
A = matrix(rand(M, K))
if S is None:
S = matrix(rand(K, N))
for iter in range(maxiter):
A, S = update(X, A, S, K, maxiter, c)
for k in range(K):
na = norm(A[:,k])
A[:,k] /= na
S[k,:] *= na
return A, S
return inner
As you noticed, you could simplify algo1's and algo2's signatures, but it's not really a crucial part, and maybe keeping the signatures intact can simplify your testing and refactoring. If you do want to simplify, you'll change the def statements for those to, say,
def algo1(X, A, S, c):
and similarly simplify the call in the iterator decorate -- there's no need for two of the arguments, nor for the default values. However, avoiding this simplification part can actually make your life simpler -- it's normally simpler if the decorated function, and the result of decorating it, keep exactly the same signature as each other, unless you have really specific needs to the contrary.
edit: the OP keeps piling on questions onto this question...:
EDIT: Thank you for the help. More questions:
Is it true that a wrapper (e.g.,
inner) is only necessary when
parameters are being passed? Because I
see decorator examples without
wrappers, and no parameters are
passed, and they work just fine.
A decorator used without parameters (in the @decorname use) is called with the function being decorated, and must return a function; a decorator used with parameters (like @decorname(23)) must return a ("higher-order") function which in turn is called with the function being decorated, and must return a function. Whether the function being decorated takes parameter or not, does not change this set of rules. It's technically possible to achieve this without inner functions (which I assume is what you mean by "wrappers"?) but it's pretty rare to do so.
From reading the Python docs some
more, functools appears useful; is its
main purpose to preserve the metadata
of the original function (e.g.,
algo1.name and algo1.doc)?
Yes, functools.wraps is used exactly for this purpose (functools also contains partial which has a completely different purpose).
With the signatures def algo1(X, A, S,
c) and def inner(X, A=None, S=None,
K=2, maxiter=10, c=0.1), the call
algo1(X, maxiter=20) still works.
Syntactically, I'm not sure why that
is. For learning purposes, could you
clarify (or cite a reference)? Thanks!
It's because inner is the function that's actually called with those parameters (after algo1 has been decorated) and only passes down (to the "real underlying algo1) parameters X, A, S, c (in the version where the wrapped algo1 is given the simplified signature). The problem, as I mentioned above, is that this makes the metadata (specifically the signature) different between the function getting decorated, and the resulting decorated function; that is pretty confusing to read and maintain, so one normally keeps the same signature at both levels, save special circumstances.
|
Potential use of Python decorator or other refactorization: iterative optimization
|
Forgive me for yet another question on Python decorators. I did read through many of them, but I wonder what the best solution to the specific following problem is.
I have written several functions that do some form of gradient descent in numpy/scipy. Given a matrix X, I try to iteratively minimize some distance, d(X, AS), as functions of A and S. Each algorithm follows the same basic procedure, but each has a different update rule. For example, here were two of my functions (note the only difference is in the update rule):
def algo1(X, A=None, S=None, K=2, maxiter=10, c=0.1):
M, N = X.shape
if A is None:
A = matrix(rand(M, K))
if S is None:
S = matrix(rand(K, N))
for iter in range(maxiter):
# Begin update rule.
A = multiply(A, (X*S.T + c)/(A*S*S.T + c))
S = multiply(S, (A.T*X + c)/(A.T*A*S + c))
# End update rule.
for k in range(K):
na = norm(A[:,k])
A[:,k] /= na
S[k,:] *= na
return A, S
... and the other:
def algo2(X, A=None, S=None, K=2, maxiter=10, c=0.1):
M, N = X.shape
O = matrix(ones([M, N]))
if A is None:
A = matrix(rand(M, K))
if S is None:
S = matrix(rand(K, N))
for iter in range(maxiter):
# Begin update rule.
A = multiply(A, ((X/(A*S))*S.T + c)/(O*S.T + c))
S = multiply(S, (A.T*(X/(A*S)) + c)/(A.T*O + c))
# End update rule.
for k in range(K):
na = norm(A[:,k])
A[:,k] /= na
S[k,:] *= na
return A, S
Both functions are successful on their own. Obviously, these functions are asking to be refactored. The unit of code that differs is the update rule. So here is my attempt at refactoring:
@iterate
def algo1(X, A=None, S=None, K=2, maxiter=10, c=0.1):
A = multiply(A, (X*S.T + c)/(A*S*S.T + c))
S = multiply(S, (A.T*X + c)/(A.T*A*S + c))
@iterate
def algo2(X, A=None, S=None, K=2, maxiter=10, c=0.1):
A = multiply(A, ((X/(A*S))*S.T + c)/(O*S.T + c))
S = multiply(S, (A.T*(X/(A*S)) + c)/(A.T*O + c))
Here are some potential function calls:
A, S = algo1(X)
A, S = algo1(X, A0, S0, maxiter=50, c=0.2)
A, S = algo1(X, K=10, maxiter=40)
Questions:
What technique is best suited for refactoring this code? Function decorators?
If so, how would you write iterate? What confuses me, in particular, are the arguments/parameters, e.g., with vs. without default values, accessing them in the decorator and "wrapper", etc. For example, the update rules themselves do not require K, but the initialization code does, so I wonder if my function signatures are correct.
EDIT: Thank you for the help. More questions:
Is it true that a wrapper (e.g., inner) is only necessary when parameters are being passed? Because I see decorator examples without wrappers, and no parameters are passed, and they work just fine.
From reading the Python docs some more, functools appears useful; is its main purpose to preserve the metadata of the original function (e.g., algo1.__name__ and algo1.__doc__)?
With the signatures def algo1(X, A, S, c) and def inner(X, A=None, S=None, K=2, maxiter=10, c=0.1), the call algo1(X, maxiter=20) still works. Syntactically, I'm not sure why that is. For learning purposes, could you clarify (or cite a reference)? Thanks!
|
[
"The following should work well as the decorator you want to use:\nimport functools\n\ndef iterate(update):\n @functools.wraps(update)\n def inner(X, A=None, S=None, K=2, maxiter=10, c=0.1):\n M, N = X.shape\n O = matrix(ones([M, N]))\n if A is None:\n A = matrix(rand(M, K))\n if S is None:\n S = matrix(rand(K, N))\n for iter in range(maxiter):\n A, S = update(X, A, S, K, maxiter, c)\n for k in range(K):\n na = norm(A[:,k])\n A[:,k] /= na\n S[k,:] *= na\n return A, S\n return inner\n\nAs you noticed, you could simplify algo1's and algo2's signatures, but it's not really a crucial part, and maybe keeping the signatures intact can simplify your testing and refactoring. If you do want to simplify, you'll change the def statements for those to, say,\ndef algo1(X, A, S, c):\n\nand similarly simplify the call in the iterator decorate -- there's no need for two of the arguments, nor for the default values. However, avoiding this simplification part can actually make your life simpler -- it's normally simpler if the decorated function, and the result of decorating it, keep exactly the same signature as each other, unless you have really specific needs to the contrary.\nedit: the OP keeps piling on questions onto this question...:\nEDIT: Thank you for the help. More questions:\n\nIs it true that a wrapper (e.g.,\n inner) is only necessary when\n parameters are being passed? Because I\n see decorator examples without\n wrappers, and no parameters are\n passed, and they work just fine.\n\nA decorator used without parameters (in the @decorname use) is called with the function being decorated, and must return a function; a decorator used with parameters (like @decorname(23)) must return a (\"higher-order\") function which in turn is called with the function being decorated, and must return a function. Whether the function being decorated takes parameter or not, does not change this set of rules. It's technically possible to achieve this without inner functions (which I assume is what you mean by \"wrappers\"?) but it's pretty rare to do so.\n\nFrom reading the Python docs some\n more, functools appears useful; is its\n main purpose to preserve the metadata\n of the original function (e.g.,\n algo1.name and algo1.doc)?\n\nYes, functools.wraps is used exactly for this purpose (functools also contains partial which has a completely different purpose).\n\nWith the signatures def algo1(X, A, S,\n c) and def inner(X, A=None, S=None,\n K=2, maxiter=10, c=0.1), the call\n algo1(X, maxiter=20) still works.\n Syntactically, I'm not sure why that\n is. For learning purposes, could you\n clarify (or cite a reference)? Thanks!\n\nIt's because inner is the function that's actually called with those parameters (after algo1 has been decorated) and only passes down (to the \"real underlying algo1) parameters X, A, S, c (in the version where the wrapped algo1 is given the simplified signature). The problem, as I mentioned above, is that this makes the metadata (specifically the signature) different between the function getting decorated, and the resulting decorated function; that is pretty confusing to read and maintain, so one normally keeps the same signature at both levels, save special circumstances.\n"
] |
[
5
] |
[] |
[] |
[
"decorator",
"numpy",
"python",
"refactoring"
] |
stackoverflow_0002306171_decorator_numpy_python_refactoring.txt
|
Q:
How to write XML elements with namespaces in python
I just tried this python 2.5 snippet to write some XML:
xmldoc = xml.dom.minidom.Document()
feed = xmldoc.createElementNS("http://www.w3.org/2005/Atom", "feed")
xmldoc.appendChild(feed)
print xmldoc.toprettyxml()
I expected the output to look like this:
<?xml version="1.0" ?>
<feed xmlns="http://www.w3.org/2005/Atom" />
Instead I got this:
<?xml version="1.0" ?>
<feed />
Apparently the XML namespace is silently being ignored here. What am I doing wrong?
A:
minidom does not support namespace normalization. The only workaround I'm aware of is explicitely setting the xmlns attribute with
xmldoc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2005/Atom')
|
How to write XML elements with namespaces in python
|
I just tried this python 2.5 snippet to write some XML:
xmldoc = xml.dom.minidom.Document()
feed = xmldoc.createElementNS("http://www.w3.org/2005/Atom", "feed")
xmldoc.appendChild(feed)
print xmldoc.toprettyxml()
I expected the output to look like this:
<?xml version="1.0" ?>
<feed xmlns="http://www.w3.org/2005/Atom" />
Instead I got this:
<?xml version="1.0" ?>
<feed />
Apparently the XML namespace is silently being ignored here. What am I doing wrong?
|
[
"minidom does not support namespace normalization. The only workaround I'm aware of is explicitely setting the xmlns attribute with\nxmldoc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2005/Atom')\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002306149_python_xml.txt
|
Q:
Fast python XML validator with XPath support
I need to read a large XML (65 Mb), validate it against a xsd, and run XPath queries on it. Below, I've given an lxml version of that. It takes a lot of time (over 5 minutes) to run the query but validation seems to be pretty quick.
I've a couple of questions. How would a performance minded Python programmer write the program using lxml? Secondly, if lxml is not the right thing for the job, what else? and could you please give a code snippet?
import sys
from datetime import datetime
from lxml import etree
start = datetime.now()
schema_file = open("library.xsd")
schema = etree.XMLSchema(file=schema_file)
parser = etree.XMLParser(schema = schema)
data_file = open(sys.argv[1], 'r')
tree = etree.parse(data_file, parser)
root = tree.getroot()
data_file.close()
schema_file.close()
end = datetime.now()
delta = end-start
print "Parsing time = ", delta
start = datetime.now()
name_list = root.xpath("book/author/name/text()")
print ("Size of list = " + str(len(name_list)))
end = datetime.now()
delta = end-start
print "Query time = ", delta
A:
I wonder if you can rewrite the xpath expression to run faster? One thing that may work is to avoid building the name_list nodeset (if you don't need it later) and have the nodes counted inside of lxml. Something like this:
start = datetime.now()
name_list_len = root.xpath("count(/book/author/name/text())")
print ("Size of list = " + str(name_list_len))
end = datetime.now()
Otherwise, you may find the expat parser faster for extracting the text, but it isn't validating, and is more complex to use (you'll need to write a state machine and a couple of callbacks). If you just need the text, it may be faster to use the C implementation of the element tree API. The lxml benchmarks make interesting reading and do seem to hint that you could extract the text more quickly with that.
One common xpath performance issue is unnecessary use of '//' at the start of the expression. In this case, making the expression absolute, e.g.:
name_list = root.xpath("/rootelement/book/author/name/text()")
can be a lot quicker if the document is structured to allow this. Shouldn't be an issue here though.
A:
The lxml benchmarks are quite useful. It appears to me that extracting element nodes using XPath is fast but extracting text could be slow. Below, I've three solutions that are pretty fast.
def bench_lxml_xpath_direct(root): # Very slow but very fast if text() is removed.
name_list = root.xpath("book/author/name/text()")
print ("Size of list = " + str(len(name_list)))
def bench_lxml_xpath_loop(root): # Fast
name_list = root.xpath("book/author/name")
result = []
for n in name_list:
result.append(n.text)
print ("Size of list = " + str(len(name_list)))
def bench_lxml_getiterator(tree): # Very fast
result = []
for name in tree.getiterator("name"):
result.append(name.text)
print ("Size of list = " + str(len(result)))
def bench_lxml_findall(tree): # Superfast
result = []
for name in tree.findall("//name"):
result.append(name.text)
print ("Size of list = " + str(len(result)))
|
Fast python XML validator with XPath support
|
I need to read a large XML (65 Mb), validate it against a xsd, and run XPath queries on it. Below, I've given an lxml version of that. It takes a lot of time (over 5 minutes) to run the query but validation seems to be pretty quick.
I've a couple of questions. How would a performance minded Python programmer write the program using lxml? Secondly, if lxml is not the right thing for the job, what else? and could you please give a code snippet?
import sys
from datetime import datetime
from lxml import etree
start = datetime.now()
schema_file = open("library.xsd")
schema = etree.XMLSchema(file=schema_file)
parser = etree.XMLParser(schema = schema)
data_file = open(sys.argv[1], 'r')
tree = etree.parse(data_file, parser)
root = tree.getroot()
data_file.close()
schema_file.close()
end = datetime.now()
delta = end-start
print "Parsing time = ", delta
start = datetime.now()
name_list = root.xpath("book/author/name/text()")
print ("Size of list = " + str(len(name_list)))
end = datetime.now()
delta = end-start
print "Query time = ", delta
|
[
"I wonder if you can rewrite the xpath expression to run faster? One thing that may work is to avoid building the name_list nodeset (if you don't need it later) and have the nodes counted inside of lxml. Something like this:\nstart = datetime.now()\nname_list_len = root.xpath(\"count(/book/author/name/text())\")\nprint (\"Size of list = \" + str(name_list_len))\nend = datetime.now()\n\nOtherwise, you may find the expat parser faster for extracting the text, but it isn't validating, and is more complex to use (you'll need to write a state machine and a couple of callbacks). If you just need the text, it may be faster to use the C implementation of the element tree API. The lxml benchmarks make interesting reading and do seem to hint that you could extract the text more quickly with that. \nOne common xpath performance issue is unnecessary use of '//' at the start of the expression. In this case, making the expression absolute, e.g.:\n name_list = root.xpath(\"/rootelement/book/author/name/text()\")\n\ncan be a lot quicker if the document is structured to allow this. Shouldn't be an issue here though. \n",
"The lxml benchmarks are quite useful. It appears to me that extracting element nodes using XPath is fast but extracting text could be slow. Below, I've three solutions that are pretty fast.\ndef bench_lxml_xpath_direct(root): # Very slow but very fast if text() is removed.\n name_list = root.xpath(\"book/author/name/text()\")\n print (\"Size of list = \" + str(len(name_list)))\n\ndef bench_lxml_xpath_loop(root): # Fast\n name_list = root.xpath(\"book/author/name\")\n result = []\n for n in name_list:\n result.append(n.text)\n\n print (\"Size of list = \" + str(len(name_list)))\n\ndef bench_lxml_getiterator(tree): # Very fast\n result = []\n for name in tree.getiterator(\"name\"):\n result.append(name.text)\n print (\"Size of list = \" + str(len(result)))\n\n\ndef bench_lxml_findall(tree): # Superfast\n result = []\n for name in tree.findall(\"//name\"):\n result.append(name.text)\n print (\"Size of list = \" + str(len(result)))\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"validation",
"xml",
"xpath",
"xsd"
] |
stackoverflow_0002302709_python_validation_xml_xpath_xsd.txt
|
Q:
Reading text files into list, then storing in dictionay fills system memory ? (A what am I doing wrong?) Python
I have 43 text files that consume "232.2 MB on disk (232,129,355 bytes) for 43 items". what to read them in to memory (see code below). The problem I am having is that each file which is about 5.3mb on disk is causing python to use an additional 100mb of system memory. If check the size of the dict() getsizeof() (see sample of output). When python is up to 3GB of system memory getsizeof(dict()) is only using 6424 bytes of memory. I don't understand what is using the memory.
What is using up all the memory?
The related link is different in that the reported memory use by python was "correct"
related question
I am not very interested in other solutions DB .... I am more interested in understanding what is happening so I know how to avoid it in the future. That said using other python built ins array rather than lists are are great suggestion if it helps.
I have heard suggestions of using guppy to find what is using the memory.
sample output:
Loading into memory: ME49_800.txt
ME49_800.txt has 228484 rows of data
ME49_800.txt has 0 rows of masked data
ME49_800.txt has 198 rows of outliers
ME49_800.txt has 0 modified rows of data
280bytes of memory used for ME49_800.txt
43 files of 43 using 12568 bytes of memory
120
Sample data:
CellHeader=X Y MEAN STDV NPIXELS
0 0 120.0 28.3 25
1 0 6924.0 1061.7 25
2 0 105.0 17.4 25
Code:
import csv, os, glob
import sys
def read_data_file(filename):
reader = csv.reader(open(filename, "U"),delimiter='\t')
fname = os.path.split(filename)[1]
data = []
mask = []
outliers = []
modified = []
maskcount = 0
outliercount = 0
modifiedcount = 0
for row in reader:
if '[MASKS]' in row:
maskcount = 1
if '[OUTLIERS]' in row:
outliercount = 1
if '[MODIFIED]' in row:
modifiedcount = 1
if row:
if not any((maskcount, outliercount, modifiedcount)):
data.append(row)
elif not any((not maskcount, outliercount, modifiedcount)):
mask.append(row)
elif not any((not maskcount, not outliercount, modifiedcount)):
outliers.append(row)
elif not any((not maskcount, not outliercount, not modifiedcount)):
modified.append(row)
else: print '***something went wrong***'
data = data[1:]
mask = mask[3:]
outliers = outliers[3:]
modified = modified[3:]
filedata = dict(zip((fname + '_data', fname + '_mask', fname + '_outliers', fname+'_modified'), (data, mask, outliers, modified)))
return filedata
def ImportDataFrom(folder):
alldata = dict{}
infolder = glob.glob( os.path.join(folder, '*.txt') )
numfiles = len(infolder)
print 'Importing files from: ', folder
print 'Importing ' + str(numfiles) + ' files from: ', folder
for infile in infolder:
fname = os.path.split(infile)[1]
print "Loading into memory: " + fname
filedata = read_data_file(infile)
alldata.update(filedata)
print fname + ' has ' + str(len(filedata[fname + '_data'])) + ' rows of data'
print fname + ' has ' + str(len(filedata[fname + '_mask'])) + ' rows of masked data'
print fname + ' has ' + str(len(filedata[fname + '_outliers'])) + ' rows of outliers'
print fname + ' has ' + str(len(filedata[fname +'_modified'])) + ' modified rows of data'
print str(sys.getsizeof(filedata)) +'bytes'' of memory used for '+ fname
print str(len(alldata)/4) + ' files of ' + str(numfiles) + ' using ' + str(sys.getsizeof(alldata)) + ' bytes of memory'
#print alldata.keys()
print str(sys.getsizeof(ImportDataFrom))
print ' '
return alldata
ImportDataFrom("/Users/vmd/Dropbox/dna/data/rawdata")
A:
The dictionary itself is very small - the bulk of the data is the whole content of the files stored in lists, containing one tuple per line. The 20x size increase is bigger than I expected but seems to be real. Splitting a 27-bytes line from your example input into a tuple, gives me 309 bytes (counting recursively, on a 64-bit machine). Add to this some unknown overhead of memory allocation, and 20x is not impossible.
Alternatives: for more compact representation, you want to convert the strings to integers/floats and to tightly pack them (without all that pointers and separate objects). I'm talking not just one row (although that's a start), but a whole list of rows together - so each file will be represented by just four 2D arrays of numbers. The array module is a start, but really what you need here are numpy arrays:
# Using explicit field types for compactness and access by name
# (e.g. data[i]['mean'] == data[i][2]).
fields = [('x', int), ('y', int), ('mean', float),
('stdv', float), ('npixels', int)]
# The simplest way is to build lists as you do now, and convert them
# to numpy array when done.
data = numpy.array(data, dtype=fields)
mask = numpy.array(mask, dtype=fields)
...
This gives me 40 bytes spent per row (measured on the .data attribute; sys.getsizeof reports that the array has a constant overhead of 80 bytes, but doesn't see the actual data used). This is still a ~1.5 more than the original files, but should easily fit into RAM.
I see 2 of your fields are labeled "x" and "y" - if your data is dense, you could arrange it by them - data[x,y]==... - instead of just storing (x,y,...) records. Besides being slightly more compact, it would be the most sensible structure, allowing easier processing.
If you need to handle even more data than your RAM will fit, pytables is a good library for efficient access to compact (even compressed) tabular data in files. (It's much better at this than general SQL DBs.)
A:
This line specifically gets the size of the function object:
print str(sys.getsizeof(ImportDataFrom))
that's unlikely to be what you're interested in.
The size of a container does not include the size of the data it contains. Consider, for example:
>>> import sys
>>> d={}
>>> sys.getsizeof(d)
140
>>> d['foo'] = 'x'*99
>>> sys.getsizeof(d)
140
>>> d['foo'] = 'x'*9999
>>> sys.getsizeof(d)
140
If you want the size of the container plus the size of all contained things you have to write your own (presumably recursive) function that reaches inside containers and digs for every byte. Or, you can use third-party libraries such as Pympler or guppy.
|
Reading text files into list, then storing in dictionay fills system memory ? (A what am I doing wrong?) Python
|
I have 43 text files that consume "232.2 MB on disk (232,129,355 bytes) for 43 items". what to read them in to memory (see code below). The problem I am having is that each file which is about 5.3mb on disk is causing python to use an additional 100mb of system memory. If check the size of the dict() getsizeof() (see sample of output). When python is up to 3GB of system memory getsizeof(dict()) is only using 6424 bytes of memory. I don't understand what is using the memory.
What is using up all the memory?
The related link is different in that the reported memory use by python was "correct"
related question
I am not very interested in other solutions DB .... I am more interested in understanding what is happening so I know how to avoid it in the future. That said using other python built ins array rather than lists are are great suggestion if it helps.
I have heard suggestions of using guppy to find what is using the memory.
sample output:
Loading into memory: ME49_800.txt
ME49_800.txt has 228484 rows of data
ME49_800.txt has 0 rows of masked data
ME49_800.txt has 198 rows of outliers
ME49_800.txt has 0 modified rows of data
280bytes of memory used for ME49_800.txt
43 files of 43 using 12568 bytes of memory
120
Sample data:
CellHeader=X Y MEAN STDV NPIXELS
0 0 120.0 28.3 25
1 0 6924.0 1061.7 25
2 0 105.0 17.4 25
Code:
import csv, os, glob
import sys
def read_data_file(filename):
reader = csv.reader(open(filename, "U"),delimiter='\t')
fname = os.path.split(filename)[1]
data = []
mask = []
outliers = []
modified = []
maskcount = 0
outliercount = 0
modifiedcount = 0
for row in reader:
if '[MASKS]' in row:
maskcount = 1
if '[OUTLIERS]' in row:
outliercount = 1
if '[MODIFIED]' in row:
modifiedcount = 1
if row:
if not any((maskcount, outliercount, modifiedcount)):
data.append(row)
elif not any((not maskcount, outliercount, modifiedcount)):
mask.append(row)
elif not any((not maskcount, not outliercount, modifiedcount)):
outliers.append(row)
elif not any((not maskcount, not outliercount, not modifiedcount)):
modified.append(row)
else: print '***something went wrong***'
data = data[1:]
mask = mask[3:]
outliers = outliers[3:]
modified = modified[3:]
filedata = dict(zip((fname + '_data', fname + '_mask', fname + '_outliers', fname+'_modified'), (data, mask, outliers, modified)))
return filedata
def ImportDataFrom(folder):
alldata = dict{}
infolder = glob.glob( os.path.join(folder, '*.txt') )
numfiles = len(infolder)
print 'Importing files from: ', folder
print 'Importing ' + str(numfiles) + ' files from: ', folder
for infile in infolder:
fname = os.path.split(infile)[1]
print "Loading into memory: " + fname
filedata = read_data_file(infile)
alldata.update(filedata)
print fname + ' has ' + str(len(filedata[fname + '_data'])) + ' rows of data'
print fname + ' has ' + str(len(filedata[fname + '_mask'])) + ' rows of masked data'
print fname + ' has ' + str(len(filedata[fname + '_outliers'])) + ' rows of outliers'
print fname + ' has ' + str(len(filedata[fname +'_modified'])) + ' modified rows of data'
print str(sys.getsizeof(filedata)) +'bytes'' of memory used for '+ fname
print str(len(alldata)/4) + ' files of ' + str(numfiles) + ' using ' + str(sys.getsizeof(alldata)) + ' bytes of memory'
#print alldata.keys()
print str(sys.getsizeof(ImportDataFrom))
print ' '
return alldata
ImportDataFrom("/Users/vmd/Dropbox/dna/data/rawdata")
|
[
"The dictionary itself is very small - the bulk of the data is the whole content of the files stored in lists, containing one tuple per line. The 20x size increase is bigger than I expected but seems to be real. Splitting a 27-bytes line from your example input into a tuple, gives me 309 bytes (counting recursively, on a 64-bit machine). Add to this some unknown overhead of memory allocation, and 20x is not impossible.\nAlternatives: for more compact representation, you want to convert the strings to integers/floats and to tightly pack them (without all that pointers and separate objects). I'm talking not just one row (although that's a start), but a whole list of rows together - so each file will be represented by just four 2D arrays of numbers. The array module is a start, but really what you need here are numpy arrays:\n# Using explicit field types for compactness and access by name\n# (e.g. data[i]['mean'] == data[i][2]).\nfields = [('x', int), ('y', int), ('mean', float), \n ('stdv', float), ('npixels', int)]\n# The simplest way is to build lists as you do now, and convert them\n# to numpy array when done.\ndata = numpy.array(data, dtype=fields)\nmask = numpy.array(mask, dtype=fields)\n...\n\nThis gives me 40 bytes spent per row (measured on the .data attribute; sys.getsizeof reports that the array has a constant overhead of 80 bytes, but doesn't see the actual data used). This is still a ~1.5 more than the original files, but should easily fit into RAM.\nI see 2 of your fields are labeled \"x\" and \"y\" - if your data is dense, you could arrange it by them - data[x,y]==... - instead of just storing (x,y,...) records. Besides being slightly more compact, it would be the most sensible structure, allowing easier processing.\nIf you need to handle even more data than your RAM will fit, pytables is a good library for efficient access to compact (even compressed) tabular data in files. (It's much better at this than general SQL DBs.)\n",
"This line specifically gets the size of the function object:\nprint str(sys.getsizeof(ImportDataFrom))\n\nthat's unlikely to be what you're interested in.\nThe size of a container does not include the size of the data it contains. Consider, for example:\n>>> import sys\n>>> d={}\n>>> sys.getsizeof(d)\n140\n>>> d['foo'] = 'x'*99\n>>> sys.getsizeof(d)\n140\n>>> d['foo'] = 'x'*9999\n>>> sys.getsizeof(d)\n140\n\nIf you want the size of the container plus the size of all contained things you have to write your own (presumably recursive) function that reaches inside containers and digs for every byte. Or, you can use third-party libraries such as Pympler or guppy.\n"
] |
[
3,
2
] |
[] |
[] |
[
"file",
"memory",
"python"
] |
stackoverflow_0002306523_file_memory_python.txt
|
Q:
python random.random() causes "'module' object is not callable" when used in custom template tag
If I start python from the command line and type:
import random
print "Random: " + str(random.random())
It prints me a random number (Expected, excellent).
If I include the above-two lines in my django application's models.py and start my django app with runserver I get the output on the command line showing me a random number (Great!)
If I take a custom tag which works perfectly fine otherwise, but I include
import random
print "Random: " + str(random.random())
as the first 2 lines of the custom tag's .py file, I get an error whenever I try to open up a template which uses that custom tag:
TypeError at /help/
'module' object is not callable
Please keep in mind that if I get rid of these two lines, my custom tag behaves as otherwise expected and no error is thrown. Unfortunately, I need some random behavior inside of my template tag.
The problem is if in a custom tag I do:
import random
on a custom template tag, it imports
<module 'django.templatetags.random' from '[snip path]'>
and not
<module 'random' from 'C:\\Program Files\\Python26\\lib\\random.pyc'>
as is normally imported from everywhere else
Django template library has a filter called random, and somehow it is getting priority above the system's random.
Can anyone recommend how to explicitly import the proper python random?
A:
The answer is ... strange.
When I originally wrote my custom tag, I called it random.py. I quickly realized that this name may not be good and renamed it randomchoice.py and deleted my random.py file. Python kept the compiled random.pyc file around, and it was getting loaded whenever I did import random. I removed my random.pyc file, and the problem went away.
A:
Yes, this kind of error is pretty easy. Basically don't name any of your filenames or anything you create with the same names as any likely python modules you are going to use.
A:
Its been a while since I tinkered around with Django, but if random.random is a "module", then try random.random.random(). Or maybe just try random(). You just don't know what kind of hackery goes on behind the scenes.
Edit
Try this:
sys.path = [r"C:\Program Files\Python26\lib\"] + sys.path
import random
sys.path.pop(0)
|
python random.random() causes "'module' object is not callable" when used in custom template tag
|
If I start python from the command line and type:
import random
print "Random: " + str(random.random())
It prints me a random number (Expected, excellent).
If I include the above-two lines in my django application's models.py and start my django app with runserver I get the output on the command line showing me a random number (Great!)
If I take a custom tag which works perfectly fine otherwise, but I include
import random
print "Random: " + str(random.random())
as the first 2 lines of the custom tag's .py file, I get an error whenever I try to open up a template which uses that custom tag:
TypeError at /help/
'module' object is not callable
Please keep in mind that if I get rid of these two lines, my custom tag behaves as otherwise expected and no error is thrown. Unfortunately, I need some random behavior inside of my template tag.
The problem is if in a custom tag I do:
import random
on a custom template tag, it imports
<module 'django.templatetags.random' from '[snip path]'>
and not
<module 'random' from 'C:\\Program Files\\Python26\\lib\\random.pyc'>
as is normally imported from everywhere else
Django template library has a filter called random, and somehow it is getting priority above the system's random.
Can anyone recommend how to explicitly import the proper python random?
|
[
"The answer is ... strange.\nWhen I originally wrote my custom tag, I called it random.py. I quickly realized that this name may not be good and renamed it randomchoice.py and deleted my random.py file. Python kept the compiled random.pyc file around, and it was getting loaded whenever I did import random. I removed my random.pyc file, and the problem went away.\n",
"Yes, this kind of error is pretty easy. Basically don't name any of your filenames or anything you create with the same names as any likely python modules you are going to use. \n",
"Its been a while since I tinkered around with Django, but if random.random is a \"module\", then try random.random.random(). Or maybe just try random(). You just don't know what kind of hackery goes on behind the scenes.\nEdit\nTry this:\nsys.path = [r\"C:\\Program Files\\Python26\\lib\\\"] + sys.path\nimport random\nsys.path.pop(0)\n\n"
] |
[
18,
5,
2
] |
[] |
[] |
[
"django",
"python",
"random",
"templatetags"
] |
stackoverflow_0000837916_django_python_random_templatetags.txt
|
Q:
Seeing if a list exists within another list?
Basically lets say i have:
>>> a = [1,3,2,2,2]
>>> b = [1,3,2]
I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.
I am kinda hoping theres a really simple one line answer.
A:
This is a simple O(n * m) algorithm:
any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))
Note that is not the fastest way of doing this. If you need high performance you could use similar techniques to those used in string searching algorithms.
A:
If by 'in the same order' you meant subsequence (as opposed to substring) then this non-one-liner should work fast:
def is_subsequence(x, y):
i, j = 0, 0
while i < len(x) and j < len(y):
if x[i] == y[j]:
i += 1
j += 1
return i == len(x)
A:
Here's a solution that works for lists of ints.
Turn for example [1, 3, 2] into the string "'1', '3', '2'". Then use built-in string inclusion to see if it's in the other list.
repr(map(str, b))[1:-1] in repr(map(str, a))[1:-1]
A:
This is probably not very efficient, but you could use:
In [1]: a = [1,3,2,2,2]
In [2]: b = [1,3,2]
In [3]: b == [val for val in a if val in b]
Out[3]: False
In [4]: a = [6,1,3,2,5,4]
In [5]: b == [val for val in a if val in b]
Out[5]: True
The first test returns False because of the duplicates of 2. The question is how you want to deal with duplicates in general. If you only want to cut them off at the end then you could trim the list to the length of a:
In [6]: a = [1,3,2,2,2]
In [7]: b == [val for val in a if val in b][:len(b)]
Out[7]: True
A:
Sorry, but what you want to do is effectively the same as string matching (albeit with lists instead of strings). You might want to look at Knuth-Morris-Pratt or Boyer Moore for a linear time algorithm.
EDIT:
I am assuming that by "in order" you mean consecutively anywhere in the sequence. If they can be separated by other elements in between, then this is not the solution you want.
|
Seeing if a list exists within another list?
|
Basically lets say i have:
>>> a = [1,3,2,2,2]
>>> b = [1,3,2]
I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.
I am kinda hoping theres a really simple one line answer.
|
[
"This is a simple O(n * m) algorithm:\nany(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))\n\nNote that is not the fastest way of doing this. If you need high performance you could use similar techniques to those used in string searching algorithms.\n",
"If by 'in the same order' you meant subsequence (as opposed to substring) then this non-one-liner should work fast:\n def is_subsequence(x, y):\n i, j = 0, 0\n while i < len(x) and j < len(y):\n if x[i] == y[j]:\n i += 1\n j += 1\n return i == len(x)\n\n",
"Here's a solution that works for lists of ints.\nTurn for example [1, 3, 2] into the string \"'1', '3', '2'\". Then use built-in string inclusion to see if it's in the other list.\nrepr(map(str, b))[1:-1] in repr(map(str, a))[1:-1]\n\n",
"This is probably not very efficient, but you could use:\nIn [1]: a = [1,3,2,2,2]\n\nIn [2]: b = [1,3,2]\n\nIn [3]: b == [val for val in a if val in b]\nOut[3]: False\n\nIn [4]: a = [6,1,3,2,5,4]\n\nIn [5]: b == [val for val in a if val in b]\nOut[5]: True\n\nThe first test returns False because of the duplicates of 2. The question is how you want to deal with duplicates in general. If you only want to cut them off at the end then you could trim the list to the length of a:\nIn [6]: a = [1,3,2,2,2]\n\nIn [7]: b == [val for val in a if val in b][:len(b)]\nOut[7]: True\n\n",
"Sorry, but what you want to do is effectively the same as string matching (albeit with lists instead of strings). You might want to look at Knuth-Morris-Pratt or Boyer Moore for a linear time algorithm.\nEDIT:\nI am assuming that by \"in order\" you mean consecutively anywhere in the sequence. If they can be separated by other elements in between, then this is not the solution you want.\n"
] |
[
6,
2,
1,
0,
0
] |
[
"if its \"in the same order\", \n>>> a = [1,3,2,2,2]\n>>> b = [1,3,2]\n>>> ' '.join(map(str,b)) in ' '.join(map(str,a))\nTrue\n\n>>> a = [1,1,2,2,2,13,2]\n>>> b = [1,3,2]\n>>> ' '.join(map(str,b)) in ' '.join(map(str,a))\nFalse\n\n"
] |
[
-2
] |
[
"list",
"python"
] |
stackoverflow_0002305729_list_python.txt
|
Q:
Is there a open-search solution for python?
lucene-like would be preferred.
thanks
A:
You can also check ElasticSearch, it has native JSON interface so integrating with it in python should be simpler. Seems like Simon Willison thinks it got potential...
A:
Why you need lucene-like when you can use lucene (PyLucene) :)
http://lucene.apache.org/pylucene/
It is great and builds against the latest build of lucene
quote from site:
PyLucene is a Python extension for
accessing Java Lucene. Its goal is to
allow you to use Lucene's text
indexing and searching capabilities
from Python. It is API compatible with
the latest version of Java Lucene,
version 2.9.0 as of October 13th,
2009.
PyLucene is not a Lucene port but a
Python wrapper around Java Lucene.
PyLucene embeds a Java VM with Lucene
into a Python process. The PyLucene
Python extension, a Python module
called lucene, is machine-generated by
JCC.
PyLucene is built with JCC, a C++ code
generator that makes it possible to
call into Java classes from Python via
Java's Native Invocation Interface
(JNI). Sources for JCC are included
with the PyLucene sources.
A:
See SolPython and solrpy
What is solrpy?
solrpy is a python client for solr, an
enterprise search server built on top
of lucene. solrpy allows you to add
documents to a solr instance, and then
to perform queries and gather search
results from solr using your favorite
programming language--python.
A:
How about python bindings for Lucene?
A:
How about Sphinx? http://www.sphinxsearch.com/
It has Python bindings included.
I don't have comparision with other solutions like Lucene,
but I'm using Sphinx for CRM and it works very well,
indexing emails, notes etc.
A:
Xapian is an excellent Lucene-alternative, with fairly good Python-bindings, which is also easier to install than pylucene.
|
Is there a open-search solution for python?
|
lucene-like would be preferred.
thanks
|
[
"You can also check ElasticSearch, it has native JSON interface so integrating with it in python should be simpler. Seems like Simon Willison thinks it got potential...\n",
"Why you need lucene-like when you can use lucene (PyLucene) :)\nhttp://lucene.apache.org/pylucene/\nIt is great and builds against the latest build of lucene\nquote from site:\n\nPyLucene is a Python extension for\n accessing Java Lucene. Its goal is to\n allow you to use Lucene's text\n indexing and searching capabilities\n from Python. It is API compatible with\n the latest version of Java Lucene,\n version 2.9.0 as of October 13th,\n 2009.\nPyLucene is not a Lucene port but a\n Python wrapper around Java Lucene.\n PyLucene embeds a Java VM with Lucene\n into a Python process. The PyLucene\n Python extension, a Python module\n called lucene, is machine-generated by\n JCC.\nPyLucene is built with JCC, a C++ code\n generator that makes it possible to\n call into Java classes from Python via\n Java's Native Invocation Interface\n (JNI). Sources for JCC are included\n with the PyLucene sources.\n\n",
"See SolPython and solrpy\n\nWhat is solrpy?\nsolrpy is a python client for solr, an\n enterprise search server built on top\n of lucene. solrpy allows you to add\n documents to a solr instance, and then\n to perform queries and gather search\n results from solr using your favorite\n programming language--python.\n\n",
"How about python bindings for Lucene?\n",
"How about Sphinx? http://www.sphinxsearch.com/\nIt has Python bindings included.\nI don't have comparision with other solutions like Lucene, \nbut I'm using Sphinx for CRM and it works very well, \nindexing emails, notes etc.\n",
"Xapian is an excellent Lucene-alternative, with fairly good Python-bindings, which is also easier to install than pylucene.\n"
] |
[
12,
10,
3,
1,
0,
0
] |
[] |
[] |
[
"lucene",
"python",
"search"
] |
stackoverflow_0002305026_lucene_python_search.txt
|
Q:
Python class syntax - is this a good idea?
I'm tempted to define my Python classes like this:
class MyClass(object):
"""my docstring"""
msg = None
a_variable = None
some_dict = {}
def __init__(self, msg):
self.msg = msg
Is declaring the object variables (msg, a_variable, etc) at the top, like Java good or bad or indifferent? I know it's unnecessary, but still tempting to do.
A:
Defining variables in the class defintion like that makes the variable accessible between every instance of that class. In Java terms it is a bit like making the variable static. However, there are major differences as show below.
class MyClass(object):
msg = "ABC"
print MyClass.msg #prints ABC
a = MyClass()
print a.msg #prints ABC
a.msg = "abc"
print a.msg #prints abc
print MyClass.msg #prints ABC
print a.__class__.msg #prints ABC
As seen from the above code, it is not quite the same thing, as while the variable can be access via self.msg, when it is assigned a value it is not assigned to the variable defined at class scope.
One of the disadvantage of doing it via the method you do is that it can lead to errors as it adds hidden state the the class. Say someone left out self.msg = "ABC" from the constructor (Or more realistically code was refactored and only one of the definitions was altered)
a = MyClass()
print a.msg #prints ABC
#somewhere else in the program
MyClass.msg = "XYZ"
#now the same bit of code leads to a different result, despite the expectation that it
#leads to the same result.
a = MyClass()
print a.msg #prints XYZ
Far better to avoid defining msg at the class level and then you avoid the issues:
class MyClass(object):
pass
print MyClass.msg #AttributeError: type object 'MyClass' has no attribute 'msg'
A:
Declaring variables directly inside the class definition makes them class variables instead of instance variables. Class variables are somewhat similar to static variables in Java and should be used like MyClass.a_variable. But they can also be used like self.a_variable, which is a problem because naive programmers can treat them as instance variables. Your "some_dict" variable, for example, would be shared by each instance of MyClass, so if you add a key "k" to it, that will be visible to any instance.
If you always remember to re-assign class variables, there's almost no difference to instance variables. Only the initial definition in MyClass will remain. But anyway, that's not good practice as you might run into trouble when not re-assigning those variables!
Better write the class like so:
class MyClass(object):
"""
Some class
"""
def __init__(self, msg):
self.__msg = msg
self.__a_variable = None
self.__some_dict = {}
Using two underscores for "private" variables (pseudo-private!) is optional. If the variables should be public, just keep their names without the __ prefix.
A:
Careful. The two msg attributes are actually stored in two different dictionaries.
One overshadows the other, but the clobbered msg attribute is still taking up space in a dictionary. So it goes unused and yet still takes up some memory.
class MyClass(object):
msg = 'FeeFiFoFum'
def __init__(self, msg):
self.msg = msg
m=MyClass('Hi Lucy')
Notice that we have 'Hi Lucy' as the value.
print(m.__dict__)
# {'msg': 'Hi Lucy'}
Notice that MyClass's dict (accessed through m.__class__) still has FeeFiFoFum.
print(m.__class__.__dict__)
# {'__dict__': <attribute '__dict__' of 'MyClass' objects>, '__module__': '__main__', '__init__': <function __init__ at 0xb76ea1ec>, 'msg': 'FeeFiFoFum', 'some_dict': {}, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': 'my docstring', 'a_variable': None}
Another (perhaps simpler) way to see this:
print(m.msg)
# Hi Lucy
print(MyClass.msg)
# FeeFiFoFum
A:
When you declare a class, Python will parse its code and put everything in the namespace of the class; then the class will be used as a kind of template for all objects derived from it - but any object will have its own copy of the reference.
Note that you always have a reference; as such, if you are able to alter the referenced object, the change will reflect into all places it is being used. However, the slot for the member data is unique for each instance, and therefore assigning it to a new object will not reflect to any other place it is being used.
Note: Michael Foord has a very nice blog entry on how class instantiation works; if you are interested in this topic, I suggest you that short reading.
Anyway, for all practical uses, there are two main differences between your two approaches:
The name is already available at class level, and you can use it without instantiating a new object; this may sound neat for declaring constants in namespaces, but in many cases the module name may already be a good one.
The name is added at class level - it means that you may not be able to mock it easily during unit tests, and that if you have any expensive operation, you get it at the very moment of the import.
Usually, reviewing code I see members declared at class level with a bit of suspicion; there are a lot of good usecases for them, but it is also quite likely they are there as a kind of habit from previous experiences with other programming languages.
|
Python class syntax - is this a good idea?
|
I'm tempted to define my Python classes like this:
class MyClass(object):
"""my docstring"""
msg = None
a_variable = None
some_dict = {}
def __init__(self, msg):
self.msg = msg
Is declaring the object variables (msg, a_variable, etc) at the top, like Java good or bad or indifferent? I know it's unnecessary, but still tempting to do.
|
[
"Defining variables in the class defintion like that makes the variable accessible between every instance of that class. In Java terms it is a bit like making the variable static. However, there are major differences as show below.\nclass MyClass(object):\n msg = \"ABC\"\n\nprint MyClass.msg #prints ABC\na = MyClass()\nprint a.msg #prints ABC\na.msg = \"abc\"\nprint a.msg #prints abc\nprint MyClass.msg #prints ABC\nprint a.__class__.msg #prints ABC\n\nAs seen from the above code, it is not quite the same thing, as while the variable can be access via self.msg, when it is assigned a value it is not assigned to the variable defined at class scope.\nOne of the disadvantage of doing it via the method you do is that it can lead to errors as it adds hidden state the the class. Say someone left out self.msg = \"ABC\" from the constructor (Or more realistically code was refactored and only one of the definitions was altered)\na = MyClass()\nprint a.msg #prints ABC\n\n#somewhere else in the program\nMyClass.msg = \"XYZ\"\n\n#now the same bit of code leads to a different result, despite the expectation that it\n#leads to the same result.\na = MyClass()\nprint a.msg #prints XYZ\n\nFar better to avoid defining msg at the class level and then you avoid the issues:\nclass MyClass(object):\n pass\n\nprint MyClass.msg #AttributeError: type object 'MyClass' has no attribute 'msg'\n\n",
"Declaring variables directly inside the class definition makes them class variables instead of instance variables. Class variables are somewhat similar to static variables in Java and should be used like MyClass.a_variable. But they can also be used like self.a_variable, which is a problem because naive programmers can treat them as instance variables. Your \"some_dict\" variable, for example, would be shared by each instance of MyClass, so if you add a key \"k\" to it, that will be visible to any instance.\nIf you always remember to re-assign class variables, there's almost no difference to instance variables. Only the initial definition in MyClass will remain. But anyway, that's not good practice as you might run into trouble when not re-assigning those variables!\nBetter write the class like so:\nclass MyClass(object):\n \"\"\"\n Some class\n \"\"\"\n\n def __init__(self, msg):\n self.__msg = msg\n self.__a_variable = None\n self.__some_dict = {}\n\nUsing two underscores for \"private\" variables (pseudo-private!) is optional. If the variables should be public, just keep their names without the __ prefix.\n",
"Careful. The two msg attributes are actually stored in two different dictionaries.\nOne overshadows the other, but the clobbered msg attribute is still taking up space in a dictionary. So it goes unused and yet still takes up some memory.\nclass MyClass(object): \n msg = 'FeeFiFoFum' \n def __init__(self, msg):\n self.msg = msg\n\nm=MyClass('Hi Lucy')\n\nNotice that we have 'Hi Lucy' as the value.\nprint(m.__dict__)\n# {'msg': 'Hi Lucy'}\n\nNotice that MyClass's dict (accessed through m.__class__) still has FeeFiFoFum.\nprint(m.__class__.__dict__)\n# {'__dict__': <attribute '__dict__' of 'MyClass' objects>, '__module__': '__main__', '__init__': <function __init__ at 0xb76ea1ec>, 'msg': 'FeeFiFoFum', 'some_dict': {}, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': 'my docstring', 'a_variable': None}\n\nAnother (perhaps simpler) way to see this:\nprint(m.msg)\n# Hi Lucy\nprint(MyClass.msg)\n# FeeFiFoFum\n\n",
"When you declare a class, Python will parse its code and put everything in the namespace of the class; then the class will be used as a kind of template for all objects derived from it - but any object will have its own copy of the reference.\nNote that you always have a reference; as such, if you are able to alter the referenced object, the change will reflect into all places it is being used. However, the slot for the member data is unique for each instance, and therefore assigning it to a new object will not reflect to any other place it is being used. \nNote: Michael Foord has a very nice blog entry on how class instantiation works; if you are interested in this topic, I suggest you that short reading.\nAnyway, for all practical uses, there are two main differences between your two approaches:\n\nThe name is already available at class level, and you can use it without instantiating a new object; this may sound neat for declaring constants in namespaces, but in many cases the module name may already be a good one.\nThe name is added at class level - it means that you may not be able to mock it easily during unit tests, and that if you have any expensive operation, you get it at the very moment of the import.\n\nUsually, reviewing code I see members declared at class level with a bit of suspicion; there are a lot of good usecases for them, but it is also quite likely they are there as a kind of habit from previous experiences with other programming languages.\n"
] |
[
8,
6,
4,
1
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0002307590_python_syntax.txt
|
Q:
Uploading a HTML file to Google App Engine - getting 405
I'm trying to do a simple echo app using Python. I want to submit a file with a POST form and echo it back (an HTML file).
Here's the handlers section of the YAML I'm using:
handlers:
- url: /statics
static_dir: statics
- url: .*
script: main.py
It's basically the hello world example in main.py and I added a directory to host my static html form file. Here's the HTML in statics/test.html:
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="bookmarks_file">
<input type="submit" value="Upload">
</form>
The handler looks like this:
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write(self.request.get('bookmarks_file'))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
However, I'm getting an error 405 when posting the file. How come?
A:
You are submitting your form with the POST method, but you implemented a get() handler instead of a post() handler. Changing def get(self): to def post(self): should fix the HTTP 405 error.
|
Uploading a HTML file to Google App Engine - getting 405
|
I'm trying to do a simple echo app using Python. I want to submit a file with a POST form and echo it back (an HTML file).
Here's the handlers section of the YAML I'm using:
handlers:
- url: /statics
static_dir: statics
- url: .*
script: main.py
It's basically the hello world example in main.py and I added a directory to host my static html form file. Here's the HTML in statics/test.html:
<form action="/" enctype="multipart/form-data" method="post">
<input type="file" name="bookmarks_file">
<input type="submit" value="Upload">
</form>
The handler looks like this:
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write(self.request.get('bookmarks_file'))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
However, I'm getting an error 405 when posting the file. How come?
|
[
"You are submitting your form with the POST method, but you implemented a get() handler instead of a post() handler. Changing def get(self): to def post(self): should fix the HTTP 405 error.\n"
] |
[
8
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002307645_google_app_engine_python.txt
|
Q:
Integrating pygame with a C module
In my Python2_6/include directory is a folder with pygame headers. I assumed that my python C module can access pygame stuff directly in C. Is this the case? How do I integrate a C module that wants to use pygame, with a python script using pygame? Right now my brain sees:
pygame <-- MyCModule <-- MyScript --> pygame
ie. Two pygame instances. So is it possible to integrate them so that my module and my app use the same instance? Why are there pygame headers in my python include directory, can I use those somehow, for direct access?
Thanks for any help.
A:
I assumed that my python C module can
access pygame stuff directly in C. Is
this the case?
No, that stuff is most likely just there because it was necessary to compile the pygame Python extension.
I don't understand what you mean when you say you see 2 pygame instances. There are as many instances as you create, no more, no less. If you have script that creates pygame objects, and your extension also creates pygame objects, then of course you will have 2 sets of objects. As the writer of the application you need to decide which part of it will have responsibility for interfacing with pygame. If the other part requires access to those pygame objects, then you pass them in as arguments.
A:
See this question. The code given in the accepted answer checks whether Pygame was already loaded, so you won't end up with two sets of Pygame stuff.
Also, those headers aren't for custom C modules. They're probably required for some SDL stuff.
|
Integrating pygame with a C module
|
In my Python2_6/include directory is a folder with pygame headers. I assumed that my python C module can access pygame stuff directly in C. Is this the case? How do I integrate a C module that wants to use pygame, with a python script using pygame? Right now my brain sees:
pygame <-- MyCModule <-- MyScript --> pygame
ie. Two pygame instances. So is it possible to integrate them so that my module and my app use the same instance? Why are there pygame headers in my python include directory, can I use those somehow, for direct access?
Thanks for any help.
|
[
"\nI assumed that my python C module can\n access pygame stuff directly in C. Is\n this the case?\n\nNo, that stuff is most likely just there because it was necessary to compile the pygame Python extension.\nI don't understand what you mean when you say you see 2 pygame instances. There are as many instances as you create, no more, no less. If you have script that creates pygame objects, and your extension also creates pygame objects, then of course you will have 2 sets of objects. As the writer of the application you need to decide which part of it will have responsibility for interfacing with pygame. If the other part requires access to those pygame objects, then you pass them in as arguments.\n",
"See this question. The code given in the accepted answer checks whether Pygame was already loaded, so you won't end up with two sets of Pygame stuff.\nAlso, those headers aren't for custom C modules. They're probably required for some SDL stuff.\n"
] |
[
0,
0
] |
[] |
[] |
[
"module",
"pygame",
"python"
] |
stackoverflow_0002171746_module_pygame_python.txt
|
Q:
Python equivalent to Java's JNLP Web Start?
Is there any way to achieve the same functionality in Python, i.e., launching a script from a browser and automatically updating it from a central server location?
A:
Run your app on Jython and use Java Web Start?
From a comment below, http://blog.pyproject.ninja/posts/2016-03-31-web-start-on-jython.html, provides a complete example.
Note that Jython is not Python- some stuff does not work, and notably Jython is only Python-2.7 compatible.
A:
Well this is still not a full match of the features of JNLP but maybe esky is closer to what you want. It's not browser based but once your app is installed on the client it can update itself. It might also lack something in the cross-platform department so depending on your environment YMMV.
Another alternative might be the Dabo framework at dabodev.com. It's been a few years since i looked at that but it still looks like it's alive :-)
A:
You may be able to achieve some functionality with Skulpt although it uses classless python, so its functionality is rather limited.
Well check out this python wiki page as it lays out various options.
|
Python equivalent to Java's JNLP Web Start?
|
Is there any way to achieve the same functionality in Python, i.e., launching a script from a browser and automatically updating it from a central server location?
|
[
"Run your app on Jython and use Java Web Start?\nFrom a comment below, http://blog.pyproject.ninja/posts/2016-03-31-web-start-on-jython.html, provides a complete example.\nNote that Jython is not Python- some stuff does not work, and notably Jython is only Python-2.7 compatible.\n",
"Well this is still not a full match of the features of JNLP but maybe esky is closer to what you want. It's not browser based but once your app is installed on the client it can update itself. It might also lack something in the cross-platform department so depending on your environment YMMV.\nAnother alternative might be the Dabo framework at dabodev.com. It's been a few years since i looked at that but it still looks like it's alive :-)\n",
"You may be able to achieve some functionality with Skulpt although it uses classless python, so its functionality is rather limited.\nWell check out this python wiki page as it lays out various options.\n"
] |
[
8,
2,
1
] |
[] |
[] |
[
"jnlp",
"python"
] |
stackoverflow_0002248921_jnlp_python.txt
|
Q:
Encoding detection library in python
This is somehow related to my question here.
I process tons of texts (in HTML and XML mainly) fetched via HTTP. I'm looking for a library in python that can do smart encoding detection based on different strategies and convert texts to unicode using best possible character encoding guess.
I found that chardet does auto-detection extremely well. However auto-detecting everything is the problem because it is SLOW and very much against all standards. As per chardet FAQ I don't want to screw the standards.
From the same FAQ here is the list of places where I want to look for encoding:
charset parameter in HTTP Content-type header.
<meta http-equiv="content-type"> element in
the <head> of a web page for HTML
documents.
encoding attribute in the XML prolog for XML
documents.
Auto-detect the character encoding as a last resort.
Basically I want to be able to look in all those place and also deal with conflicting information automatically.
Is there such library out there or do I need to write it myself?
A:
BeautifulSoup's UnicodeDammit, which in turn uses chardet.
chardet by itself is quite useful for the general case (determining text's encoding) but slow as you say. UnicodeDammit adds extra features on top of chardet, in particular that it can look up the encoding explicitly specified in XML's encoding tags.
As for the HTTP Content-type header, I think you need to read that yourself to extract the charset parameter, and then pass it to UnicodeDammit in the fromEncoding parameter.
As for resolving conflicts, UnicodeDammit will give precedence to explicitly-stated encoding (if the encoding doesn't generate errors). See the docs for full details.
A:
BeautifulSoup (the html parser) incorporates a class called UnicodeDammit that does just that. Have a look and see if you like it.
|
Encoding detection library in python
|
This is somehow related to my question here.
I process tons of texts (in HTML and XML mainly) fetched via HTTP. I'm looking for a library in python that can do smart encoding detection based on different strategies and convert texts to unicode using best possible character encoding guess.
I found that chardet does auto-detection extremely well. However auto-detecting everything is the problem because it is SLOW and very much against all standards. As per chardet FAQ I don't want to screw the standards.
From the same FAQ here is the list of places where I want to look for encoding:
charset parameter in HTTP Content-type header.
<meta http-equiv="content-type"> element in
the <head> of a web page for HTML
documents.
encoding attribute in the XML prolog for XML
documents.
Auto-detect the character encoding as a last resort.
Basically I want to be able to look in all those place and also deal with conflicting information automatically.
Is there such library out there or do I need to write it myself?
|
[
"BeautifulSoup's UnicodeDammit, which in turn uses chardet.\nchardet by itself is quite useful for the general case (determining text's encoding) but slow as you say. UnicodeDammit adds extra features on top of chardet, in particular that it can look up the encoding explicitly specified in XML's encoding tags.\nAs for the HTTP Content-type header, I think you need to read that yourself to extract the charset parameter, and then pass it to UnicodeDammit in the fromEncoding parameter.\nAs for resolving conflicts, UnicodeDammit will give precedence to explicitly-stated encoding (if the encoding doesn't generate errors). See the docs for full details.\n",
"BeautifulSoup (the html parser) incorporates a class called UnicodeDammit that does just that. Have a look and see if you like it. \n"
] |
[
10,
3
] |
[] |
[] |
[
"character_encoding",
"html",
"http",
"python",
"xml"
] |
stackoverflow_0002307795_character_encoding_html_http_python_xml.txt
|
Q:
How to find out the summarized text of a given URL in python / Django?
How to find out the summarized text for a given URL?
What do i mean by summarized text?
Merck $41.1 Billion Schering-Plough Bid Seeks Science
Link Descrption
Merck & Co.’s $41.1 billion purchase of Schering-Plough Corp. adds experimental drugs for blood clots, infections and schizophrenia and allows the companies to speed research on biotechnology drugs.
For the above URL the below three lines is the summary text.
A short 2 to 3 line description of the URL which we usually obtain by fetching that page , examining the content thereafter figuring out short description from that html markup.
Are there any good algorithm which does this? (or)
Are there any good libraries in python/django which does this?
A:
I had the same need, and lemur, although it has summarization capabilities, I found it buggy to the point of being unusable. Over the weekend I used nltk to code up a summarize module in python: https://github.com/thavelick/summarize
I took the algorithm from the Java library Classifier4J here: http://classifier4j.sourceforge.net/ but used nltk and a python wherever possible.
Here is the basic usage:
>>> import summarize
A SimpleSummarizer (currently the only summarizer) makes a summary by using sentences with the most frequent words:
>>> ss = summarize.SimpleSummarizer()
>>> input = "NLTK is a python library for working human-written text. Summarize is a package that uses NLTK to create summaries."
>>> ss.summarize(input, 1)
'NLTK is a python library for working human-written text.'
You can specify any number of sentenecs in the summary as you like.
>>> input = "NLTK is a python library for working human-written text. Summarize is a package that uses NLTK to create summaries. A Summariser is really cool. I don't think there are any other python summarisers."
>>> ss.summarize(input, 2)
"NLTK is a python library for working human-written text. I don't think there are any other python summarisers."
Unlike the original algorithm from Classifier4J, this summarizer works
correctly with punctuation other than periods:
>>> input = "NLTK is a python library for working human-written text! Summarize is a package that uses NLTK to create summaries."
>>> ss.summarize(input, 1)
'NLTK is a python library for working human-written text!'
UPDATE
I've now (finally!) released this under the Apache 2.0 license, the same license as nltk, and put the module up on github (see above). Any contributions or suggestions are welcome.
A:
Text summarization is a fairly complicated topic. If you have a need to do this in a serious way, you may wish to look at projects like Lemur (http://www.lemurproject.org/).
However, what I suspect you really want is a text abstract here. If you know what part of the document contains the body text, locate it using an HTML parsing library like BeautifulSoup, and then strip out the HTML; take the first sentence, or first N characters (which ever suits best), and use that. Sort of a poor cousin's abstract-generator :-)
A:
Check out the Natural Language Toolkit. Its a very useful python library if you're doing any text-processing.
Then look at this paper by HP Luhn (1958). It describes a naive but effective method of generating summaries of text.
Use the nltk.probability.FreqDist object to track how often words appear in text and then score sentences according to how many of the most frequent words appear in them. Then select the sentences with the best scores and voila, you have a summary of the document.
I suspect the NLTK should have a means of loading documents from the web and getting all of the HTML tags out of the way. I haven't done that kind of thing myself, but if you look up the corpus readers you might find something helpful.
|
How to find out the summarized text of a given URL in python / Django?
|
How to find out the summarized text for a given URL?
What do i mean by summarized text?
Merck $41.1 Billion Schering-Plough Bid Seeks Science
Link Descrption
Merck & Co.’s $41.1 billion purchase of Schering-Plough Corp. adds experimental drugs for blood clots, infections and schizophrenia and allows the companies to speed research on biotechnology drugs.
For the above URL the below three lines is the summary text.
A short 2 to 3 line description of the URL which we usually obtain by fetching that page , examining the content thereafter figuring out short description from that html markup.
Are there any good algorithm which does this? (or)
Are there any good libraries in python/django which does this?
|
[
"I had the same need, and lemur, although it has summarization capabilities, I found it buggy to the point of being unusable. Over the weekend I used nltk to code up a summarize module in python: https://github.com/thavelick/summarize\nI took the algorithm from the Java library Classifier4J here: http://classifier4j.sourceforge.net/ but used nltk and a python wherever possible.\nHere is the basic usage:\n>>> import summarize\n\nA SimpleSummarizer (currently the only summarizer) makes a summary by using sentences with the most frequent words:\n>>> ss = summarize.SimpleSummarizer()\n>>> input = \"NLTK is a python library for working human-written text. Summarize is a package that uses NLTK to create summaries.\"\n>>> ss.summarize(input, 1)\n'NLTK is a python library for working human-written text.'\n\nYou can specify any number of sentenecs in the summary as you like.\n>>> input = \"NLTK is a python library for working human-written text. Summarize is a package that uses NLTK to create summaries. A Summariser is really cool. I don't think there are any other python summarisers.\"\n>>> ss.summarize(input, 2)\n\"NLTK is a python library for working human-written text. I don't think there are any other python summarisers.\"\n\nUnlike the original algorithm from Classifier4J, this summarizer works\ncorrectly with punctuation other than periods:\n>>> input = \"NLTK is a python library for working human-written text! Summarize is a package that uses NLTK to create summaries.\"\n>>> ss.summarize(input, 1)\n'NLTK is a python library for working human-written text!'\n\nUPDATE\nI've now (finally!) released this under the Apache 2.0 license, the same license as nltk, and put the module up on github (see above). Any contributions or suggestions are welcome.\n",
"Text summarization is a fairly complicated topic. If you have a need to do this in a serious way, you may wish to look at projects like Lemur (http://www.lemurproject.org/).\nHowever, what I suspect you really want is a text abstract here. If you know what part of the document contains the body text, locate it using an HTML parsing library like BeautifulSoup, and then strip out the HTML; take the first sentence, or first N characters (which ever suits best), and use that. Sort of a poor cousin's abstract-generator :-)\n",
"Check out the Natural Language Toolkit. Its a very useful python library if you're doing any text-processing.\nThen look at this paper by HP Luhn (1958). It describes a naive but effective method of generating summaries of text.\nUse the nltk.probability.FreqDist object to track how often words appear in text and then score sentences according to how many of the most frequent words appear in them. Then select the sentences with the best scores and voila, you have a summary of the document.\nI suspect the NLTK should have a means of loading documents from the web and getting all of the HTML tags out of the way. I haven't done that kind of thing myself, but if you look up the corpus readers you might find something helpful.\n"
] |
[
22,
4,
4
] |
[
"Your best bet in this case would be to use a HTML parsing library like BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/)\nFrom there, you can fetch for example, all the pages p tags:\n\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\npage = urllib2.urlopen(\"http://www.bloomberg.com/apps/newspid=20601103&sid=a8p0FQHnw.Yo&refer=us\")\nsoup = BeautifulSoup(page)\nsoup.findAll('p')\n\nAnd then, do some parsing around. It depends entirely on the page, as every site is structured differently. You can get lucky on some sites as they may do and you simply look for a p tag with the id#summary in it, while others (like Blooberg) might require a bit more playing around with.\n"
] |
[
-4
] |
[
"django",
"python"
] |
stackoverflow_0000626754_django_python.txt
|
Q:
Variable Files with Python
I am trying to have a file path like 'C:\Programfiles\file.txt' but i would like to have file.txt be a variable that i can change whenever i need to. I am trying to compare 2 directories then copy files from one to another if they arent already there. i have this code so far.
import os
import shutil
A= set(os.listdir(r"C:\Users\Morpheous\Desktop\Python Test"))
B= set(os.listdir(r"C:\Users\Morpheous\Desktop\Python Test 2"))
if len(A)< len(B):
C=B-A
print("File is: %s" %(C))
shutil.copy2('C:\\Users\\Morpheous\\Desktop\\Python Test 2\\%r'%(C),'C:\\Users\\Morpheous\\Desktop\\Python Test')
elif len(A) > len(B):
C=B-A
print(C)
and i get an error because the variable is inserted into path with {''} around it. How would i go about doing this?
A:
Please use os.path.join to construct paths. Also, you should put the directories in variables for reuse. Furthermore you need to iterate over the difference between the folders (B - A) in order to get each filename that's in the difference set (C is the set of files that have been added!).
Here's the corrected version - tested and working:
import os
import shutil
pathA = r"C:\Users\Morpheous\Desktop\Python Test"
pathB = r"C:\Users\Morpheous\Desktop\Python Test 2"
A = set(os.listdir(pathA))
B = set(os.listdir(pathB))
C = B - A
if len(C):
print("Difference is: %s" % repr(C))
for addedFile in C:
shutil.copy2(os.path.join(pathB, addedFile),
os.path.join(pathA, addedFile))
else:
print("No new files")
A:
you should use a library like filecmp to compare directories/files
>>> import filecmp
>>> import os
>>> dira = os.path.join("/home","dir1")
>>> dirb = os.path.join("/home","dir2")
>>> os.listdir(dira)
['file.jpg', 'file2.txt']
>>> os.listdir(dirb)
['file1.jpg', 'file2.txt']
>>> r=filecmp.dircmp(a,b)
>>> r.right_only # only in dirb
['file1.jpg']
>>> r.left_only # only in dira
['file.jpg']
A:
Use %s instead of %r, and C.pop().replace(' ', '\\ ') instead of C, which is a set and not a string (the replace is needed to "escape" every space -- I think). Last but not least, I think you're using shutil.copy2 wrong: see the docs -- it wants two arguments, not one argument with a space separator.
There may well be other bugs lurking in your code (I'm not sure what that 2\\ part is supposed to mean, for example; and you may need a loop, as copy2 does one file at a time and you may have serveral; etc, etc), but these at least are definitely there.
|
Variable Files with Python
|
I am trying to have a file path like 'C:\Programfiles\file.txt' but i would like to have file.txt be a variable that i can change whenever i need to. I am trying to compare 2 directories then copy files from one to another if they arent already there. i have this code so far.
import os
import shutil
A= set(os.listdir(r"C:\Users\Morpheous\Desktop\Python Test"))
B= set(os.listdir(r"C:\Users\Morpheous\Desktop\Python Test 2"))
if len(A)< len(B):
C=B-A
print("File is: %s" %(C))
shutil.copy2('C:\\Users\\Morpheous\\Desktop\\Python Test 2\\%r'%(C),'C:\\Users\\Morpheous\\Desktop\\Python Test')
elif len(A) > len(B):
C=B-A
print(C)
and i get an error because the variable is inserted into path with {''} around it. How would i go about doing this?
|
[
"Please use os.path.join to construct paths. Also, you should put the directories in variables for reuse. Furthermore you need to iterate over the difference between the folders (B - A) in order to get each filename that's in the difference set (C is the set of files that have been added!).\nHere's the corrected version - tested and working:\nimport os\nimport shutil\n\npathA = r\"C:\\Users\\Morpheous\\Desktop\\Python Test\"\npathB = r\"C:\\Users\\Morpheous\\Desktop\\Python Test 2\"\n\nA = set(os.listdir(pathA))\nB = set(os.listdir(pathB))\nC = B - A\n\nif len(C):\n print(\"Difference is: %s\" % repr(C))\n\n for addedFile in C:\n shutil.copy2(os.path.join(pathB, addedFile),\n os.path.join(pathA, addedFile))\nelse:\n print(\"No new files\")\n\n",
"you should use a library like filecmp to compare directories/files\n>>> import filecmp\n>>> import os\n>>> dira = os.path.join(\"/home\",\"dir1\")\n>>> dirb = os.path.join(\"/home\",\"dir2\")\n>>> os.listdir(dira)\n['file.jpg', 'file2.txt']\n>>> os.listdir(dirb)\n['file1.jpg', 'file2.txt']\n>>> r=filecmp.dircmp(a,b)\n>>> r.right_only # only in dirb\n['file1.jpg']\n>>> r.left_only # only in dira\n['file.jpg']\n\n",
"Use %s instead of %r, and C.pop().replace(' ', '\\\\ ') instead of C, which is a set and not a string (the replace is needed to \"escape\" every space -- I think). Last but not least, I think you're using shutil.copy2 wrong: see the docs -- it wants two arguments, not one argument with a space separator.\nThere may well be other bugs lurking in your code (I'm not sure what that 2\\\\ part is supposed to mean, for example; and you may need a loop, as copy2 does one file at a time and you may have serveral; etc, etc), but these at least are definitely there.\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"file",
"python",
"python_3.x",
"variables"
] |
stackoverflow_0002306947_file_python_python_3.x_variables.txt
|
Q:
How does assignment of a function as a class attribute become a method in Python?
>>> class A(object): pass
>>> def func(cls): pass
>>> A.func = func
>>> A.func
<unbound method A.func>
How does this assignment create a method? It seems unintuitive that assignment does the following for classes:
Turn functions into unbound instance methods
Turn functions wrapped in classmethod() into class methods (actually, this is pretty intuitive)
Turn functions wrapped in staticmethod() into functions
It seems that for the first, there should be an instancemethod(), and for the last one, there shouldn't be a wrapper function at all. I understand that these are for uses within a class block, but why should they apply outside of it?
But more importantly, how exactly does assignment of the function into a class work? What magic happens that resolves those 3 things?
Even more confusing with this:
>>> A.func
<unbound method A.func>
>>> A.__dict__['func']
<function func at 0x...>
But I think this is something to do with descriptors, when retrieving attributes. I don't think it has much to do with the setting of attributes here.
A:
Descriptors are the magic1 that turns an ordinary function into a bound or unbound method when you retrieve it from an instance or class, since they’re all just functions that need different binding strategies. The classmethod and staticmethod decorators implement other binding strategies, and staticmethod actually just returns the raw function, which is the same behavior you get from a non-function callable object.
See “User-defined methods” for some gory details, but note this:
Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation.
So if you wanted this transformation for your own callable object, you could just wrap it in a function, but you could also write a descriptor to implement your own binding strategy.
Here’s the staticmethod decorator in action, returning the underlying function when it’s accessed.
>>> @staticmethod
... def f(): pass
>>> class A(object): pass
>>> A.f = f
>>> A.f
<function f at 0x100479398>
>>> f
<staticmethod object at 0x100492750>
Whereas a normal object with a __call__ method doesn’t get transformed:
>>> class C(object):
... def __call__(self): pass
>>> c = C()
>>> A.c = c
>>> A.c
<__main__.C object at 0x10048b890>
>>> c
<__main__.C object at 0x10048b890>
1 The specific function is func_descr_get in Objects/funcobject.c.
A:
You're right that this has something to do with descriptor protocol. Descriptors are how passing the receiver object as the first parameter of a method is implemented in Python. You can read more detail about Python attribute lookup from here. The following shows on a bit lower level, what is happening when you do A.func = func; A.func:
# A.func = func
A.__dict__['func'] = func # This just sets the attribute
# A.func
# The __getattribute__ method of a type object calls the __get__ method with
# None as the first parameter and the type as the second.
A.__dict__['func'].__get__(None, A) # The __get__ method of a function object
# returns an unbound method object if the
# first parameter is None.
a = A()
# a.func()
# The __getattribute__ method of object finds an attribute on the type object
# and calls the __get__ method of it with the instance as its first parameter.
a.__class__.__dict__['func'].__get__(a, a.__class__)
# This returns a bound method object that is actually just a proxy for
# inserting the object as the first parameter to the function call.
So it's the looking up of the function on a class or an instance that turns it into a method, not assigning it to a class attribute.
classmethod and staticmethod are just slightly different descriptors, classmethod returning a bound method object bound to a type object and staticmethod just returns the original function.
A:
What you have to consider is that in Python everything is an object. By establishing that it is easier to understand what is happening. If you have a function def foo(bar): print bar, you can do spam = foo and call spam(1), getting of course, 1.
Objects in Python keep their instance attributes in a dictionary called __dict__ with a "pointer" to other objects. As functions in Python are objects as well, they can be assigned and manipulated as simple variables, passed around to other functions, etc. Python's implementation of object orientation takes advantage of this, and treats methods as attributes, as functions that are in the __dict__ of the object.
Instance methods' first parameter is always the instance object itself, generally called self (but this could be called this or banana). When a method is called directly on the class, it is unbound to any instance, so you have to give it an instance object as the first parameter (A.func(A())). When you call a bound function (A().func()), the first parameter of the method, self, is implicit, but behind the curtains Python does exactly the same as calling directly on the unbound function and passing the instance object as the first parameter.
If this is understood, the fact that assigning A.func = func (which behind the curtains is doing A.__dict__["func"] = func) leaves you with an unbound method, is unsurprising.
In your example the cls in def func(cls): pass actually what will be passed on is the instance (self) of type A. When you apply the classmethod or staticmethod decorators do nothing more than take the first argument obtained during the call of the function/method, and transform it into something else, before calling the function.
classmethod takes the first argument, gets the class object of the instance, and passes that as the first argument to the function call, while staticmethod simply discards the first parameter and calls the function without it.
A:
Point 1: The function func you defined exists as a First-Class Object in Python.
Point 2: Classes in Python store their attributes in their __dict__.
So what happens when you pass a function as the value of a class attribute in Python? That function is stored in the class' __dict__, making it a method of that class accessed by calling the attribute name you assigned it to.
A:
Relating to MTsoul's comment to Gabriel Hurley's answer:
What is different is that func has a __call__() method, making it "callable", i.e. you can apply the () operator to it. Check out the Python docs (search for __call__ on that page).
|
How does assignment of a function as a class attribute become a method in Python?
|
>>> class A(object): pass
>>> def func(cls): pass
>>> A.func = func
>>> A.func
<unbound method A.func>
How does this assignment create a method? It seems unintuitive that assignment does the following for classes:
Turn functions into unbound instance methods
Turn functions wrapped in classmethod() into class methods (actually, this is pretty intuitive)
Turn functions wrapped in staticmethod() into functions
It seems that for the first, there should be an instancemethod(), and for the last one, there shouldn't be a wrapper function at all. I understand that these are for uses within a class block, but why should they apply outside of it?
But more importantly, how exactly does assignment of the function into a class work? What magic happens that resolves those 3 things?
Even more confusing with this:
>>> A.func
<unbound method A.func>
>>> A.__dict__['func']
<function func at 0x...>
But I think this is something to do with descriptors, when retrieving attributes. I don't think it has much to do with the setting of attributes here.
|
[
"Descriptors are the magic1 that turns an ordinary function into a bound or unbound method when you retrieve it from an instance or class, since they’re all just functions that need different binding strategies. The classmethod and staticmethod decorators implement other binding strategies, and staticmethod actually just returns the raw function, which is the same behavior you get from a non-function callable object. \nSee “User-defined methods” for some gory details, but note this:\n\nAlso notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation.\n\nSo if you wanted this transformation for your own callable object, you could just wrap it in a function, but you could also write a descriptor to implement your own binding strategy.\nHere’s the staticmethod decorator in action, returning the underlying function when it’s accessed.\n>>> @staticmethod\n... def f(): pass\n>>> class A(object): pass\n>>> A.f = f\n>>> A.f\n<function f at 0x100479398>\n>>> f\n<staticmethod object at 0x100492750>\n\nWhereas a normal object with a __call__ method doesn’t get transformed:\n>>> class C(object):\n... def __call__(self): pass\n>>> c = C() \n>>> A.c = c \n>>> A.c\n<__main__.C object at 0x10048b890>\n>>> c\n<__main__.C object at 0x10048b890>\n\n1 The specific function is func_descr_get in Objects/funcobject.c.\n",
"You're right that this has something to do with descriptor protocol. Descriptors are how passing the receiver object as the first parameter of a method is implemented in Python. You can read more detail about Python attribute lookup from here. The following shows on a bit lower level, what is happening when you do A.func = func; A.func:\n# A.func = func\nA.__dict__['func'] = func # This just sets the attribute\n# A.func\n# The __getattribute__ method of a type object calls the __get__ method with\n# None as the first parameter and the type as the second.\nA.__dict__['func'].__get__(None, A) # The __get__ method of a function object\n # returns an unbound method object if the\n # first parameter is None.\na = A()\n# a.func()\n# The __getattribute__ method of object finds an attribute on the type object\n# and calls the __get__ method of it with the instance as its first parameter.\na.__class__.__dict__['func'].__get__(a, a.__class__)\n# This returns a bound method object that is actually just a proxy for\n# inserting the object as the first parameter to the function call.\n\nSo it's the looking up of the function on a class or an instance that turns it into a method, not assigning it to a class attribute.\nclassmethod and staticmethod are just slightly different descriptors, classmethod returning a bound method object bound to a type object and staticmethod just returns the original function.\n",
"What you have to consider is that in Python everything is an object. By establishing that it is easier to understand what is happening. If you have a function def foo(bar): print bar, you can do spam = foo and call spam(1), getting of course, 1.\nObjects in Python keep their instance attributes in a dictionary called __dict__ with a \"pointer\" to other objects. As functions in Python are objects as well, they can be assigned and manipulated as simple variables, passed around to other functions, etc. Python's implementation of object orientation takes advantage of this, and treats methods as attributes, as functions that are in the __dict__ of the object.\nInstance methods' first parameter is always the instance object itself, generally called self (but this could be called this or banana). When a method is called directly on the class, it is unbound to any instance, so you have to give it an instance object as the first parameter (A.func(A())). When you call a bound function (A().func()), the first parameter of the method, self, is implicit, but behind the curtains Python does exactly the same as calling directly on the unbound function and passing the instance object as the first parameter.\nIf this is understood, the fact that assigning A.func = func (which behind the curtains is doing A.__dict__[\"func\"] = func) leaves you with an unbound method, is unsurprising.\nIn your example the cls in def func(cls): pass actually what will be passed on is the instance (self) of type A. When you apply the classmethod or staticmethod decorators do nothing more than take the first argument obtained during the call of the function/method, and transform it into something else, before calling the function.\nclassmethod takes the first argument, gets the class object of the instance, and passes that as the first argument to the function call, while staticmethod simply discards the first parameter and calls the function without it.\n",
"Point 1: The function func you defined exists as a First-Class Object in Python.\nPoint 2: Classes in Python store their attributes in their __dict__.\nSo what happens when you pass a function as the value of a class attribute in Python? That function is stored in the class' __dict__, making it a method of that class accessed by calling the attribute name you assigned it to.\n",
"Relating to MTsoul's comment to Gabriel Hurley's answer:\nWhat is different is that func has a __call__() method, making it \"callable\", i.e. you can apply the () operator to it. Check out the Python docs (search for __call__ on that page).\n"
] |
[
4,
4,
3,
0,
0
] |
[] |
[] |
[
"class_method",
"python"
] |
stackoverflow_0002307653_class_method_python.txt
|
Q:
Python - Spaces in Filenames
Possible Duplicate:
How to escape os.system() calls in Python?
Is there a Python method of making filenames safe (ie. putting \ infront of spaces and escaping ( , ), symbols) programatically in Python?
A:
Spaces are already "safe" for Python in open(). As for os.system() and similar functions, use subprocess instead.
A:
>>> import pipes
>>> pipes.quote("\&*!")
"'\\&*!'"
|
Python - Spaces in Filenames
|
Possible Duplicate:
How to escape os.system() calls in Python?
Is there a Python method of making filenames safe (ie. putting \ infront of spaces and escaping ( , ), symbols) programatically in Python?
|
[
"Spaces are already \"safe\" for Python in open(). As for os.system() and similar functions, use subprocess instead.\n",
">>> import pipes\n>>> pipes.quote(\"\\&*!\")\n\"'\\\\&*!'\"\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"file_io",
"linux",
"module",
"python"
] |
stackoverflow_0002308394_file_io_linux_module_python.txt
|
Q:
How to convert a numeric string with place-value commas into an integer?
In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?
A:
It really depends where you get your number from.
If the number you are trying to convert comes from user input, use locale.atoi(). That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.
If on the other hand you read it, let's say, from a file, that always uses the same format, use int("1,234".replace(",", "")) or int("1.234".replace(".", "")) depending on your situation. This is not only easier to read and debug, but it's not affected by the user's locale setting, so your parser will work on any system.
A:
locale.atoi(), after setting an appropriate locale.
A:
>>> s="1,374"
>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, '')
'en_US.UTF-8'
>>> locale.atoi(s)
1374
A:
int("1,374".replace(",",""))
|
How to convert a numeric string with place-value commas into an integer?
|
In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?
|
[
"It really depends where you get your number from.\nIf the number you are trying to convert comes from user input, use locale.atoi(). That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.\nIf on the other hand you read it, let's say, from a file, that always uses the same format, use int(\"1,234\".replace(\",\", \"\")) or int(\"1.234\".replace(\".\", \"\")) depending on your situation. This is not only easier to read and debug, but it's not affected by the user's locale setting, so your parser will work on any system.\n",
"locale.atoi(), after setting an appropriate locale.\n",
">>> s=\"1,374\"\n>>> import locale\n>>> locale.setlocale(locale.LC_NUMERIC, '')\n'en_US.UTF-8'\n>>> locale.atoi(s)\n1374\n\n",
"int(\"1,374\".replace(\",\",\"\"))\n\n"
] |
[
9,
4,
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002308443_python.txt
|
Q:
How can I have an encrypted input in Python?
I am writing a Python program that requires a user to input their gmail usernames and passwords. When the user types in their password, I want the characters to be displayed as asterisks. Is this possible for a command-line program?
A:
getpass.getpass() doesn't show asterisks but instead suppresses all output, which is expected behavior on some systems.
|
How can I have an encrypted input in Python?
|
I am writing a Python program that requires a user to input their gmail usernames and passwords. When the user types in their password, I want the characters to be displayed as asterisks. Is this possible for a command-line program?
|
[
"getpass.getpass() doesn't show asterisks but instead suppresses all output, which is expected behavior on some systems.\n"
] |
[
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002308536_python.txt
|
Q:
Pass array of structs from Python to C
[Update: Problem solved! See bottom of the post]
I need to allow python developers to pass an array of packed data (in this case vertices) into my API, which is a series of C++ interfaces exposed manually through the Python C API. My initial impression with this is to use the ctypes Structure class to allow for an interface like this:
class Vertex(Structure):
_fields_ = [
('x', c_float),
('y', c_float),
('z', c_float),
('u', c_float),
('v', c_float),
('color', c_int)
]
verts = (Vertex * 3)()
verts[0] = Vertex(0.0, 0.5, 0.0, 0.0, 0.5, 0xFF0000FF)
verts[1] = Vertex(0.5, -0.5, 0.0, 0.5, -0.5, 0x00FF00FF)
verts[2] = Vertex(-0.5, -0.5, 0.0, -0.5, -0.5, 0x0000FFFF)
device.ReadVertices(verts, 3) # This is the interfaces to the C++ object
Where the function I'm trying to pass to has the following signature:
void Device::ReadVertices(Vertex* verts, int count);
And the Python wrapper looks something like this:
static PyObject* Device_ReadVertices(Py_Device* self, PyObject* args)
{
PyObject* py_verts;
int count;
if(!PyArg_ParseTuple(args, "Oi", &py_verts, &count))
return NULL;
// This Doesn't Work!
Vertex* verts = static_cast<Vertex*>(PyCObject_AsVoidPtr(py_verts));
self->device->ReadVertices(verts, count);
Py_RETURN_NONE;
}
Of course, the biggest issue I have is this: I can retrieve the PyObject for the struct, but I have no idea how I would cast it to the correct type. The above code fails miserably. So how exactly would I go about allowing the user to pass me this kind of data from Python?
Now, a couple of things to consider: First is that I already have quite a bit of my Python/C++ layer written, and am perfectly happy with it (I moved away from SWIG so I could have more flexibility). I don't want to re-code it, so I would prefer a solution that works with the C API natively. Second, I do intend to have the Vertex structure be pre-defined in my C++ code, so I would prefer to not have the user need to re-define it in the Python (cuts down on errors that way), but I'm not sure how to expose a contiguous structure like that. Third, I have no reason for trying the ctypes structure aside from not knowing another way to do it. Any suggestions are welcome. Finally, since this is (as you may have guessed) for a graphics app I would prefer a faster method over a convenient one, even if the faster method takes a little bit more work.
Thanks for any help! I'm still feeling my way around python extensions, so it's a great help to get community input on some of the stickier parts.
[SOLUTION]
So first off, thanks to everyone who pitched in their ideas. It was a lot of little tidbits that added up to the eventual answer. In the end here is what I found: Sam's suggestion of using struct.pack ended up being right on the money. Seeing that I'm using Python 3, I had to tweak it ever so slightly, but when all was said and done this actually got a triangle showing up on my screen:
verts = bytes()
verts += struct.pack("fffffI", 0.0, 0.5, 0.0, 0.0, 0.5, 0xFF0000FF)
verts += struct.pack("fffffI", 0.5, -0.5, 0.0, 0.5, -0.5, 0x00FF00FF)
verts += struct.pack("fffffI", -0.5, -0.5, 0.0, -0.5, -0.5, 0x0000FFFF)
device.ReadVertices(verts, 3)
With my tuple parsing now looking like this:
static PyObject* Device_ReadVertices(Py_Device* self, PyObject* args)
{
void* py_verts;
int len, count;
if(!PyArg_ParseTuple(args, "y#i", &py_verts, &len, &count))
return NULL;
// Works now!
Vertex* verts = static_cast<Vertex*>(py_verts);
self->device->ReadVertices(verts, count);
Py_RETURN_NONE;
}
Note that even though I don't use the len variable in this example (though I will in the final product) I need to parse the tuple using 'y#' instead of just 'y' or else it will stop at the first NULL (according to the documentation). Also to be considered: void* casts like this are quite dangerous, so please do loads more error checking than I show here!
So, job well done, happy day, pack up and go home, yes?
Wait! Not so fast! There's MORE!
Feeling good about how that all worked out I decided, on a whim, to see if my previous attempt still blew up on me and reverted back to the first snippet of python in this post. (Using the new C code, of course) and... it worked! The results were identical to the struct.pack version! Wow!
So this means your users have a choice in how they're going to provide this kind of data, and your code can handle either with no changes. Personally I'm going to encourage the ctype.Structure method, since I think it makes for easier readability, but really it's whatever the user is comfortable with. (Heck, they could manually type out a string of bytes in hex if they wanted to. It works. I tried.)
Honestly I think this is the best possible outcome, so I'm ecstatic. Thank you all again, and good luck to anyone else who runs into this problem!
A:
Not tested but you should give this a try and let us know if its fast enough for your needs.
On the python side, pack the vertices into a string instead of an object.
str = "" # byte stream for encoding data
str += struct.pack("5f i", vert1.x, vert1.y, vert1.z, vert1.u, vert1.v, vert1.color) # 5 floats and an int
# same for other vertices
device. ReadVertices( verts, 3) # send vertices to C library
On the C library/python wrapper, modify your PyArgs_ParseTuple to use the format string "si". This will convert your python string into a C string (char*) which you can then typecast as a pointer to your vector struct. At this point the C string is a stream of bytes/words/floats and should be what you're looking for.
Good luck!
A:
The easiest thing I can see to do would be to just avoid the issue altogether and expose a Device_ReadVertex that takes in x, y, z, u, v and color as arguments. This has obvious drawbacks, like making the Python programmers feed it vertices one by one.
If that's not good enough (seems likely it isn't), then you could try defining a new Python type as described here. It's a bit more code but I think this is the "more architecturally sound" method, because you ensure your Python developers are using the same type definition as you are in the C code. It also allows for a bit more flexibility than a simple struct (it's really a class, with the potential to add methods, etc), which I'm not sure you actually need but it might come in handy later.
|
Pass array of structs from Python to C
|
[Update: Problem solved! See bottom of the post]
I need to allow python developers to pass an array of packed data (in this case vertices) into my API, which is a series of C++ interfaces exposed manually through the Python C API. My initial impression with this is to use the ctypes Structure class to allow for an interface like this:
class Vertex(Structure):
_fields_ = [
('x', c_float),
('y', c_float),
('z', c_float),
('u', c_float),
('v', c_float),
('color', c_int)
]
verts = (Vertex * 3)()
verts[0] = Vertex(0.0, 0.5, 0.0, 0.0, 0.5, 0xFF0000FF)
verts[1] = Vertex(0.5, -0.5, 0.0, 0.5, -0.5, 0x00FF00FF)
verts[2] = Vertex(-0.5, -0.5, 0.0, -0.5, -0.5, 0x0000FFFF)
device.ReadVertices(verts, 3) # This is the interfaces to the C++ object
Where the function I'm trying to pass to has the following signature:
void Device::ReadVertices(Vertex* verts, int count);
And the Python wrapper looks something like this:
static PyObject* Device_ReadVertices(Py_Device* self, PyObject* args)
{
PyObject* py_verts;
int count;
if(!PyArg_ParseTuple(args, "Oi", &py_verts, &count))
return NULL;
// This Doesn't Work!
Vertex* verts = static_cast<Vertex*>(PyCObject_AsVoidPtr(py_verts));
self->device->ReadVertices(verts, count);
Py_RETURN_NONE;
}
Of course, the biggest issue I have is this: I can retrieve the PyObject for the struct, but I have no idea how I would cast it to the correct type. The above code fails miserably. So how exactly would I go about allowing the user to pass me this kind of data from Python?
Now, a couple of things to consider: First is that I already have quite a bit of my Python/C++ layer written, and am perfectly happy with it (I moved away from SWIG so I could have more flexibility). I don't want to re-code it, so I would prefer a solution that works with the C API natively. Second, I do intend to have the Vertex structure be pre-defined in my C++ code, so I would prefer to not have the user need to re-define it in the Python (cuts down on errors that way), but I'm not sure how to expose a contiguous structure like that. Third, I have no reason for trying the ctypes structure aside from not knowing another way to do it. Any suggestions are welcome. Finally, since this is (as you may have guessed) for a graphics app I would prefer a faster method over a convenient one, even if the faster method takes a little bit more work.
Thanks for any help! I'm still feeling my way around python extensions, so it's a great help to get community input on some of the stickier parts.
[SOLUTION]
So first off, thanks to everyone who pitched in their ideas. It was a lot of little tidbits that added up to the eventual answer. In the end here is what I found: Sam's suggestion of using struct.pack ended up being right on the money. Seeing that I'm using Python 3, I had to tweak it ever so slightly, but when all was said and done this actually got a triangle showing up on my screen:
verts = bytes()
verts += struct.pack("fffffI", 0.0, 0.5, 0.0, 0.0, 0.5, 0xFF0000FF)
verts += struct.pack("fffffI", 0.5, -0.5, 0.0, 0.5, -0.5, 0x00FF00FF)
verts += struct.pack("fffffI", -0.5, -0.5, 0.0, -0.5, -0.5, 0x0000FFFF)
device.ReadVertices(verts, 3)
With my tuple parsing now looking like this:
static PyObject* Device_ReadVertices(Py_Device* self, PyObject* args)
{
void* py_verts;
int len, count;
if(!PyArg_ParseTuple(args, "y#i", &py_verts, &len, &count))
return NULL;
// Works now!
Vertex* verts = static_cast<Vertex*>(py_verts);
self->device->ReadVertices(verts, count);
Py_RETURN_NONE;
}
Note that even though I don't use the len variable in this example (though I will in the final product) I need to parse the tuple using 'y#' instead of just 'y' or else it will stop at the first NULL (according to the documentation). Also to be considered: void* casts like this are quite dangerous, so please do loads more error checking than I show here!
So, job well done, happy day, pack up and go home, yes?
Wait! Not so fast! There's MORE!
Feeling good about how that all worked out I decided, on a whim, to see if my previous attempt still blew up on me and reverted back to the first snippet of python in this post. (Using the new C code, of course) and... it worked! The results were identical to the struct.pack version! Wow!
So this means your users have a choice in how they're going to provide this kind of data, and your code can handle either with no changes. Personally I'm going to encourage the ctype.Structure method, since I think it makes for easier readability, but really it's whatever the user is comfortable with. (Heck, they could manually type out a string of bytes in hex if they wanted to. It works. I tried.)
Honestly I think this is the best possible outcome, so I'm ecstatic. Thank you all again, and good luck to anyone else who runs into this problem!
|
[
"Not tested but you should give this a try and let us know if its fast enough for your needs.\nOn the python side, pack the vertices into a string instead of an object.\nstr = \"\" # byte stream for encoding data\nstr += struct.pack(\"5f i\", vert1.x, vert1.y, vert1.z, vert1.u, vert1.v, vert1.color) # 5 floats and an int\n# same for other vertices\n\ndevice. ReadVertices( verts, 3) # send vertices to C library\nOn the C library/python wrapper, modify your PyArgs_ParseTuple to use the format string \"si\". This will convert your python string into a C string (char*) which you can then typecast as a pointer to your vector struct. At this point the C string is a stream of bytes/words/floats and should be what you're looking for.\nGood luck!\n",
"The easiest thing I can see to do would be to just avoid the issue altogether and expose a Device_ReadVertex that takes in x, y, z, u, v and color as arguments. This has obvious drawbacks, like making the Python programmers feed it vertices one by one.\nIf that's not good enough (seems likely it isn't), then you could try defining a new Python type as described here. It's a bit more code but I think this is the \"more architecturally sound\" method, because you ensure your Python developers are using the same type definition as you are in the C code. It also allows for a bit more flexibility than a simple struct (it's really a class, with the potential to add methods, etc), which I'm not sure you actually need but it might come in handy later.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"python_3.x",
"python_c_api",
"structure"
] |
stackoverflow_0002307290_python_python_3.x_python_c_api_structure.txt
|
Q:
why class creation throws error
Just playin around class
def func(*args, **kwargs):
print args, kwargs
class Klass(func): pass
it throws error
TypeError: Error when calling the
metaclass bases
function() argument 1 must be code, not str
What does it mean, i am passing no str nowhere?
and yes I should be passing class in bases but why didn't error say that, instead of this cryptic error?
A:
see here for the reason for the cryptic msg
http://bugs.python.org/issue6829
questions Error when calling the metaclass bases: function() argument 1 must be code, not str has same problem.
Edit: play-around
Though you can use metaclass to make it work in a twisted way ;)
def func(name, klassDict):
return type(name, (), klassDict)
class MyMeta(type):
def __new__(self, name, bases, klassDict):
return bases[0](name, klassDict)
class Klass(func):
__metaclass__ = MyMeta
print Klass
|
why class creation throws error
|
Just playin around class
def func(*args, **kwargs):
print args, kwargs
class Klass(func): pass
it throws error
TypeError: Error when calling the
metaclass bases
function() argument 1 must be code, not str
What does it mean, i am passing no str nowhere?
and yes I should be passing class in bases but why didn't error say that, instead of this cryptic error?
|
[
"see here for the reason for the cryptic msg\nhttp://bugs.python.org/issue6829\nquestions Error when calling the metaclass bases: function() argument 1 must be code, not str has same problem.\nEdit: play-around\nThough you can use metaclass to make it work in a twisted way ;)\ndef func(name, klassDict):\n return type(name, (), klassDict)\n\nclass MyMeta(type):\n def __new__(self, name, bases, klassDict):\n return bases[0](name, klassDict)\n\nclass Klass(func):\n __metaclass__ = MyMeta\n\nprint Klass\n\n"
] |
[
2
] |
[] |
[] |
[
"class",
"python"
] |
stackoverflow_0002308945_class_python.txt
|
Q:
Get class in Python decorator
In this code:
def online_only(func, self):
def f(*args, **kwargs):
if self.running:
return func(*args, **kwargs)
else:
return False
return f
class VM(object):
@property
def running(self):
return True
@property
@online_only
def diskinfo(self):
return True
I want diskinfo to run only when VM.running returned True. How can I get online_only to be able to read self.running?
A:
self is passed as the first parameter to the wrapping function, so just treat the first parameter specially in f:
def online_only(func):
def f(self, *args, **kwargs):
if self.running:
return func(self, *args, **kwargs)
else:
return False
return f
A:
You can not have two arguments in def online_only(func, self) ? it will raise TypeError, so change it to def online_only(func)
The first argument to wrapped function would be self, you can just use that
e.g.
def online_only(func):
def f(self):
if self.running:
return func(self)
else:
return False
return f
class VM(object):
@property
def running(self):
return True
@property
@online_only
def diskinfo(self):
return True
print VM().diskinfo
|
Get class in Python decorator
|
In this code:
def online_only(func, self):
def f(*args, **kwargs):
if self.running:
return func(*args, **kwargs)
else:
return False
return f
class VM(object):
@property
def running(self):
return True
@property
@online_only
def diskinfo(self):
return True
I want diskinfo to run only when VM.running returned True. How can I get online_only to be able to read self.running?
|
[
"self is passed as the first parameter to the wrapping function, so just treat the first parameter specially in f:\ndef online_only(func):\n def f(self, *args, **kwargs):\n if self.running:\n return func(self, *args, **kwargs)\n else:\n return False\n return f\n\n",
"\nYou can not have two arguments in def online_only(func, self) ? it will raise TypeError, so change it to def online_only(func)\nThe first argument to wrapped function would be self, you can just use that \ne.g.\n\n\ndef online_only(func):\n def f(self):\n if self.running:\n return func(self)\n else:\n return False\n return f\n\nclass VM(object):\n @property\n def running(self):\n return True\n\n @property\n @online_only\n def diskinfo(self):\n return True\n\nprint VM().diskinfo\n\n"
] |
[
7,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002309124_python.txt
|
Q:
IMEI number of a mobile phone using python
How can I get the IMEI number of a mobile phone using Python?
A:
Sending AT+CGSN through the appropriate serial device will have it return the IMEI.
|
IMEI number of a mobile phone using python
|
How can I get the IMEI number of a mobile phone using Python?
|
[
"Sending AT+CGSN through the appropriate serial device will have it return the IMEI.\n"
] |
[
0
] |
[] |
[] |
[
"imei",
"mobile_phones",
"python"
] |
stackoverflow_0002309108_imei_mobile_phones_python.txt
|
Q:
cx_Oracle, generators, and threads in Python
What is the behavior of cx_Oracle cursors when the connection object is used by different threads? How would generators affect this behavior? Specifically...
Edit: The original example function was incorrect; a generator was being returned by a sub function, yield wasn't used directly in the loop. This clarifies when finally is executed (after return does), but still doesn't answer whether a cursor can be used if another thread starts using the connection object the cursor was created from. It actually seems (in python 2.4, at least), try...finally with yield causes a syntax error.
def Get()
conn = pool.get()
try:
cursor = conn.cursor()
cursor.execute("select * from table ...")
return IterRows(cursor)
finally:
pool.put(conn)
def IterRows(cursor):
for r in cursor:
yield r
Get() is a function called by multiple threads. The connections are created with the threaded=False argument.
I'm wondering...
Is thread 1's cursor object still usable if thread 2 comes along and uses the same connection object? If not, what might happen?
The behavior i'm seeing is an exception in cx_Oracle talking about a protocol error, and then a segfault follows.
A:
See the docs: threadsafety is, and I quote,
Currently 2, which means that threads
may share the module and connections,
but not cursors.
So your "pool of cursors" construct (where one cursor may be used by different threads) seems to be beyond the threadsafety level. It's not an issue of sharing connections (that's OK since you've passed threaded properly in the connection's constructor) but cursors. You may want to store each cursor in threading.local after the first time a thread has used it, so that each thread can have its own 1-cursor "pool" (not a key optimization, though: making a new cursor is not a heavy-duty operation).
Wrt your question 2, the finally clause executes when the generator object (built by a call to your generator function Get) is all done -- either because it's raising StopIteration, or because it's being garbage collected (typically because the last reference to it has just gone away). E.g if the caller is:
def imthecaller():
for i, row in enumerate(Get()):
print i, row
if i > 1: break
# this is the moment the generators' finally-clause runs
print 'bye'
the finally executes after (at most) 3 rows have been yielded.
|
cx_Oracle, generators, and threads in Python
|
What is the behavior of cx_Oracle cursors when the connection object is used by different threads? How would generators affect this behavior? Specifically...
Edit: The original example function was incorrect; a generator was being returned by a sub function, yield wasn't used directly in the loop. This clarifies when finally is executed (after return does), but still doesn't answer whether a cursor can be used if another thread starts using the connection object the cursor was created from. It actually seems (in python 2.4, at least), try...finally with yield causes a syntax error.
def Get()
conn = pool.get()
try:
cursor = conn.cursor()
cursor.execute("select * from table ...")
return IterRows(cursor)
finally:
pool.put(conn)
def IterRows(cursor):
for r in cursor:
yield r
Get() is a function called by multiple threads. The connections are created with the threaded=False argument.
I'm wondering...
Is thread 1's cursor object still usable if thread 2 comes along and uses the same connection object? If not, what might happen?
The behavior i'm seeing is an exception in cx_Oracle talking about a protocol error, and then a segfault follows.
|
[
"See the docs: threadsafety is, and I quote,\n\nCurrently 2, which means that threads\n may share the module and connections,\n but not cursors.\n\nSo your \"pool of cursors\" construct (where one cursor may be used by different threads) seems to be beyond the threadsafety level. It's not an issue of sharing connections (that's OK since you've passed threaded properly in the connection's constructor) but cursors. You may want to store each cursor in threading.local after the first time a thread has used it, so that each thread can have its own 1-cursor \"pool\" (not a key optimization, though: making a new cursor is not a heavy-duty operation).\nWrt your question 2, the finally clause executes when the generator object (built by a call to your generator function Get) is all done -- either because it's raising StopIteration, or because it's being garbage collected (typically because the last reference to it has just gone away). E.g if the caller is:\ndef imthecaller():\n for i, row in enumerate(Get()):\n print i, row\n if i > 1: break\n # this is the moment the generators' finally-clause runs\n print 'bye'\n\nthe finally executes after (at most) 3 rows have been yielded.\n"
] |
[
2
] |
[] |
[] |
[
"cx_oracle",
"generator",
"multithreading",
"python",
"yield"
] |
stackoverflow_0002308698_cx_oracle_generator_multithreading_python_yield.txt
|
Q:
How to fix the wxpython events called?
with this code:
import wx
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
panel = wx.Panel.__init__(self, parent, *args, **kwargs)
self.colorOver = ((89,89,89))
self.colorLeave = ((110,110,110))
self.colorFont = ((145,145,145))
self.SetBackgroundColour(self.colorLeave)
self.SetForegroundColour(self.colorLeave)
self.name = "Plugin"
self.overPanel = 0
self.overLabel = 0
self.overButton = 0
sizer = wx.BoxSizer(wx.VERTICAL)
self.pluginName = wx.StaticText(self, -1, ' ' + self.getName())
self.pluginClose = wx.BitmapButton(self, -1, wx.Bitmap('C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Images\close.png'), style=wx.NO_BORDER)
self.pluginClose.Hide()
gs = wx.GridSizer(2, 2, 0, 0)
gs.AddMany([(self.pluginName, 0, wx.ALIGN_LEFT), (self.pluginClose, 0, wx.ALIGN_RIGHT|wx.CENTER)])
sizer.Add(gs, 1, wx.EXPAND)
self.SetSizer(sizer)
self.pluginName.Bind(wx.EVT_LEAVE_WINDOW, self.onLabelMouseLeave)
self.pluginName.Bind(wx.EVT_ENTER_WINDOW, self.onLabelMouseOver)
self.pluginClose.Bind(wx.EVT_BUTTON, self.onCloseMouseClick)
self.Bind(wx.EVT_LEAVE_WINDOW, self.onPanelMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self.onPanelMouseOver)
def onPanelMouseOver(self, event):
self.overPanel = 1
self.overLabel = 0
self.SetBackgroundColour(self.colorOver)
self.pluginName.SetForegroundColour(self.colorFont)
self.Refresh()
self.pluginClose.Show()
def onPanelMouseLeave(self, event):
if self.overLabel == 0:
self.overPanel = 0
self.SetBackgroundColour(self.colorLeave)
self.pluginName.SetForegroundColour(self.colorLeave)
self.Refresh()
self.pluginClose.Hide()
def onLabelMouseOver(self, event):
self.overPanel = 0
self.overLabel = 1
self.SetBackgroundColour(self.colorOver)
self.pluginName.SetForegroundColour(self.colorFont)
self.Refresh()
self.pluginClose.Show()
def onLabelMouseLeave(self, event):
if self.overPanel == 0:
self.overLabel = 0
self.SetBackgroundColour(self.colorLeave)
self.pluginName.SetForegroundColour(self.colorLeave)
self.Refresh()
self.pluginClose.Hide()
def OnClose(self, event):
self.Close()
app.Destroy()
def onCloseMouseClick(self, event):
self.Hide()
def getName(self):
return self.name
whenever I get over the BitmapButton the next two events:
self.Bind(wx.EVT_LEAVE_WINDOW, self.onPanelMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self.onPanelMouseOver)
are allways beeing called.
What is wrong with it? How can only one event be called?
Note: if I bind the leave and enter window events to the BitmapButton the two previous events are still called.
A:
Problem is you are hiding and showing bitmap on mouseover, so when you move mouseover bitmap, mouse goes off panel, onPanelMouseLeave is called and you hide bitmap, which means now mouse if over panel, onPanelMouseOver is called and in that event you again show bitmap and that means now mouse if over bitmap again and out of panel and hence you are stuck in a hide/show circle.
Comment out self.pluginClose.Hide() in onPanelMouseLeave and you won't see multiple events.
Try to come with a different approach e.g. check if mouse if over bitmap and hence do not hide it.
|
How to fix the wxpython events called?
|
with this code:
import wx
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
panel = wx.Panel.__init__(self, parent, *args, **kwargs)
self.colorOver = ((89,89,89))
self.colorLeave = ((110,110,110))
self.colorFont = ((145,145,145))
self.SetBackgroundColour(self.colorLeave)
self.SetForegroundColour(self.colorLeave)
self.name = "Plugin"
self.overPanel = 0
self.overLabel = 0
self.overButton = 0
sizer = wx.BoxSizer(wx.VERTICAL)
self.pluginName = wx.StaticText(self, -1, ' ' + self.getName())
self.pluginClose = wx.BitmapButton(self, -1, wx.Bitmap('C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Images\close.png'), style=wx.NO_BORDER)
self.pluginClose.Hide()
gs = wx.GridSizer(2, 2, 0, 0)
gs.AddMany([(self.pluginName, 0, wx.ALIGN_LEFT), (self.pluginClose, 0, wx.ALIGN_RIGHT|wx.CENTER)])
sizer.Add(gs, 1, wx.EXPAND)
self.SetSizer(sizer)
self.pluginName.Bind(wx.EVT_LEAVE_WINDOW, self.onLabelMouseLeave)
self.pluginName.Bind(wx.EVT_ENTER_WINDOW, self.onLabelMouseOver)
self.pluginClose.Bind(wx.EVT_BUTTON, self.onCloseMouseClick)
self.Bind(wx.EVT_LEAVE_WINDOW, self.onPanelMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self.onPanelMouseOver)
def onPanelMouseOver(self, event):
self.overPanel = 1
self.overLabel = 0
self.SetBackgroundColour(self.colorOver)
self.pluginName.SetForegroundColour(self.colorFont)
self.Refresh()
self.pluginClose.Show()
def onPanelMouseLeave(self, event):
if self.overLabel == 0:
self.overPanel = 0
self.SetBackgroundColour(self.colorLeave)
self.pluginName.SetForegroundColour(self.colorLeave)
self.Refresh()
self.pluginClose.Hide()
def onLabelMouseOver(self, event):
self.overPanel = 0
self.overLabel = 1
self.SetBackgroundColour(self.colorOver)
self.pluginName.SetForegroundColour(self.colorFont)
self.Refresh()
self.pluginClose.Show()
def onLabelMouseLeave(self, event):
if self.overPanel == 0:
self.overLabel = 0
self.SetBackgroundColour(self.colorLeave)
self.pluginName.SetForegroundColour(self.colorLeave)
self.Refresh()
self.pluginClose.Hide()
def OnClose(self, event):
self.Close()
app.Destroy()
def onCloseMouseClick(self, event):
self.Hide()
def getName(self):
return self.name
whenever I get over the BitmapButton the next two events:
self.Bind(wx.EVT_LEAVE_WINDOW, self.onPanelMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self.onPanelMouseOver)
are allways beeing called.
What is wrong with it? How can only one event be called?
Note: if I bind the leave and enter window events to the BitmapButton the two previous events are still called.
|
[
"Problem is you are hiding and showing bitmap on mouseover, so when you move mouseover bitmap, mouse goes off panel, onPanelMouseLeave is called and you hide bitmap, which means now mouse if over panel, onPanelMouseOver is called and in that event you again show bitmap and that means now mouse if over bitmap again and out of panel and hence you are stuck in a hide/show circle.\nComment out self.pluginClose.Hide() in onPanelMouseLeave and you won't see multiple events.\nTry to come with a different approach e.g. check if mouse if over bitmap and hence do not hide it.\n"
] |
[
2
] |
[] |
[] |
[
"button",
"events",
"panel",
"python",
"wxpython"
] |
stackoverflow_0002306000_button_events_panel_python_wxpython.txt
|
Q:
Sizing controls for items in wx.lib.CustomTreeCtrl
Is there a trick to sizing controls for wx.lib.CUstomTreeCtrl? I've been trying to create my own custom controls (just panels with sub-controls in them) and add them as items in my CustomTreeCtrl, but when the tree renders, it's as if the panels aren't expanded to the appropriate size. I can set the panel size manually by using SetSize() but if I do that, the tree doesn't seem to be aware of the size (the rows aren't scaled to the appropriate size) and the items are rendered on top of each other. I've tried to override DoGetBestSize() but it seems to not have any effect.
A:
Can you put a self contained sample code and we can try to fix that.
Have you tried adding custom items which return correct height for your panel?
|
Sizing controls for items in wx.lib.CustomTreeCtrl
|
Is there a trick to sizing controls for wx.lib.CUstomTreeCtrl? I've been trying to create my own custom controls (just panels with sub-controls in them) and add them as items in my CustomTreeCtrl, but when the tree renders, it's as if the panels aren't expanded to the appropriate size. I can set the panel size manually by using SetSize() but if I do that, the tree doesn't seem to be aware of the size (the rows aren't scaled to the appropriate size) and the items are rendered on top of each other. I've tried to override DoGetBestSize() but it seems to not have any effect.
|
[
"Can you put a self contained sample code and we can try to fix that.\nHave you tried adding custom items which return correct height for your panel?\n"
] |
[
0
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002219514_python_wxpython.txt
|
Q:
Modifiying a Django view for a certain project
So I simply want to use the delete() from the django.contrib.comments.views.moderation module, but only allowing the users with permission to delete their comments. In order to do this, all I have to do is uncomment #@permission_required("comments.delete_comment"), but I want to be able to do this without modifying the django framework. How can I modify/extend this view to my project? I guess the better question would be, what is the best way to change the setting for the delete() without changing anything in the django framework?
A:
That line is only commented out because Django 1.1 maintains compatibility with Python 2.3 which doesn't support the decorator (@) syntax. But the view is decorated with permission_required nonetheless (with syntax that is compatible with Python 2.3), as you can see here. Django 1.2 will drop support for Python 2.3 and will switch to the @-syntax. This is already visible on trunk.
Bottom line: you have to do nothing, as Django does already exactly what you want (this seems to be a recurring theme with Django :-) ).
|
Modifiying a Django view for a certain project
|
So I simply want to use the delete() from the django.contrib.comments.views.moderation module, but only allowing the users with permission to delete their comments. In order to do this, all I have to do is uncomment #@permission_required("comments.delete_comment"), but I want to be able to do this without modifying the django framework. How can I modify/extend this view to my project? I guess the better question would be, what is the best way to change the setting for the delete() without changing anything in the django framework?
|
[
"That line is only commented out because Django 1.1 maintains compatibility with Python 2.3 which doesn't support the decorator (@) syntax. But the view is decorated with permission_required nonetheless (with syntax that is compatible with Python 2.3), as you can see here. Django 1.2 will drop support for Python 2.3 and will switch to the @-syntax. This is already visible on trunk.\nBottom line: you have to do nothing, as Django does already exactly what you want (this seems to be a recurring theme with Django :-) ).\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_comments",
"python"
] |
stackoverflow_0002307219_django_django_comments_python.txt
|
Q:
How to Include xml file as .py source file
I am having a xml file and i am reading the data from that xml file.
But the problem is that i am making an exe file from all the available .py files (using py2exe).
i dont want to distribute my xml file along with my exe ( because of securiy reasons) as standalone xml file.I want my xml file should be part of exe as all other remaining .py files.
So Any idea can i use my xml file as .py file or anyother method.
Any help really appreciable.
A:
One thing you can do is include it as a string in a module:
bigxml = '''<?xml ...
....
....
....
</topelement>'''
Then just import it:
from xmldoc import bigxml
|
How to Include xml file as .py source file
|
I am having a xml file and i am reading the data from that xml file.
But the problem is that i am making an exe file from all the available .py files (using py2exe).
i dont want to distribute my xml file along with my exe ( because of securiy reasons) as standalone xml file.I want my xml file should be part of exe as all other remaining .py files.
So Any idea can i use my xml file as .py file or anyother method.
Any help really appreciable.
|
[
"One thing you can do is include it as a string in a module:\nbigxml = '''<?xml ...\n ....\n ....\n ....\n</topelement>'''\n\nThen just import it:\nfrom xmldoc import bigxml\n\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002309783_python.txt
|
Q:
Downloading Image
I used urllib2.build_opener() to download an image from a corresponding url.But for a particular url I am getting an error. When I checked that url, I saw that there is no image. How can I check whether there is an image or not? This is my code:
opener1 = urllib2.build_opener()
page1=opener1.open(orginal)
my_picture=page1.read()
The error i got is
File "suitcase.py", line 120, in <module>
get_suitcase()
File "suitcase.py", line 96, in get_suitcase
page1=opener1.open(orginal)
File "D:\Program Files\Python\lib\urllib2.py", line 395, in open
response = meth(req, response)
File "D:\Program Files\Python\lib\urllib2.py", line 508, in http_response
'http', request, response, code, msg, hdrs)
File "D:\Program Files\Python\lib\urllib2.py", line 433, in error
return self._call_chain(*args)
File "D:\Program Files\Python\lib\urllib2.py", line 367, in _call_chain
result = func(*args)
File "D:\Program Files\Python\lib\urllib2.py", line 516, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
How do I check that an image is there and proceed with saving that image?
A:
I don't understand. Why just not catch the error with the try and except keywords?
A:
as others have suggested catch the exception and check for code e.g.
import urllib2
opener1 = urllib2.build_opener()
try:
page1=opener1.open("http://www.google.com/nosuchimage")
my_picture=page1.read()
except urllib2.HTTPError,e:
if e.code == 404:
print "no such image"
else:
print "error",e
except urllib2.URLError,e:
print "URLError",e
A:
By checking the code attribute of the exception.
A:
try:
page1=opener1.open(orginal)
except HTTPError, e:
if e.code == 404: # Only one of the many possible errors...
print "Resource does not exist"
raise
my_picture=page1.read()
see also urllib2 - the missing manual
|
Downloading Image
|
I used urllib2.build_opener() to download an image from a corresponding url.But for a particular url I am getting an error. When I checked that url, I saw that there is no image. How can I check whether there is an image or not? This is my code:
opener1 = urllib2.build_opener()
page1=opener1.open(orginal)
my_picture=page1.read()
The error i got is
File "suitcase.py", line 120, in <module>
get_suitcase()
File "suitcase.py", line 96, in get_suitcase
page1=opener1.open(orginal)
File "D:\Program Files\Python\lib\urllib2.py", line 395, in open
response = meth(req, response)
File "D:\Program Files\Python\lib\urllib2.py", line 508, in http_response
'http', request, response, code, msg, hdrs)
File "D:\Program Files\Python\lib\urllib2.py", line 433, in error
return self._call_chain(*args)
File "D:\Program Files\Python\lib\urllib2.py", line 367, in _call_chain
result = func(*args)
File "D:\Program Files\Python\lib\urllib2.py", line 516, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
How do I check that an image is there and proceed with saving that image?
|
[
"I don't understand. Why just not catch the error with the try and except keywords?\n",
"as others have suggested catch the exception and check for code e.g.\nimport urllib2\n\nopener1 = urllib2.build_opener()\ntry:\n page1=opener1.open(\"http://www.google.com/nosuchimage\")\n my_picture=page1.read()\nexcept urllib2.HTTPError,e:\n if e.code == 404:\n print \"no such image\"\n else:\n print \"error\",e\nexcept urllib2.URLError,e:\n print \"URLError\",e\n\n",
"By checking the code attribute of the exception.\n",
"try:\n page1=opener1.open(orginal)\nexcept HTTPError, e:\n if e.code == 404: # Only one of the many possible errors...\n print \"Resource does not exist\"\n raise\n\nmy_picture=page1.read() \n\nsee also urllib2 - the missing manual\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002309829_python.txt
|
Q:
Redirect stderr to stdout on exec-ed process from python?
In a bash script, I can write:
exec 2>&1
exec someprog
And the stderr output of someprog would be redirected to stdout.
Is there any way to do a similar thing using python's os.exec* functions?
This doesn't have to be portable, just work on Linux.
A:
os.dup2(1, 2)
Illuminating examples
Let's execute /bin/ls with a bogus argument so that it complains to stderr.
$ python -c "import os; os.execl('/bin/ls', '', 'ffweew')" 1>/dev/null
: ffweew: No such file or directory
$ python -c "import os; os.execl('/bin/ls', '', 'ffweew')" 2>/dev/null
$ python -c "import os; os.dup2(1, 2); os.execl('/bin/ls', '', 'ffweew')" 1>/dev/null
$ python -c "import os; os.dup2(1, 2); os.execl('/bin/ls', '', 'ffweew')" 2>/dev/null
: ffweew: No such file or directory
$
First two invocations prove that ls does not write to stdout, and writes the error message to stderr.
In the 3rd and the 4th invocation, the Python program duplicates file descriptor 1 as file descriptor 2, achieving the desired effect.
|
Redirect stderr to stdout on exec-ed process from python?
|
In a bash script, I can write:
exec 2>&1
exec someprog
And the stderr output of someprog would be redirected to stdout.
Is there any way to do a similar thing using python's os.exec* functions?
This doesn't have to be portable, just work on Linux.
|
[
"os.dup2(1, 2)\nIlluminating examples\nLet's execute /bin/ls with a bogus argument so that it complains to stderr.\n\n$ python -c \"import os; os.execl('/bin/ls', '', 'ffweew')\" 1>/dev/null\n: ffweew: No such file or directory\n$ python -c \"import os; os.execl('/bin/ls', '', 'ffweew')\" 2>/dev/null\n$ python -c \"import os; os.dup2(1, 2); os.execl('/bin/ls', '', 'ffweew')\" 1>/dev/null\n$ python -c \"import os; os.dup2(1, 2); os.execl('/bin/ls', '', 'ffweew')\" 2>/dev/null\n: ffweew: No such file or directory\n$ \n\nFirst two invocations prove that ls does not write to stdout, and writes the error message to stderr.\nIn the 3rd and the 4th invocation, the Python program duplicates file descriptor 1 as file descriptor 2, achieving the desired effect.\n"
] |
[
5
] |
[] |
[] |
[
"file_descriptor",
"linux",
"python",
"redirect"
] |
stackoverflow_0002309911_file_descriptor_linux_python_redirect.txt
|
Q:
Get rid of leading zeros for date strings in Python?
Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'12/01/2009'
See also
Python strftime - date without leading 0?
A:
A simpler and readable solution is to format it yourself:
>>> d = datetime.datetime.now()
>>> "%d/%d/%d"%(d.month, d.day, d.year)
4/8/2012
A:
@OP, it doesn't take much to do a bit of string manipulation.
>>> t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
>>> '/'.join( map( str, map(int,t.split("/")) ) )
'12/1/2009'
A:
I'd suggest a very simple regular expression. It's not like this is performace-critical, is it?
Search for \b0 and replace with nothing.
I. e.:
import re
newstring = re.sub(r"\b0","",time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y')))
A:
>>> time.strftime('%-m/%-d/%Y',time.strptime('8/1/2009', '%m/%d/%Y'))
'8/1/2009'
However, I suspect this is dependent on the system's strftime() implementation and might not be fully portable to all platforms, if that matters to you.
|
Get rid of leading zeros for date strings in Python?
|
Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'12/01/2009'
See also
Python strftime - date without leading 0?
|
[
"A simpler and readable solution is to format it yourself:\n>>> d = datetime.datetime.now()\n>>> \"%d/%d/%d\"%(d.month, d.day, d.year)\n4/8/2012\n\n",
"@OP, it doesn't take much to do a bit of string manipulation.\n>>> t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))\n>>> '/'.join( map( str, map(int,t.split(\"/\")) ) )\n'12/1/2009'\n\n",
"I'd suggest a very simple regular expression. It's not like this is performace-critical, is it? \nSearch for \\b0 and replace with nothing.\nI. e.:\nimport re\nnewstring = re.sub(r\"\\b0\",\"\",time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y')))\n\n",
">>> time.strftime('%-m/%-d/%Y',time.strptime('8/1/2009', '%m/%d/%Y'))\n'8/1/2009'\n\nHowever, I suspect this is dependent on the system's strftime() implementation and might not be fully portable to all platforms, if that matters to you.\n"
] |
[
22,
8,
3,
2
] |
[] |
[] |
[
"date",
"leading_zero",
"python"
] |
stackoverflow_0002309828_date_leading_zero_python.txt
|
Q:
file manipulation and find a word and tricky replace
I have file something like this
hostname ser1-xyz
myuser name
passwd secret
group 1234
hostname ser2-xyz
myuser name
passwd secret
group 2345
I need to find the line first appearance of host named "ser1-xyz" and modify it as
"ser1" and increment it's the group value by 1
So that final file looks like :
hostname ser1
myuser name
passwd secret
group 1235
hostname ser2-xyz
myuser name
passwd secret
group 2345
Currently I'm following code,which can modify the "ser1-xyz" into "ser1"
for line in fileinput.FileInput(fn,inplace=1):
line = line.replace(search,replace)
But how to increment group value?
A:
one way
import fileinput
f=0
for line in fileinput.input("file",inplace=0):
if "hostname" in line and "ser1-xyz" in line:
line=line.replace("ser1-xyz","ser1")
f=1
if f and "group" in line:
a=line.rstrip().split(" ")
a[-1]=str(int(a[-1])+1)
line=' '.join(a)
f=0
print line.rstrip()
output
$ ./python.py
hostname ser1
myuser name
passwd secret
group 1235
hostname ser2-xyz
myuser name
passwd secret
group 2345
change inplace=0 to inplace=1 for inplace edit.
|
file manipulation and find a word and tricky replace
|
I have file something like this
hostname ser1-xyz
myuser name
passwd secret
group 1234
hostname ser2-xyz
myuser name
passwd secret
group 2345
I need to find the line first appearance of host named "ser1-xyz" and modify it as
"ser1" and increment it's the group value by 1
So that final file looks like :
hostname ser1
myuser name
passwd secret
group 1235
hostname ser2-xyz
myuser name
passwd secret
group 2345
Currently I'm following code,which can modify the "ser1-xyz" into "ser1"
for line in fileinput.FileInput(fn,inplace=1):
line = line.replace(search,replace)
But how to increment group value?
|
[
"one way\nimport fileinput\nf=0\nfor line in fileinput.input(\"file\",inplace=0):\n if \"hostname\" in line and \"ser1-xyz\" in line:\n line=line.replace(\"ser1-xyz\",\"ser1\")\n f=1\n if f and \"group\" in line:\n a=line.rstrip().split(\" \")\n a[-1]=str(int(a[-1])+1)\n line=' '.join(a)\n f=0\n print line.rstrip()\n\noutput\n$ ./python.py\nhostname ser1\nmyuser name\npasswd secret\ngroup 1235\n\nhostname ser2-xyz\nmyuser name\npasswd secret\ngroup 2345\n\nchange inplace=0 to inplace=1 for inplace edit.\n"
] |
[
2
] |
[] |
[] |
[
"file",
"python",
"replace"
] |
stackoverflow_0002310014_file_python_replace.txt
|
Q:
Reading file from concatinated ( tar ) file directly without untarring the tar file
Hi i am having a one xml file and some image files, i am making my one concatenate file (ie as like tar file) from all these file (i am having my own scripts for tarring and untarring).
before i describe what exactly i want you have to look the current situation.
As of now i have to untar the all files into a directory then i am able to read the xml file which is part of the tar file.Then i read the data from xml file and then i am able to draw image mention in xml ( image names are mention in xml attribute value) on corresponding panels.
Now i want when someone click on my tar file, i should able to read the xml file and then i am able to read all the other images ( data) and i can draw on the corresponding panel with extract specifically in to a directory.
Is any method or any help really help me alot.
Thanks in advance.
A:
The tarfile module gives you access to tarballs. It won't be random access, but you can read out any files you need and put them in a temporary directory, or just store them in strings.
|
Reading file from concatinated ( tar ) file directly without untarring the tar file
|
Hi i am having a one xml file and some image files, i am making my one concatenate file (ie as like tar file) from all these file (i am having my own scripts for tarring and untarring).
before i describe what exactly i want you have to look the current situation.
As of now i have to untar the all files into a directory then i am able to read the xml file which is part of the tar file.Then i read the data from xml file and then i am able to draw image mention in xml ( image names are mention in xml attribute value) on corresponding panels.
Now i want when someone click on my tar file, i should able to read the xml file and then i am able to read all the other images ( data) and i can draw on the corresponding panel with extract specifically in to a directory.
Is any method or any help really help me alot.
Thanks in advance.
|
[
"The tarfile module gives you access to tarballs. It won't be random access, but you can read out any files you need and put them in a temporary directory, or just store them in strings.\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002310100_python.txt
|
Q:
running a .py by double-clicking is not working
I'm using Windows XP.
When I double click the Launch_PyDemos.pyw from the book Programming Python, nothing happens. When I try to run Launch_PyDemos.pyw from command-line, I get the error message:
Traceback (most recent call last):
File "PyDemos2.pyw", line 41, in <module>
from PP3E.Gui.Tools.windows import MainWindow # a Tk with icon, title, quit
ImportError: No module named PP3E.Gui.Tools.windows
When I set the PythonPath enviroment variable to the PP3E folder, nothing happens. When I append the PP3E folder to the Path enviroment variable, nothing happens. When I copy the PP3E directory tree to the site-packages folder in your Python source library, nothing happens.
What is going on?
A:
You're missing libraries from the book. Quoting a bytes thread:
Please follow the instructions on the
book, or read the README-PP3E.txt
file; below I copy the most relevant
parts:
"""Copy the entire PP3E directory tree
to some directory on your computer,
and add the name of the directory
containing PP3E to your module search
path (i.e., you PYTHONPATH shell
setting, ".pth" files, etc.).
Alternatively, copy the PP3E directory
tree to the site-packages folder in
your Python source library (e.g.,
C:\Python24\Lib\site-packages on
Windows for Python 2.4). Because this
directory is automatically searched on
imports, copying here makes PYTHONPATH
settings unnecessary."""
Also, make sure you get the updated
version from
http://examples.oreilly.com/python3/pp3e-updates.html
|
running a .py by double-clicking is not working
|
I'm using Windows XP.
When I double click the Launch_PyDemos.pyw from the book Programming Python, nothing happens. When I try to run Launch_PyDemos.pyw from command-line, I get the error message:
Traceback (most recent call last):
File "PyDemos2.pyw", line 41, in <module>
from PP3E.Gui.Tools.windows import MainWindow # a Tk with icon, title, quit
ImportError: No module named PP3E.Gui.Tools.windows
When I set the PythonPath enviroment variable to the PP3E folder, nothing happens. When I append the PP3E folder to the Path enviroment variable, nothing happens. When I copy the PP3E directory tree to the site-packages folder in your Python source library, nothing happens.
What is going on?
|
[
"You're missing libraries from the book. Quoting a bytes thread:\n\nPlease follow the instructions on the\n book, or read the README-PP3E.txt\n file; below I copy the most relevant\n parts:\n\"\"\"Copy the entire PP3E directory tree\n to some directory on your computer,\n and add the name of the directory\n containing PP3E to your module search\n path (i.e., you PYTHONPATH shell\n setting, \".pth\" files, etc.).\nAlternatively, copy the PP3E directory\n tree to the site-packages folder in\n your Python source library (e.g.,\n C:\\Python24\\Lib\\site-packages on\n Windows for Python 2.4). Because this\n directory is automatically searched on\n imports, copying here makes PYTHONPATH\n settings unnecessary.\"\"\"\nAlso, make sure you get the updated\n version from\n http://examples.oreilly.com/python3/pp3e-updates.html\n\n"
] |
[
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002310189_python.txt
|
Q:
How do I print out which arguments a Python function requires/allows?
Suppose I have a function and I want to print out the arguments it accepts. How can I do this?
A:
Use inspect.getargspec() to find out.
A:
I see that someone has already offered the answer i had in mind, so i'll suggest a purely practical one. IDLE will give you a function's parameters as a 'tooltip'.
This should be enabled by default; the tooltip will appear just after you type the function name and the left parenthesis.
To do this, IDLE just accesses the function's doc string, so it will show the tooltip for any python function--standard library, third-party library, or even a function you've created earlier and is in a namespace accessible to IDLE.
Obviously, this is works only when you are working in interactive mode in IDLE, though it does have the advantage of not requiring an additional function call.
A:
The help function does this.
All you have to do is put in docstrings for your functions.
|
How do I print out which arguments a Python function requires/allows?
|
Suppose I have a function and I want to print out the arguments it accepts. How can I do this?
|
[
"Use inspect.getargspec() to find out.\n",
"I see that someone has already offered the answer i had in mind, so i'll suggest a purely practical one. IDLE will give you a function's parameters as a 'tooltip'. \nThis should be enabled by default; the tooltip will appear just after you type the function name and the left parenthesis. \nTo do this, IDLE just accesses the function's doc string, so it will show the tooltip for any python function--standard library, third-party library, or even a function you've created earlier and is in a namespace accessible to IDLE.\nObviously, this is works only when you are working in interactive mode in IDLE, though it does have the advantage of not requiring an additional function call. \n",
"The help function does this.\nAll you have to do is put in docstrings for your functions.\n"
] |
[
6,
2,
0
] |
[
"if you use IPython (as you absolutely should), use\nfoo?\n\nto see the documentation, including what the function expects, and:\nfoo??\n\nto see the above documentation plus the source code (if available)\n"
] |
[
-1
] |
[
"argument_passing",
"arguments",
"function",
"python"
] |
stackoverflow_0002309645_argument_passing_arguments_function_python.txt
|
Q:
Python Virtualbox API
http://enomalism.com/api/pyvb/pyvb.vm.vbVM-class.html
there is a parameter **kw in init(self, **kw)
what is it?
A:
A dictionary of arbitrary keyword arguments. See http://docs.python.org/tutorial/controlflow.html#keyword-arguments
If it really is a question about that concrete API, then please excuse me, I was typing faster than thinking.
A:
**kw is short for **kwargs. Additional named aguments.
A:
Looks like it's a dictionary of options from the source?
|
Python Virtualbox API
|
http://enomalism.com/api/pyvb/pyvb.vm.vbVM-class.html
there is a parameter **kw in init(self, **kw)
what is it?
|
[
"A dictionary of arbitrary keyword arguments. See http://docs.python.org/tutorial/controlflow.html#keyword-arguments\nIf it really is a question about that concrete API, then please excuse me, I was typing faster than thinking.\n",
"**kw is short for **kwargs. Additional named aguments.\n",
"Looks like it's a dictionary of options from the source?\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002310563_python.txt
|
Q:
Printing tuple data in normal text in Python
I have variable r=(u'East london,London,England', u'Mr.Baker in East london (at 2010-02-21 15:25:27.0)') in this format from webservice as a output from small program. How can I print these tuple data as normal string like:
East london,London,England Mr.Baker in East london (at 2010-02-21 15:25:27.0)
can anybody help me out of this please?Thanks in advance!
my code is giving now!
from sqlite3 import *
import feedparser
import codecs# newly added
data = feedparser.parse("some url")
conn = connect('location2.db')
curs = conn.cursor()
curs.execute('''create table location_top6
( id integer primary key,title text ,
updated text)''')
for i in range(len(data['entries'])):
curs.execute("insert into location_top6 values\
(NULL, '%s', '%s')" % (data.entries[i].title,data.entries[i].summary))
conn.commit()
curs.execute("select * from location_top6")
for r in curs:
print r
and I want this r value printed as normal string!
A:
just join on the separator, if it's space it would be:
' '.join(r)
edit: re your update code. Your table contains primary key, as can be seen from the table definition, that primary key is an integer. That's why you're getting that TypeError. The question is whether you want to print that primary key or not. If the answer is yes you could do the following:
' '.join(str(i) for i in r)
if no is the answer: you just need to ' '.join(r[1:]).
A:
If the sequence x contains other types than string, convert those first:
' '.join( map( str, x ) )
|
Printing tuple data in normal text in Python
|
I have variable r=(u'East london,London,England', u'Mr.Baker in East london (at 2010-02-21 15:25:27.0)') in this format from webservice as a output from small program. How can I print these tuple data as normal string like:
East london,London,England Mr.Baker in East london (at 2010-02-21 15:25:27.0)
can anybody help me out of this please?Thanks in advance!
my code is giving now!
from sqlite3 import *
import feedparser
import codecs# newly added
data = feedparser.parse("some url")
conn = connect('location2.db')
curs = conn.cursor()
curs.execute('''create table location_top6
( id integer primary key,title text ,
updated text)''')
for i in range(len(data['entries'])):
curs.execute("insert into location_top6 values\
(NULL, '%s', '%s')" % (data.entries[i].title,data.entries[i].summary))
conn.commit()
curs.execute("select * from location_top6")
for r in curs:
print r
and I want this r value printed as normal string!
|
[
"just join on the separator, if it's space it would be:\n' '.join(r)\n\nedit: re your update code. Your table contains primary key, as can be seen from the table definition, that primary key is an integer. That's why you're getting that TypeError. The question is whether you want to print that primary key or not. If the answer is yes you could do the following:\n' '.join(str(i) for i in r)\n\nif no is the answer: you just need to ' '.join(r[1:]).\n",
"If the sequence x contains other types than string, convert those first:\n' '.join( map( str, x ) )\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"tuples"
] |
stackoverflow_0002310919_python_tuples.txt
|
Q:
How can I get python in the command prompt on Windows?
I have just installed Python on my Windows 7. I thought that after that I will be able to run python on the command prompt but it is not the case. After the installation I also found out that I can run the python command shell. This is nice. But what should I do if I want to save my program in a file and then I want to run this program (in Linux, for example, I typed "python file_name.py" in the command line).
A:
You need to add the python bin directory to your path. Follow the instructions here and add c:\python26\bin to the path (unless you installed python in a non-default location).
A:
Is python.exe in your windows path? Try to look at the PATH environment variable and see if the installation folder of python is listed there.
A:
You need to update your environment variables to include the path to the Python executable.
On XP you can do this by right clicking on "My Computer" -> Properties and then going to the "Advanced" tab.
|
How can I get python in the command prompt on Windows?
|
I have just installed Python on my Windows 7. I thought that after that I will be able to run python on the command prompt but it is not the case. After the installation I also found out that I can run the python command shell. This is nice. But what should I do if I want to save my program in a file and then I want to run this program (in Linux, for example, I typed "python file_name.py" in the command line).
|
[
"You need to add the python bin directory to your path. Follow the instructions here and add c:\\python26\\bin to the path (unless you installed python in a non-default location).\n",
"Is python.exe in your windows path? Try to look at the PATH environment variable and see if the installation folder of python is listed there.\n",
"You need to update your environment variables to include the path to the Python executable. \nOn XP you can do this by right clicking on \"My Computer\" -> Properties and then going to the \"Advanced\" tab. \n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"command_line",
"command_prompt",
"python",
"windows"
] |
stackoverflow_0002311074_command_line_command_prompt_python_windows.txt
|
Q:
Determine if string in input is a single word in Python
a brain dead third party program I'm forced to use determines how to treat paths depending if the input supplied is a single word, or a full path: in the former case, the path is interpreted relative to some obscure root directory.
So, given that the input can be a full or relative path, or a single word (including underscores and dashes, but not spaces), I'm wondering how to write a function that determines if the input is a single "word" as defined above.
For example:
"Public_345" would classify as valid "word"
"/home/path/to/something" would obviously be not
"Foo bar" would also not be considered a valid "word"
As string methods are not OK, I am wondering if it would be possible to use regular expression. Initially I thought up of something like this:
match = re.compile(r"[\w-]+")
word = "abdcde_-4"
if len(re.findall(match, word)) == 1:
print "Single word"
It does feel extremely ugly, however, and I'm pretty sure it doesn't catch corner cases. Are there (much) better solutions around there?
A:
You could tweak your regex to match the whole input string so that you don't have to count the matches. I.e.
if re.match(r'\A[\w-]+\Z', word):
print "Single word"
(compile the regex if you feel so inclined)
\A and \Z match the beginning and end of the input string, respectively. So, if your word contains other data in it besides the path, then the above approach does not work.
A:
>>> r="Foo bar".split()
>>> if len(r) != 1: print "not ok"
...
not ok
>>> if "/" in "/home/path/to/something":
... print "ok"
...
ok
A:
Just check the string and see if it contains a ' ' (space) or an '\' (path separator). If it does, then it's not a "single word".
A:
Check the os.path module. You can use os.path.abspath() to convert a given path into full path (if it is on the same system).
You can check with the following snippet if the string has any whitespace characters.
if(str.split()[-1] == str) return True
|
Determine if string in input is a single word in Python
|
a brain dead third party program I'm forced to use determines how to treat paths depending if the input supplied is a single word, or a full path: in the former case, the path is interpreted relative to some obscure root directory.
So, given that the input can be a full or relative path, or a single word (including underscores and dashes, but not spaces), I'm wondering how to write a function that determines if the input is a single "word" as defined above.
For example:
"Public_345" would classify as valid "word"
"/home/path/to/something" would obviously be not
"Foo bar" would also not be considered a valid "word"
As string methods are not OK, I am wondering if it would be possible to use regular expression. Initially I thought up of something like this:
match = re.compile(r"[\w-]+")
word = "abdcde_-4"
if len(re.findall(match, word)) == 1:
print "Single word"
It does feel extremely ugly, however, and I'm pretty sure it doesn't catch corner cases. Are there (much) better solutions around there?
|
[
"You could tweak your regex to match the whole input string so that you don't have to count the matches. I.e.\nif re.match(r'\\A[\\w-]+\\Z', word):\n print \"Single word\"\n\n(compile the regex if you feel so inclined)\n\\A and \\Z match the beginning and end of the input string, respectively. So, if your word contains other data in it besides the path, then the above approach does not work.\n",
">>> r=\"Foo bar\".split()\n>>> if len(r) != 1: print \"not ok\"\n...\nnot ok\n>>> if \"/\" in \"/home/path/to/something\":\n... print \"ok\"\n...\nok\n\n",
"Just check the string and see if it contains a ' ' (space) or an '\\' (path separator). If it does, then it's not a \"single word\".\n",
"Check the os.path module. You can use os.path.abspath() to convert a given path into full path (if it is on the same system). \nYou can check with the following snippet if the string has any whitespace characters.\nif(str.split()[-1] == str) return True\n"
] |
[
6,
3,
0,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002311044_python_string.txt
|
Q:
When using Parallel Python, is there any way to tell on which machine the job has run?
I have written a simple program using parallel python, and all works well. However, mainly for curiosities sake, I would like to know on which machine each task ran, and how long it took.
Is there any way to programmatically get this information for the job that is returned?
A:
A uuid1 could help:
>>> import uuid
>>> uuid.uuid1()
UUID('b46fa8cf-1fc1-11df-b891-001641ec3fab')
>>>
See pydoc uuid and the RFC 4122 for more details, I think the last 48 bits are unique to the host. Not sure you you call/return that in Parallel python though.
In the pp.py I found:
self.__stats[hostid] = _Statistics(ncpus, rworker)
Can you then use get_stats() to get at that:
get_stats(self)
Returns job execution statistics as a dictionary.
|
When using Parallel Python, is there any way to tell on which machine the job has run?
|
I have written a simple program using parallel python, and all works well. However, mainly for curiosities sake, I would like to know on which machine each task ran, and how long it took.
Is there any way to programmatically get this information for the job that is returned?
|
[
"A uuid1 could help:\n>>> import uuid\n>>> uuid.uuid1()\nUUID('b46fa8cf-1fc1-11df-b891-001641ec3fab')\n>>>\n\nSee pydoc uuid and the RFC 4122 for more details, I think the last 48 bits are unique to the host. Not sure you you call/return that in Parallel python though.\nIn the pp.py I found:\nself.__stats[hostid] = _Statistics(ncpus, rworker)\n\nCan you then use get_stats() to get at that:\nget_stats(self)\nReturns job execution statistics as a dictionary.\n"
] |
[
1
] |
[] |
[] |
[
"parallel_python",
"python"
] |
stackoverflow_0002307739_parallel_python_python.txt
|
Q:
How to handle user mangement in Django for groups that has same access but different rules?
Background information:
I have created an internal site for a company. Most of the work has gone into making calculation tools that their sale persons can use to make offers for clients. Create pdf offers and contracts that can be downloaded, compare prices etc. All of this is working fine.
Now their sale persons have been divided into two groups.
One group is sale personal that is hired by the company.
The other group is persons a company themselves.
The question:
My challenge now is, that I in some cases need to display different things depending on the type of sales person. Some of the rules for the calculation tools will have different rules as to which numbers will be allowed etc. But a big part of the site will still be the same for both groups.
What I would like to know, is if there is a good way of handling this problem?
My own thoughts:
I thought about managing this by using the groups that is available in contrib.auth. That way I could keep a single code base, but would have to make rules a lot of different places. Rules for validating forms to check if the numbers entered is allowed, will depend on the group the user is in. Some things will have different names, or the workflow might be a bit different. Some tools will only be available to one of the groups. This seems like a quick solution here and now, but if the two groups will need to change more and more, it seems like this would quickly become hard to manage.
I also thought about making two different sites. The idea here was to create apps that both groups use, so I only would need to make the code for that 1 place. Then I could make the custom parts for each site and wouldn't need to check for the user in most templates and views. But I'm not sure if this is a good way to go about things. It will create a lot of extra work, and if the two groups can use a lot of the same code, this might not really be needed.
The biggest concern is that I don't really know how this evolve, so it could end up with the two groups being entire different or with only very few differences. What I would like to do, is write some code that can support both scenarios so I wont end up regretting my choice a half year from now.
So, how do you handle this case of user management. I'm looking for ideas techniques or reusable apps that address this problem, not a ready made solution.
Clarifications:
My issue is not pure presentation that can be done with templates, but also that certain calculation tools (a form that is filled out) will have different rules/validation applied to them, and in some cases the calculations done will also be different. So they might see the same form, but wont be allowed to enter the same numbers, and the same numbers might not give the same result.
A:
you could use proxy models on the Group and User models that come packed with django.
then write your authorization and calculation methods inside the proxy model. if a new group is added later, you only need to add/change the methods inside of those two proxy models. then make every instance of Group and User (obviously only where necessary, not literally every one) find the proxy model instead of the actual contrib model.
A:
If I'm understanding you correctly, it seems like you want to have two different groups have access to all the same views, but they will see different numbers. You can achieve this effect by making separate templates for the different groups, and then loading the appropriate template for each view depending on the group of the current user.
Similarly you can use a context processor to put the current group into the context for every view, and then put conditionals in the templates to select which numbers to show.
The other option is to have two separate sets of views for the two different groups. Then use decorators on the views to make sure the groups only go to the views that are for them.
|
How to handle user mangement in Django for groups that has same access but different rules?
|
Background information:
I have created an internal site for a company. Most of the work has gone into making calculation tools that their sale persons can use to make offers for clients. Create pdf offers and contracts that can be downloaded, compare prices etc. All of this is working fine.
Now their sale persons have been divided into two groups.
One group is sale personal that is hired by the company.
The other group is persons a company themselves.
The question:
My challenge now is, that I in some cases need to display different things depending on the type of sales person. Some of the rules for the calculation tools will have different rules as to which numbers will be allowed etc. But a big part of the site will still be the same for both groups.
What I would like to know, is if there is a good way of handling this problem?
My own thoughts:
I thought about managing this by using the groups that is available in contrib.auth. That way I could keep a single code base, but would have to make rules a lot of different places. Rules for validating forms to check if the numbers entered is allowed, will depend on the group the user is in. Some things will have different names, or the workflow might be a bit different. Some tools will only be available to one of the groups. This seems like a quick solution here and now, but if the two groups will need to change more and more, it seems like this would quickly become hard to manage.
I also thought about making two different sites. The idea here was to create apps that both groups use, so I only would need to make the code for that 1 place. Then I could make the custom parts for each site and wouldn't need to check for the user in most templates and views. But I'm not sure if this is a good way to go about things. It will create a lot of extra work, and if the two groups can use a lot of the same code, this might not really be needed.
The biggest concern is that I don't really know how this evolve, so it could end up with the two groups being entire different or with only very few differences. What I would like to do, is write some code that can support both scenarios so I wont end up regretting my choice a half year from now.
So, how do you handle this case of user management. I'm looking for ideas techniques or reusable apps that address this problem, not a ready made solution.
Clarifications:
My issue is not pure presentation that can be done with templates, but also that certain calculation tools (a form that is filled out) will have different rules/validation applied to them, and in some cases the calculations done will also be different. So they might see the same form, but wont be allowed to enter the same numbers, and the same numbers might not give the same result.
|
[
"you could use proxy models on the Group and User models that come packed with django.\nthen write your authorization and calculation methods inside the proxy model. if a new group is added later, you only need to add/change the methods inside of those two proxy models. then make every instance of Group and User (obviously only where necessary, not literally every one) find the proxy model instead of the actual contrib model.\n",
"If I'm understanding you correctly, it seems like you want to have two different groups have access to all the same views, but they will see different numbers. You can achieve this effect by making separate templates for the different groups, and then loading the appropriate template for each view depending on the group of the current user.\nSimilarly you can use a context processor to put the current group into the context for every view, and then put conditionals in the templates to select which numbers to show.\nThe other option is to have two separate sets of views for the two different groups. Then use decorators on the views to make sure the groups only go to the views that are for them.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python",
"user_management"
] |
stackoverflow_0002311094_django_python_user_management.txt
|
Q:
Using Javascript to change all textareas in an html page
I am creating a project in Django, and I am using the Django Admin pages along with TinyMCE. But I would like to be able to toggle TinyMCE on and off like in this example:
http://tinymce.moxiecode.com/examples/example_01.php
but since the admin page is generated automatically I imagine I need to overide the base_site.html template which I can do. But my question is "Is there any way I can have something like -- if is textarea ..... -- in javascript?"
Thanks
A:
You can use
document.getElementsByTagName("textarea")
to return an array of all the <textarea/> elements. Then iterate over it and do with it as you will.
|
Using Javascript to change all textareas in an html page
|
I am creating a project in Django, and I am using the Django Admin pages along with TinyMCE. But I would like to be able to toggle TinyMCE on and off like in this example:
http://tinymce.moxiecode.com/examples/example_01.php
but since the admin page is generated automatically I imagine I need to overide the base_site.html template which I can do. But my question is "Is there any way I can have something like -- if is textarea ..... -- in javascript?"
Thanks
|
[
"You can use\ndocument.getElementsByTagName(\"textarea\")\n\nto return an array of all the <textarea/> elements. Then iterate over it and do with it as you will.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"django_admin",
"javascript",
"python"
] |
stackoverflow_0002311718_django_django_admin_javascript_python.txt
|
Q:
Slicing at runtime
can someone explain me how to slice a numpy.array at runtime?
I don't know the rank (number of dimensions) at 'coding time'.
A minimal example:
import numpy as np
a = np.arange(16).reshape(4,4) # 2D matrix
targetsize = [2,3] # desired shape
b_correct = dynSlicing(a, targetsize)
b_wrong = np.resize(a, targetsize)
print a
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
print b_correct
[[0 1 2]
[4 5 6]]
print b_wrong
[[0 1 2]
[3 4 5]]
And my ugly dynSlicing():
def dynSlicing(data, targetsize):
ndims = len(targetsize)
if(ndims==1):
return data[:targetsize[0]],
elif(ndims==2):
return data[:targetsize[0], :targetsize[1]]
elif(ndims==3):
return data[:targetsize[0], :targetsize[1], :targetsize[2]]
elif(ndims==4):
return data[:targetsize[0], :targetsize[1], :targetsize[2], :targetsize[3]]
Resize() will not do the job since it flats the array before dropping elements.
Thanks,
Tebas
A:
Passing a tuple of slice objects does the job:
def dynSlicing(data, targetsize):
return data[tuple(slice(x) for x in targetsize)]
A:
Simple solution:
b = a[tuple(map(slice,targetsize))]
A:
You can directly 'change' it. This is due to the nature of arrays only allowing backdrop.
Instead you can copy a section, or even better create a view of the desired shape:
http://www.scipy.org/Tentative_NumPy_Tutorial#head-1529ae93dd5d431ffe3a1001a4ab1a394e70a5f2
|
Slicing at runtime
|
can someone explain me how to slice a numpy.array at runtime?
I don't know the rank (number of dimensions) at 'coding time'.
A minimal example:
import numpy as np
a = np.arange(16).reshape(4,4) # 2D matrix
targetsize = [2,3] # desired shape
b_correct = dynSlicing(a, targetsize)
b_wrong = np.resize(a, targetsize)
print a
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
print b_correct
[[0 1 2]
[4 5 6]]
print b_wrong
[[0 1 2]
[3 4 5]]
And my ugly dynSlicing():
def dynSlicing(data, targetsize):
ndims = len(targetsize)
if(ndims==1):
return data[:targetsize[0]],
elif(ndims==2):
return data[:targetsize[0], :targetsize[1]]
elif(ndims==3):
return data[:targetsize[0], :targetsize[1], :targetsize[2]]
elif(ndims==4):
return data[:targetsize[0], :targetsize[1], :targetsize[2], :targetsize[3]]
Resize() will not do the job since it flats the array before dropping elements.
Thanks,
Tebas
|
[
"Passing a tuple of slice objects does the job:\ndef dynSlicing(data, targetsize):\n return data[tuple(slice(x) for x in targetsize)]\n\n",
"Simple solution:\nb = a[tuple(map(slice,targetsize))]\n\n",
"You can directly 'change' it. This is due to the nature of arrays only allowing backdrop.\nInstead you can copy a section, or even better create a view of the desired shape:\nhttp://www.scipy.org/Tentative_NumPy_Tutorial#head-1529ae93dd5d431ffe3a1001a4ab1a394e70a5f2\n"
] |
[
6,
2,
1
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002311578_numpy_python.txt
|
Q:
python twisted stdio multiple connections to a server with a command prompt for interaction
I have written a simple twisted application that connects to a server that listens on 1 or more ports. The twisted app connects to this server and usually connects to a few of the open ports at a time. This server is a serial logger that connects to serial devices and provides the serial line information through a raw TCP Socket and I need to log all this data to disk.
My current app logs any received information to disk without issue.
What I now need to do but am unable to make progress on is add the ability to interact with my application through stdin. I need to be able to issue commands to the local application but also send text commands through the connected sockets.
I have a basic prompt using basic.LineReceiver and adding this to my reactor but can't figure out how to send the data to the server or even if this is the correct way of doing this.
A simplified example would be helpful to show what I need to do.
Thanks
J
A:
To add an interactive console to your Twisted app, see this article -- it explains how to use twisted.internet.stdio for the purpose.
|
python twisted stdio multiple connections to a server with a command prompt for interaction
|
I have written a simple twisted application that connects to a server that listens on 1 or more ports. The twisted app connects to this server and usually connects to a few of the open ports at a time. This server is a serial logger that connects to serial devices and provides the serial line information through a raw TCP Socket and I need to log all this data to disk.
My current app logs any received information to disk without issue.
What I now need to do but am unable to make progress on is add the ability to interact with my application through stdin. I need to be able to issue commands to the local application but also send text commands through the connected sockets.
I have a basic prompt using basic.LineReceiver and adding this to my reactor but can't figure out how to send the data to the server or even if this is the correct way of doing this.
A simplified example would be helpful to show what I need to do.
Thanks
J
|
[
"To add an interactive console to your Twisted app, see this article -- it explains how to use twisted.internet.stdio for the purpose.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"stdio",
"twisted",
"user_interface"
] |
stackoverflow_0002311844_python_stdio_twisted_user_interface.txt
|
Q:
Django efficiency question
I am wondering would this make any real efficieny difference (ie computation time, memory etc..)
This is my model:
class FooUser(models.Model):
name = models.CharField(max_length=50)
sirname = models.CharField(max_length=50)
Assume I have 2 different approaches while saving a FooUser at a view:
First one, assigning retrieved values to a variable and pass it to the object after that.
#say I retrieve name and sirname from users cookie.(lets not care for the exceptions for now.
input_name =request.session['name']
input_sirname =request.session['sirname']
FooUser(name=input_name,sirname=input_sirname).save()
Second one, directly passing as parameter:
#say I retrieve name and sirname from users cookie.(lets not care for the exceptions for now.
FooUser(name=request.session['name'],sirname=request.session['sirname']).save()
I know this question can be a little stupid but for long inputs, passing these inputs to the object makes the code almost unreadable :)
A:
This:
input_name =request.session['name']
input_sirname =request.session['sirname']
is not copying strings to variables. It's only assigning pointers to string objects to names in local dictionary (input_name, input_sirname). For better explanation you can take a loot at this: http://effbot.org/zone/python-objects.htm.
Writing this, having those intermediate dictionary entries (input_name, input_sirname) has such low overhead in 99,999% of cases, that I bet you have some other bottlenecks in your program you should focus on.
And remember: premature optimization is the root of all evil :-)
A:
The time required to bind a local name to a value, as in, e.g., input_name = request.session['name'], is absolutely negligible compared to the time executing .save() itself will take -- you'll never be able to measure it. So, forget such small efficiencies and focus on style, robustness, maintainability (which are fine in both cases in your example) -- if and when you need to tune your application for speed, start by profiling it.
A:
I would argue that the second method (with passing request.session elements directly) is more readable. Looking at the code I know immediately what's going on - it's creating an object using raw, unmodified session data. Had it been just a variable I wouldn't know where it comes from, had it been modified in the meantime etc. I would have to read much larger portion of the code. You can split the statement over multiple lines.
FooUser(
name=request.session['name'],
sirname=request.session['sirname']
).save()
|
Django efficiency question
|
I am wondering would this make any real efficieny difference (ie computation time, memory etc..)
This is my model:
class FooUser(models.Model):
name = models.CharField(max_length=50)
sirname = models.CharField(max_length=50)
Assume I have 2 different approaches while saving a FooUser at a view:
First one, assigning retrieved values to a variable and pass it to the object after that.
#say I retrieve name and sirname from users cookie.(lets not care for the exceptions for now.
input_name =request.session['name']
input_sirname =request.session['sirname']
FooUser(name=input_name,sirname=input_sirname).save()
Second one, directly passing as parameter:
#say I retrieve name and sirname from users cookie.(lets not care for the exceptions for now.
FooUser(name=request.session['name'],sirname=request.session['sirname']).save()
I know this question can be a little stupid but for long inputs, passing these inputs to the object makes the code almost unreadable :)
|
[
"This:\n input_name =request.session['name']\n input_sirname =request.session['sirname']\n\nis not copying strings to variables. It's only assigning pointers to string objects to names in local dictionary (input_name, input_sirname). For better explanation you can take a loot at this: http://effbot.org/zone/python-objects.htm.\nWriting this, having those intermediate dictionary entries (input_name, input_sirname) has such low overhead in 99,999% of cases, that I bet you have some other bottlenecks in your program you should focus on.\nAnd remember: premature optimization is the root of all evil :-)\n",
"The time required to bind a local name to a value, as in, e.g., input_name = request.session['name'], is absolutely negligible compared to the time executing .save() itself will take -- you'll never be able to measure it. So, forget such small efficiencies and focus on style, robustness, maintainability (which are fine in both cases in your example) -- if and when you need to tune your application for speed, start by profiling it.\n",
"I would argue that the second method (with passing request.session elements directly) is more readable. Looking at the code I know immediately what's going on - it's creating an object using raw, unmodified session data. Had it been just a variable I wouldn't know where it comes from, had it been modified in the meantime etc. I would have to read much larger portion of the code. You can split the statement over multiple lines.\nFooUser(\n name=request.session['name'],\n sirname=request.session['sirname']\n).save()\n\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"django",
"performance",
"python"
] |
stackoverflow_0002311251_django_performance_python.txt
|
Q:
Attempting to use gevent library in Python: "ImportError: cannot import name core"
I'm attempting to use the gevent library in a Python app I'm writing. However, both easy_install and installing it manually appears to be failing. Any suggestions?
Python 2.6.2 (r262:71600, Aug 5 2009, 10:31:21)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gevent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gevent/__init__.py", line 28, in <module>
from gevent.greenlet import Greenlet, joinall, killall
File "gevent/greenlet.py", line 5, in <module>
from gevent import core
ImportError: cannot import name core
>>>
The complete dump of my "build" and "install" commands are:
(env)[root@test1:downloads/gevent-0.10.0]# python setup.py build (02-20 16:00)
found system libevent for linux2
running build
running build_py
creating build/lib.linux-i686-2.6
creating build/lib.linux-i686-2.6/gevent
copying gevent/rawgreenlet.py -> build/lib.linux-i686-2.6/gevent
copying gevent/thread.py -> build/lib.linux-i686-2.6/gevent
copying gevent/greenlet.py -> build/lib.linux-i686-2.6/gevent
copying gevent/event.py -> build/lib.linux-i686-2.6/gevent
copying gevent/hub.py -> build/lib.linux-i686-2.6/gevent
copying gevent/util.py -> build/lib.linux-i686-2.6/gevent
copying gevent/monkey.py -> build/lib.linux-i686-2.6/gevent
copying gevent/__init__.py -> build/lib.linux-i686-2.6/gevent
copying gevent/coros.py -> build/lib.linux-i686-2.6/gevent
copying gevent/select.py -> build/lib.linux-i686-2.6/gevent
copying gevent/wsgi.py -> build/lib.linux-i686-2.6/gevent
copying gevent/socket.py -> build/lib.linux-i686-2.6/gevent
copying gevent/queue.py -> build/lib.linux-i686-2.6/gevent
copying gevent/pool.py -> build/lib.linux-i686-2.6/gevent
copying gevent/timeout.py -> build/lib.linux-i686-2.6/gevent
copying gevent/backdoor.py -> build/lib.linux-i686-2.6/gevent
copying gevent/proc.py -> build/lib.linux-i686-2.6/gevent
running build_ext
building 'gevent.core' extension
creating build/temp.linux-i686-2.6
creating build/temp.linux-i686-2.6/gevent
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.6 -c gevent/core.c -o build/temp.linux-i686-2.6/gevent/core.o
gevent/core.c: In function ‘__pyx_pf_6gevent_4core_get_header_version’:
gevent/core.c:4360: warning: label ‘__pyx_L1_error’ defined but not used
gevent/core.c: In function ‘__pyx_pf_6gevent_4core_reinit’:
gevent/core.c:4419: warning: label ‘__pyx_L1_error’ defined but not used
gcc -pthread -shared build/temp.linux-i686-2.6/gevent/core.o -levent -o build/lib.linux-i686-2.6/gevent/core.so
(env)[root@test1:downloads/gevent-0.10.0]# python setup.py install (02-20 16:01)
found system libevent for linux2
running install
running build
running build_py
running build_ext
running install_lib
creating /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/rawgreenlet.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/thread.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/greenlet.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/event.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/hub.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/util.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/monkey.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/__init__.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/coros.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/select.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/wsgi.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/socket.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/queue.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/pool.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/timeout.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/backdoor.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/proc.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/core.so -> /ews/test_project/env/lib/python2.6/site-packages/gevent
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/rawgreenlet.py to rawgreenlet.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/thread.py to thread.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/greenlet.py to greenlet.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/event.py to event.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/hub.py to hub.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/util.py to util.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/monkey.py to monkey.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/__init__.py to __init__.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/coros.py to coros.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/select.py to select.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/wsgi.py to wsgi.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/socket.py to socket.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/queue.py to queue.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/pool.py to pool.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/timeout.py to timeout.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/backdoor.py to backdoor.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/proc.py to proc.pyc
running install_egg_info
Writing /ews/test_project/env/lib/python2.6/site-packages/gevent-0.10.0-py2.6.egg-info
(env)[root@test1:downloads/gevent-0.10.0]# python (02-20 16:01)
Python 2.6.2 (r262:71600, Aug 5 2009, 10:31:21)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gevent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gevent/__init__.py", line 28, in <module>
from gevent.greenlet import Greenlet, joinall, killall
File "gevent/greenlet.py", line 5, in <module>
from gevent import core
ImportError: cannot import name core
>>>
A:
The error was caused simply by trying to run a script from the project source directory. Changing to any other directory and doing an "import" worked fine. More information here on the gevent mailing list.
A:
I've answered your question on the mailing list.
BTW, are you using version 0.10.0 of gevent? It's ancient! The latest one is 0.12.0.
|
Attempting to use gevent library in Python: "ImportError: cannot import name core"
|
I'm attempting to use the gevent library in a Python app I'm writing. However, both easy_install and installing it manually appears to be failing. Any suggestions?
Python 2.6.2 (r262:71600, Aug 5 2009, 10:31:21)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gevent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gevent/__init__.py", line 28, in <module>
from gevent.greenlet import Greenlet, joinall, killall
File "gevent/greenlet.py", line 5, in <module>
from gevent import core
ImportError: cannot import name core
>>>
The complete dump of my "build" and "install" commands are:
(env)[root@test1:downloads/gevent-0.10.0]# python setup.py build (02-20 16:00)
found system libevent for linux2
running build
running build_py
creating build/lib.linux-i686-2.6
creating build/lib.linux-i686-2.6/gevent
copying gevent/rawgreenlet.py -> build/lib.linux-i686-2.6/gevent
copying gevent/thread.py -> build/lib.linux-i686-2.6/gevent
copying gevent/greenlet.py -> build/lib.linux-i686-2.6/gevent
copying gevent/event.py -> build/lib.linux-i686-2.6/gevent
copying gevent/hub.py -> build/lib.linux-i686-2.6/gevent
copying gevent/util.py -> build/lib.linux-i686-2.6/gevent
copying gevent/monkey.py -> build/lib.linux-i686-2.6/gevent
copying gevent/__init__.py -> build/lib.linux-i686-2.6/gevent
copying gevent/coros.py -> build/lib.linux-i686-2.6/gevent
copying gevent/select.py -> build/lib.linux-i686-2.6/gevent
copying gevent/wsgi.py -> build/lib.linux-i686-2.6/gevent
copying gevent/socket.py -> build/lib.linux-i686-2.6/gevent
copying gevent/queue.py -> build/lib.linux-i686-2.6/gevent
copying gevent/pool.py -> build/lib.linux-i686-2.6/gevent
copying gevent/timeout.py -> build/lib.linux-i686-2.6/gevent
copying gevent/backdoor.py -> build/lib.linux-i686-2.6/gevent
copying gevent/proc.py -> build/lib.linux-i686-2.6/gevent
running build_ext
building 'gevent.core' extension
creating build/temp.linux-i686-2.6
creating build/temp.linux-i686-2.6/gevent
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.6 -c gevent/core.c -o build/temp.linux-i686-2.6/gevent/core.o
gevent/core.c: In function ‘__pyx_pf_6gevent_4core_get_header_version’:
gevent/core.c:4360: warning: label ‘__pyx_L1_error’ defined but not used
gevent/core.c: In function ‘__pyx_pf_6gevent_4core_reinit’:
gevent/core.c:4419: warning: label ‘__pyx_L1_error’ defined but not used
gcc -pthread -shared build/temp.linux-i686-2.6/gevent/core.o -levent -o build/lib.linux-i686-2.6/gevent/core.so
(env)[root@test1:downloads/gevent-0.10.0]# python setup.py install (02-20 16:01)
found system libevent for linux2
running install
running build
running build_py
running build_ext
running install_lib
creating /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/rawgreenlet.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/thread.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/greenlet.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/event.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/hub.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/util.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/monkey.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/__init__.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/coros.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/select.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/wsgi.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/socket.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/queue.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/pool.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/timeout.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/backdoor.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/proc.py -> /ews/test_project/env/lib/python2.6/site-packages/gevent
copying build/lib.linux-i686-2.6/gevent/core.so -> /ews/test_project/env/lib/python2.6/site-packages/gevent
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/rawgreenlet.py to rawgreenlet.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/thread.py to thread.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/greenlet.py to greenlet.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/event.py to event.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/hub.py to hub.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/util.py to util.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/monkey.py to monkey.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/__init__.py to __init__.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/coros.py to coros.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/select.py to select.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/wsgi.py to wsgi.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/socket.py to socket.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/queue.py to queue.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/pool.py to pool.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/timeout.py to timeout.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/backdoor.py to backdoor.pyc
byte-compiling /ews/test_project/env/lib/python2.6/site-packages/gevent/proc.py to proc.pyc
running install_egg_info
Writing /ews/test_project/env/lib/python2.6/site-packages/gevent-0.10.0-py2.6.egg-info
(env)[root@test1:downloads/gevent-0.10.0]# python (02-20 16:01)
Python 2.6.2 (r262:71600, Aug 5 2009, 10:31:21)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gevent
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gevent/__init__.py", line 28, in <module>
from gevent.greenlet import Greenlet, joinall, killall
File "gevent/greenlet.py", line 5, in <module>
from gevent import core
ImportError: cannot import name core
>>>
|
[
"The error was caused simply by trying to run a script from the project source directory. Changing to any other directory and doing an \"import\" worked fine. More information here on the gevent mailing list.\n",
"I've answered your question on the mailing list.\nBTW, are you using version 0.10.0 of gevent? It's ancient! The latest one is 0.12.0.\n"
] |
[
1,
0
] |
[] |
[] |
[
"gevent",
"python"
] |
stackoverflow_0002303745_gevent_python.txt
|
Q:
Scheduling Python Programs
How would you go about a having a function check something every ten minutes?
I would like to check a directory for new files every ten minutes. I know python has a time library but can it be used for this?
A:
The sched module is worth a look.
A:
time.sleep:
time.sleep(10*60)
you might want to look into cron or Scheduled Tasks services of the OS.
A:
for checking of files, you may want to try pyinotify
|
Scheduling Python Programs
|
How would you go about a having a function check something every ten minutes?
I would like to check a directory for new files every ten minutes. I know python has a time library but can it be used for this?
|
[
"The sched module is worth a look.\n",
"time.sleep:\ntime.sleep(10*60)\n\nyou might want to look into cron or Scheduled Tasks services of the OS.\n",
"for checking of files, you may want to try pyinotify\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"time"
] |
stackoverflow_0002312314_python_python_3.x_time.txt
|
Q:
python string interpolation
What could generate the following behavior ?
>>> print str(msg)
my message
>>> print unicode(msg)
my message
But:
>>> print '%s' % msg
another message
More info:
my msg object is inherited from unicode.
the methods __str__/__unicode__/__repr__ methods were overridden to return the string 'my message'.
the msg object was initialised with the string 'another message'.
this is running on python 2.5
the variable msg was not changed between the tests
this is actually real doctest that is really giving these results.
I would like an solution that matches this doctest, with minimal fuss (especially around the actual inheritance):
>>> print '%s' % msg
my message
Thanks for all suggestions.
I don't feel this will help more, but for curious readers (and adventurous pythonist), here's the implementation of the object:
class Message(zope.i18nmessageid.Message):
def __repr__(self):
return repr(zope.i18n.interpolate(self.default, self.mapping))
def __str__(self):
return zope.i18n.interpolate(self.default, self.mapping)
def __unicode__(self):
return zope.i18n.interpolate(self.default, self.mapping)
This is how we create the object msg:
>>> msg = Message('another message', 'mydomain', default='my message')
Zope packages version and code used are:
zope.i18n-3.4.0 (interpolation() method code )
zope.i18nmessageid-3.4.3 (Message class code)
EDIT INFO:
added/updated the names of the methods that were overriden
added some more info (python version, and minor info)
updated some wrong info (the class of `msg` is based on `unicode` class and not `basestring`)
added the actual implementation of the class used
A:
Update 2: Please find the original answer, including a simple example of a class exhibiting the behaviour described by the OP, below the horizontal bar. As for what I was able to surmise in the course of my inquiry into Python's sources (v. 2.6.4):
The file Include/unicodeobject.h contains the following to lines (nos. 436-7 in my (somewhat old) checkout):
#define PyUnicode_AS_UNICODE(op) \
(((PyUnicodeObject *)(op))->str)
This is used all over the place in the formatting code, which, as far as I can tell, means that during string formatting, any object which inherits from unicode will be reached into so that its unicode string buffer may be used directly, without calling any Python methods. Which is good as far as performance is concerned, I'm sure (and very much in line with Juergen's conjecture in a comment on this answer).
For the OP's question, this probably means that making things work the way the OP would like them to may only be possible if something like Anurag Uniyal's wrapper class idea is acceptable for this particular use case. If it isn't, the only thing which comes to my mind now is to wrap objects of this class in str / unicode wherever their being interpolated into a string... ugh. (I sincerely hope I'm just missing a cleaner solution which someone will point out in a minute!)
(Update: This was posted about a minute before the OP included the code of his class, but I'm leaving it here anyway (1) for the conjecture / initial attempt at an explanation below the code, (2) for a simple example of how to produce this behaviour (Anurag Uniyal has since provided another one calling unicode's constructor directly, as opposed to via super), (3) in hope of later being able to edit in something to help the OP in obtaining the desired behaviour.)
Here's an example of a class which actually works like what the OP describes (Python 2.6.4, it does produce a deprecation warning -- /usr/bin/ipython:3: DeprecationWarning: object.__init__() takes no parameters):
class Foo(unicode):
def __init__(self, msg):
super(unicode, self).__init__(msg)
def __str__(self): return 'str msg'
def __repr__(self): return 'repr msg'
def __unicode__(self): return u'unicode msg'
A couple of interactions in IPython:
In [12]: print(Foo("asdf"))
asdf
In [13]: str(Foo("asdf"))
Out[13]: 'str msg'
In [14]: print str(Foo("asdf"))
-------> print(str(Foo("asdf")))
str msg
In [15]: print(str(Foo("asdf")))
str msg
In [16]: print('%s' % Foo("asdf"))
asdf
Apparently string interpolation treats this object as an instance of unicode (directly calling the unicode implementation of __str__), whereas the other functions treat it as an instance of Foo. How this happens internally and why it works like this and whether it's a bug or a feature, I really don't know.
As for how to fix the OP's object... Well, how would I know without seeing its code??? Give me the code and I promise to think about it! Ok, I'm thinking about it... No ideas so far.
A:
So problem is class like to something below behaves weirdly
class Msg(unicode):
def __init__(self, s):
unicode.__init__(self, s)
__unicode__ = __repr__ = __str__ = lambda self: "my message"
msg = Msg("another message")
print str(msg)
print unicode(msg)
print "%s"%msg
this prints
my message
my message
another message
I am not sure why this happens or how to fix it, but a very crude attempt by wrapping Msg, but not sure it will help in OP's problem
class MsgX(object):
def __init__(self, s):
self._msg = Msg(s)
__unicode__ = __repr__ = __str__ = lambda self: repr(self._msg)
msg = MsgX("another message")
print str(msg)
print unicode(msg)
print "%s"%msg
output:
my message
my message
my message
A:
I think your problem is that you are trying to extend a built-in. Magic __ methods don't get called for builtins. I think you will have to do some kind of wrap-and-delegate, like this (untested) (maybe Anurag beat me to the punch):
class Message(object):
def __init__(self, strvalue, domain, default='my message'):
self.msg = zope.i18nmessageid.Message(strvalue,domain,default)
def __getattr__(self,attr):
return getattr(self.msg,attr)
def __repr__(self):
return repr(zope.i18n.interpolate(self.msg.default, self.msg.mapping))
def __str__(self):
return zope.i18n.interpolate(self.msg.default, self.msg.mapping)
def __unicode__(self):
return zope.i18n.interpolate(self.msg.default, self.msg.mapping)
Update 1 - it seems that __ methods do get called for subclasses of builtins
>>> class Z(int):
... def __add__(self,other): return self*other
... def __str__(self): return "***"
...
>>> a = Z(100)
>>> a + 2
200
>>> a
100
>>> str(a)
'***'
>>> "%s" % a
'***'
So there is definitely some inconsistency going on...
|
python string interpolation
|
What could generate the following behavior ?
>>> print str(msg)
my message
>>> print unicode(msg)
my message
But:
>>> print '%s' % msg
another message
More info:
my msg object is inherited from unicode.
the methods __str__/__unicode__/__repr__ methods were overridden to return the string 'my message'.
the msg object was initialised with the string 'another message'.
this is running on python 2.5
the variable msg was not changed between the tests
this is actually real doctest that is really giving these results.
I would like an solution that matches this doctest, with minimal fuss (especially around the actual inheritance):
>>> print '%s' % msg
my message
Thanks for all suggestions.
I don't feel this will help more, but for curious readers (and adventurous pythonist), here's the implementation of the object:
class Message(zope.i18nmessageid.Message):
def __repr__(self):
return repr(zope.i18n.interpolate(self.default, self.mapping))
def __str__(self):
return zope.i18n.interpolate(self.default, self.mapping)
def __unicode__(self):
return zope.i18n.interpolate(self.default, self.mapping)
This is how we create the object msg:
>>> msg = Message('another message', 'mydomain', default='my message')
Zope packages version and code used are:
zope.i18n-3.4.0 (interpolation() method code )
zope.i18nmessageid-3.4.3 (Message class code)
EDIT INFO:
added/updated the names of the methods that were overriden
added some more info (python version, and minor info)
updated some wrong info (the class of `msg` is based on `unicode` class and not `basestring`)
added the actual implementation of the class used
|
[
"Update 2: Please find the original answer, including a simple example of a class exhibiting the behaviour described by the OP, below the horizontal bar. As for what I was able to surmise in the course of my inquiry into Python's sources (v. 2.6.4):\nThe file Include/unicodeobject.h contains the following to lines (nos. 436-7 in my (somewhat old) checkout):\n#define PyUnicode_AS_UNICODE(op) \\ \n (((PyUnicodeObject *)(op))->str)\n\nThis is used all over the place in the formatting code, which, as far as I can tell, means that during string formatting, any object which inherits from unicode will be reached into so that its unicode string buffer may be used directly, without calling any Python methods. Which is good as far as performance is concerned, I'm sure (and very much in line with Juergen's conjecture in a comment on this answer).\nFor the OP's question, this probably means that making things work the way the OP would like them to may only be possible if something like Anurag Uniyal's wrapper class idea is acceptable for this particular use case. If it isn't, the only thing which comes to my mind now is to wrap objects of this class in str / unicode wherever their being interpolated into a string... ugh. (I sincerely hope I'm just missing a cleaner solution which someone will point out in a minute!)\n\n(Update: This was posted about a minute before the OP included the code of his class, but I'm leaving it here anyway (1) for the conjecture / initial attempt at an explanation below the code, (2) for a simple example of how to produce this behaviour (Anurag Uniyal has since provided another one calling unicode's constructor directly, as opposed to via super), (3) in hope of later being able to edit in something to help the OP in obtaining the desired behaviour.)\nHere's an example of a class which actually works like what the OP describes (Python 2.6.4, it does produce a deprecation warning -- /usr/bin/ipython:3: DeprecationWarning: object.__init__() takes no parameters):\nclass Foo(unicode):\n def __init__(self, msg):\n super(unicode, self).__init__(msg)\n def __str__(self): return 'str msg'\n def __repr__(self): return 'repr msg'\n def __unicode__(self): return u'unicode msg'\n\nA couple of interactions in IPython:\nIn [12]: print(Foo(\"asdf\"))\nasdf\n\nIn [13]: str(Foo(\"asdf\"))\nOut[13]: 'str msg'\n\nIn [14]: print str(Foo(\"asdf\"))\n-------> print(str(Foo(\"asdf\")))\nstr msg\n\nIn [15]: print(str(Foo(\"asdf\")))\nstr msg\n\nIn [16]: print('%s' % Foo(\"asdf\"))\nasdf\n\nApparently string interpolation treats this object as an instance of unicode (directly calling the unicode implementation of __str__), whereas the other functions treat it as an instance of Foo. How this happens internally and why it works like this and whether it's a bug or a feature, I really don't know.\nAs for how to fix the OP's object... Well, how would I know without seeing its code??? Give me the code and I promise to think about it! Ok, I'm thinking about it... No ideas so far.\n",
"So problem is class like to something below behaves weirdly\nclass Msg(unicode):\n def __init__(self, s):\n unicode.__init__(self, s)\n\n __unicode__ = __repr__ = __str__ = lambda self: \"my message\"\n\nmsg = Msg(\"another message\")\nprint str(msg)\nprint unicode(msg)\nprint \"%s\"%msg\n\nthis prints\nmy message\nmy message\nanother message\n\nI am not sure why this happens or how to fix it, but a very crude attempt by wrapping Msg, but not sure it will help in OP's problem\nclass MsgX(object):\n def __init__(self, s):\n self._msg = Msg(s)\n\n __unicode__ = __repr__ = __str__ = lambda self: repr(self._msg)\n\nmsg = MsgX(\"another message\")\nprint str(msg)\nprint unicode(msg)\nprint \"%s\"%msg\n\noutput:\nmy message\nmy message\nmy message\n\n",
"I think your problem is that you are trying to extend a built-in. Magic __ methods don't get called for builtins. I think you will have to do some kind of wrap-and-delegate, like this (untested) (maybe Anurag beat me to the punch):\nclass Message(object): \n\n def __init__(self, strvalue, domain, default='my message'):\n self.msg = zope.i18nmessageid.Message(strvalue,domain,default)\n\n def __getattr__(self,attr):\n return getattr(self.msg,attr)\n\n def __repr__(self): \n return repr(zope.i18n.interpolate(self.msg.default, self.msg.mapping)) \n\n def __str__(self): \n return zope.i18n.interpolate(self.msg.default, self.msg.mapping) \n\n def __unicode__(self): \n return zope.i18n.interpolate(self.msg.default, self.msg.mapping) \n\nUpdate 1 - it seems that __ methods do get called for subclasses of builtins\n>>> class Z(int):\n... def __add__(self,other): return self*other\n... def __str__(self): return \"***\"\n...\n>>> a = Z(100)\n>>> a + 2\n200\n>>> a\n100\n>>> str(a)\n'***'\n>>> \"%s\" % a\n'***'\n\nSo there is definitely some inconsistency going on...\n"
] |
[
8,
6,
3
] |
[] |
[] |
[
"python",
"string",
"string_interpolation"
] |
stackoverflow_0002311906_python_string_string_interpolation.txt
|
Q:
QListWidget on freemantle
I have a problem with QListWidget on freemantle (maemo, n900).
I want to use two QListWidget on same window and allow the user to pick on number in each window.
When the user use the second QListWidget, the "blue" color on it disparear.
How to change the color of a item selected in QListWidget which is not active ?
A:
Kind of a hack, but you can change the QPallete of both QListWidgets so that the inactive color is the same as the active color.
http://qt.nokia.com/doc/4.6/qpalette.html#ColorGroup-enum
There is code sample here: http://www.qtcentre.org/threads/17922-two-qlistwidgets that might be of use to you. I don't have access to any mobile Qt-enabled devices to test it out but it should work in theory.
|
QListWidget on freemantle
|
I have a problem with QListWidget on freemantle (maemo, n900).
I want to use two QListWidget on same window and allow the user to pick on number in each window.
When the user use the second QListWidget, the "blue" color on it disparear.
How to change the color of a item selected in QListWidget which is not active ?
|
[
"Kind of a hack, but you can change the QPallete of both QListWidgets so that the inactive color is the same as the active color.\nhttp://qt.nokia.com/doc/4.6/qpalette.html#ColorGroup-enum\nThere is code sample here: http://www.qtcentre.org/threads/17922-two-qlistwidgets that might be of use to you. I don't have access to any mobile Qt-enabled devices to test it out but it should work in theory.\n"
] |
[
2
] |
[] |
[] |
[
"maemo",
"n900",
"python",
"qt"
] |
stackoverflow_0002311739_maemo_n900_python_qt.txt
|
Q:
Different 404 pages depending on the application in Django
We are developing a project with several applications using Django. It shares the database, but it has several applications targeting different very different users. Roughly, administrators and final users. The UI of each application is very different.
I need to create a 404 error page, but seems that I can only create one for all the project. I would like to create different 404 templates and being able to shown them depending on the application (URL) the user is asking for...
For general, clearly invalid URL it's easy, but in the code there are other ways of launching exceptions, like get_object_or_404 calls.
Anyone knows a way of doing that?
A:
It's not at all true that you can only create a single 404 page for the entire app. The documentation explains how you can create a specific 404 handler view, which of course can look at the value of request.path to see what URL was requested and render the relevant template.
A:
Write a 404 view by setting handler404, and not just a template. In that view, try to figure from the url which 404 you should show, and render that.
|
Different 404 pages depending on the application in Django
|
We are developing a project with several applications using Django. It shares the database, but it has several applications targeting different very different users. Roughly, administrators and final users. The UI of each application is very different.
I need to create a 404 error page, but seems that I can only create one for all the project. I would like to create different 404 templates and being able to shown them depending on the application (URL) the user is asking for...
For general, clearly invalid URL it's easy, but in the code there are other ways of launching exceptions, like get_object_or_404 calls.
Anyone knows a way of doing that?
|
[
"It's not at all true that you can only create a single 404 page for the entire app. The documentation explains how you can create a specific 404 handler view, which of course can look at the value of request.path to see what URL was requested and render the relevant template.\n",
"Write a 404 view by setting handler404, and not just a template. In that view, try to figure from the url which 404 you should show, and render that.\n"
] |
[
4,
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002312407_django_python.txt
|
Q:
Python ( or general programming ). Why use <> instead of != and are there risks?
I think if I understand correctly, a <> b is the exact same thing functionally as a != b, and in Python not a == b, but is there reason to use <> over the other versions? I know a common mistake for Python newcomers is to think that not a is b is the same as a != b or not a == b.
Do similar misconceptions occur with <>, or is it exactly the same functionally?
Does it cost more in memory, processor, etc.
A:
<> in Python 2 is an exact synonym for != -- no reason to use it, no disadvantages either except the gratuitous heterogeneity (a style issue). It's been long discouraged, and has now been removed in Python 3.
A:
Just a pedantic note: the <> operator is in some sense misnamed (misdenoted?). a <> b might naturally be interpreted as meaning a < b or a > b (evaluating a and b only once, of course), but since not all orderings are total orderings, this doesn't match the actual semantics. For example, 2.0 != float('nan') is true, but 2.0 < float('nan') or 2.0 > float('nan') is false.
The != operator isn't subject to such possible misinterpretation.
For an interesting take (with poetry!) on the decision to drop <> for Python 3.x, see Requiem for an operator.
A:
you shouldn't use <> in python.
|
Python ( or general programming ). Why use <> instead of != and are there risks?
|
I think if I understand correctly, a <> b is the exact same thing functionally as a != b, and in Python not a == b, but is there reason to use <> over the other versions? I know a common mistake for Python newcomers is to think that not a is b is the same as a != b or not a == b.
Do similar misconceptions occur with <>, or is it exactly the same functionally?
Does it cost more in memory, processor, etc.
|
[
"<> in Python 2 is an exact synonym for != -- no reason to use it, no disadvantages either except the gratuitous heterogeneity (a style issue). It's been long discouraged, and has now been removed in Python 3.\n",
"Just a pedantic note: the <> operator is in some sense misnamed (misdenoted?). a <> b might naturally be interpreted as meaning a < b or a > b (evaluating a and b only once, of course), but since not all orderings are total orderings, this doesn't match the actual semantics. For example, 2.0 != float('nan') is true, but 2.0 < float('nan') or 2.0 > float('nan') is false.\nThe != operator isn't subject to such possible misinterpretation.\nFor an interesting take (with poetry!) on the decision to drop <> for Python 3.x, see Requiem for an operator.\n",
"you shouldn't use <> in python.\n"
] |
[
15,
8,
0
] |
[] |
[] |
[
"operators",
"python"
] |
stackoverflow_0002312169_operators_python.txt
|
Q:
How do I store a dict/list in a database?
If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
A:
Options:
1) Pickling
2) XML
3) JSON
others I am sure. It has a lot to do on how much portability means to you.
A:
Why don't you use some serialization/deserialization from pickle module ?
http://docs.python.org/library/pickle.html
A:
Best, under your stated conditions:
import cPickle
...
thestring = cPickle.dumps(thedict, -1)
the -1 ensures the most efficient serialization and produces a binary string (arbitrary string of bytes). If you need an ascii string (because e.g. some Unicode transcoding is going to happen and you can't switch the field's type from, say, TEXT to BLOB), avoid the -1, but you'll then be less efficient.
To get the dict back later from the string, in either case,
thenewdict = cPickle.loads(thestring)
A:
There are any number of serialization methods out there, JSON is readable, reasonably compact, supported natively, and portable. I prefer it over pickle, since the latter can execute arbitrary code and potentially introduce security holes, and because of its portability.
Depending on your data's layout, you may also be able to use your ORM to directly map the data into database constructs.
A:
You have two options
use a standard serialization format (json, xml, yaml, ...)
pros: you can access with a any language that can parse those formats (on the worst case you can write your own parser)
cons: could be slower to save and load the data (this depends of the implementation mostly)
use cPickle:
pros: easy to use, fast and native python way to do serialization.
cons: only python based apps can have access to the data.
|
How do I store a dict/list in a database?
|
If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
|
[
"Options:\n1) Pickling\n2) XML\n3) JSON\nothers I am sure. It has a lot to do on how much portability means to you.\n",
"Why don't you use some serialization/deserialization from pickle module ?\nhttp://docs.python.org/library/pickle.html\n",
"Best, under your stated conditions:\nimport cPickle\n ...\nthestring = cPickle.dumps(thedict, -1)\n\nthe -1 ensures the most efficient serialization and produces a binary string (arbitrary string of bytes). If you need an ascii string (because e.g. some Unicode transcoding is going to happen and you can't switch the field's type from, say, TEXT to BLOB), avoid the -1, but you'll then be less efficient.\nTo get the dict back later from the string, in either case,\nthenewdict = cPickle.loads(thestring)\n\n",
"There are any number of serialization methods out there, JSON is readable, reasonably compact, supported natively, and portable. I prefer it over pickle, since the latter can execute arbitrary code and potentially introduce security holes, and because of its portability. \nDepending on your data's layout, you may also be able to use your ORM to directly map the data into database constructs.\n",
"You have two options\n\nuse a standard serialization format (json, xml, yaml, ...)\n\npros: you can access with a any language that can parse those formats (on the worst case you can write your own parser)\ncons: could be slower to save and load the data (this depends of the implementation mostly)\n\nuse cPickle:\n\npros: easy to use, fast and native python way to do serialization.\ncons: only python based apps can have access to the data.\n\n\n"
] |
[
4,
3,
2,
2,
1
] |
[] |
[] |
[
"database",
"dictionary",
"list",
"python",
"string"
] |
stackoverflow_0002311223_database_dictionary_list_python_string.txt
|
Q:
Python: using 4 spaces for indentation. Why?
While coding python I'm using only 2 spaces to indent, sure PEP-8 really recommend to have 4 spaces, but historically for me it's unusual.
So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?
P.S. And finally, what's easy way to convert all existing codebase from 2 spaces to 4 spaces?
P.P.S. PEP-8 Also srictly recommend not using tabs for indention. read here
So, to summarize:
Pros:
Have more space to arrange when wraping string more than 80 lines long.
Can copy code from snippets and it just works.
Cons:
With deeper level of nested statements you have less space for actual code.
Thanks.
A:
Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be displayed as different widths, that makes no syntactic difference. The worst that can happen is that some of the comments don't line up. The horror!) but I've accepted that since the python community as a whole uses 4 spaces, I use 4 spaces. This way, I can assemble code from snippets others have written, and it all works.
A:
I like the fact that four space characters nicely indents the inner code of a function, because def + one space makes four characters.
def·foo():
····pass
A:
I think the real question is why spaces and not tabs.
Tabs are clearly better:
It makes nearly impossible to have inconsistent indentation (I've seen code that normally has 4 spaces indents, but then some parts happen to be one space off, it's difficult to tell by simple inspection if there are 7 or 8 spaces... That wouldn't happen with tabs, unless you set your tabstop to 1 space).
Tab is a logical semantic representation for indentation, it allows you (and any other developer) to choose to display as many "spaces" (or rather columns) you want without messing with other people's preferences.
It is also less keystrokes if you happen to have only "notepad" (or other dummy editor) at hand.
Adding and removing tabs is a symmetric operation. Most IDE's may insert automatically 4 spaces when hitting the tab key, but usually they remove just 1 space when hitting backspace (un-indent operation is still accessible as shift-tab, but that's a two key combination) or you use the mouse to click in the middle of the indentation and delete one character.
They take only 1 byte rather than 4 (multiply by thousands of lines and you save a few KB! :p)
You have one less thing to settle an agreement, because if you decide to go for spaces, then the discussion starts again to choose how many (although the consensus seems to be around four).
Advantages of spaces:
Guido likes them.
You cannot easily type a tab here, it transfers the focus (although you can paste one).
A:
There's no "better" indentation. It's a religious holy-war topic. Four is nice because it's enough to make the indentation clear, but not so much that your whole screen is mostly whitespace and you have to scroll horizontally to read half the program.
It also has the upside of being a "half-tab" w/r to the historical definition of a "tab."
Other than that, use whatever your group likes. It's like chocolate vs. vanilla.
An easy way to switch is to use an editor that has tab and space-tab support. Convert all your leading space-tabs to tabs, set the tab size to four, and then convert leading tabs back to space-tabs.
Pretty easy to do with a python script too. Just count all the leading spaces, then add the same amount to the beginning of the line and write it back out.
A:
The PEP isn't the boss of you. If it's already consistently 2-space indented, there's no reason to change all your code to conform to it. You could follow it going forward if you really think it's that vital, but, frankly, I don't. You're better off going with whatever convention provides you (and your coworkers) the most comfort both in reading and writing.
A:
Any decent editor (emacs, vim) will abstract this whole nonsense out for you. It will work equally well with spaces or tabs, and it can be configured to use any number of spaces (or any number of space-widths for a tab character). It can also convert between the different formats without too much trouble (see the :retab command in vim).
If you're trying to convert source formatting in bulk, I recommend you take a look at the indent utility.
That said, I can't resist answering the other question... My preference has always been for tabs, since it bypasses the whole issue and everyone can view the source code with the widths set as they see fit. It's also a lot less typing when you're working in editors that aren't helpful with converting it. As far as 2 vs 4 spaces, that's purely cosmetic.
A:
Also one of reasons is: when you have some long line (longer than 80 symbols) and want to split it in 2 you will have only 1 space to indent, that is a bit confusing:
if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
and someotherstatementhere:
# some code inside if block
pass
if code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \
and someotherstatementhere:
# some code inside if block
pass
A:
If you're the only coder working on your source file and there are no coding standards that enforce a particular style, use whatever you're comfortable with. Personally (and in line with our coding standard), I use hard tabs so that whoever is looking at the code can use their own preference.
To make a change, you simply need to change all start-of-line spaces to ones that are twice as large. There are many ways to do this; in the Vim text editor, I can think of two: firstly:
:%s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)
This is a simple regular expression that looks for one or more pairs of spaces at the start of the line and replaces them with twice as many spaces as were found. It can be extended to do all files by opening vim with:
vim *.py
(or the equivalent), followed by (untested):
:argdo %s/^\(\s\{2}\)\+/\=repeat(' ', len(submatch(0))*2)/ | w
Alternatively:
" Switch to hard tabs:
:set noexpandtab
" Set the tab stop to the current setting
:set tabstop=2
" Change all spaces to tabs based on tabstop
:retab!
" Change the tab stop to the new setting
:set tabstop=4
" Go back to soft tabs
:set expandtab
" Replace all the tabs in the current file to spaces
:retab
Of course, many other tools will offer similar features: I would be surprised if something like sed, awk, perl or python couldn't do this very easily.
A:
Identation and general coding style standards vary from language to language, project to project. There is one reason for adopting a coding style standard: so that the code look uniform, no matter who wrote it. That improves legibility in the project, and, to put it bluntly, it looks better.
There is one reason that is not valid when adopting a coding style standard: because you like it. Coding standards exists precisely because people's preferences vary, and if left to their own, chaos would ensue, to the detriment of all.
If you are writing code for yourself alone, which no one will ever read, go ahead and write it whatever you like. Otherwise, following the accepted standard of your community will make your code much more agreeable to everyone else's eyes. And remember, too, that if you DO decide to contribute code to a community in the future, you'll have an easier time if you are used to their coding style already.
As for changing the tab size, there are are many source code formatters out there which support Python, and most programmer's editors and IDEs also have this capability. You probably have it already, it's just a matter of consulting the documentation for the editor you are using.
A:
It is easier to visually identify long nested code blocks with 4 spaces. Saves time when debugging.
A:
One reason is that if you use less spaces for indentation, you will be able to nest more statements (since line length is normally restricted to 80).
Now I'm pretty sure that some people still disagree on how many nested constructs should be the maximum.
A:
If you want to write python code together with other programmers it becomes a problem if you use a different indention as them.
Most Python programmers tend to use 4-space indention.
A:
using 4 spaces or 2 spaces is entirely up to you. 4 spaces is just a convention. What is most important, don't mix tabs and spaces. Use the space bar
|
Python: using 4 spaces for indentation. Why?
|
While coding python I'm using only 2 spaces to indent, sure PEP-8 really recommend to have 4 spaces, but historically for me it's unusual.
So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?
P.S. And finally, what's easy way to convert all existing codebase from 2 spaces to 4 spaces?
P.P.S. PEP-8 Also srictly recommend not using tabs for indention. read here
So, to summarize:
Pros:
Have more space to arrange when wraping string more than 80 lines long.
Can copy code from snippets and it just works.
Cons:
With deeper level of nested statements you have less space for actual code.
Thanks.
|
[
"Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be displayed as different widths, that makes no syntactic difference. The worst that can happen is that some of the comments don't line up. The horror!) but I've accepted that since the python community as a whole uses 4 spaces, I use 4 spaces. This way, I can assemble code from snippets others have written, and it all works.\n",
"I like the fact that four space characters nicely indents the inner code of a function, because def + one space makes four characters.\ndef·foo():\n····pass\n\n",
"I think the real question is why spaces and not tabs.\nTabs are clearly better:\n\nIt makes nearly impossible to have inconsistent indentation (I've seen code that normally has 4 spaces indents, but then some parts happen to be one space off, it's difficult to tell by simple inspection if there are 7 or 8 spaces... That wouldn't happen with tabs, unless you set your tabstop to 1 space).\nTab is a logical semantic representation for indentation, it allows you (and any other developer) to choose to display as many \"spaces\" (or rather columns) you want without messing with other people's preferences.\nIt is also less keystrokes if you happen to have only \"notepad\" (or other dummy editor) at hand.\nAdding and removing tabs is a symmetric operation. Most IDE's may insert automatically 4 spaces when hitting the tab key, but usually they remove just 1 space when hitting backspace (un-indent operation is still accessible as shift-tab, but that's a two key combination) or you use the mouse to click in the middle of the indentation and delete one character.\nThey take only 1 byte rather than 4 (multiply by thousands of lines and you save a few KB! :p)\nYou have one less thing to settle an agreement, because if you decide to go for spaces, then the discussion starts again to choose how many (although the consensus seems to be around four).\n\nAdvantages of spaces:\n\nGuido likes them.\nYou cannot easily type a tab here, it transfers the focus (although you can paste one).\n\n",
"There's no \"better\" indentation. It's a religious holy-war topic. Four is nice because it's enough to make the indentation clear, but not so much that your whole screen is mostly whitespace and you have to scroll horizontally to read half the program.\nIt also has the upside of being a \"half-tab\" w/r to the historical definition of a \"tab.\"\nOther than that, use whatever your group likes. It's like chocolate vs. vanilla.\nAn easy way to switch is to use an editor that has tab and space-tab support. Convert all your leading space-tabs to tabs, set the tab size to four, and then convert leading tabs back to space-tabs.\nPretty easy to do with a python script too. Just count all the leading spaces, then add the same amount to the beginning of the line and write it back out.\n",
"The PEP isn't the boss of you. If it's already consistently 2-space indented, there's no reason to change all your code to conform to it. You could follow it going forward if you really think it's that vital, but, frankly, I don't. You're better off going with whatever convention provides you (and your coworkers) the most comfort both in reading and writing.\n",
"Any decent editor (emacs, vim) will abstract this whole nonsense out for you. It will work equally well with spaces or tabs, and it can be configured to use any number of spaces (or any number of space-widths for a tab character). It can also convert between the different formats without too much trouble (see the :retab command in vim).\nIf you're trying to convert source formatting in bulk, I recommend you take a look at the indent utility.\nThat said, I can't resist answering the other question... My preference has always been for tabs, since it bypasses the whole issue and everyone can view the source code with the widths set as they see fit. It's also a lot less typing when you're working in editors that aren't helpful with converting it. As far as 2 vs 4 spaces, that's purely cosmetic.\n",
"Also one of reasons is: when you have some long line (longer than 80 symbols) and want to split it in 2 you will have only 1 space to indent, that is a bit confusing:\nif code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \\\n and someotherstatementhere:\n # some code inside if block\n pass\n\nif code80symbolslong and somelongvariablegoeshere and somelongerthan80symbols \\\n and someotherstatementhere:\n # some code inside if block\n pass\n\n",
"If you're the only coder working on your source file and there are no coding standards that enforce a particular style, use whatever you're comfortable with. Personally (and in line with our coding standard), I use hard tabs so that whoever is looking at the code can use their own preference.\nTo make a change, you simply need to change all start-of-line spaces to ones that are twice as large. There are many ways to do this; in the Vim text editor, I can think of two: firstly:\n:%s/^\\(\\s\\{2}\\)\\+/\\=repeat(' ', len(submatch(0))*2)\n\nThis is a simple regular expression that looks for one or more pairs of spaces at the start of the line and replaces them with twice as many spaces as were found. It can be extended to do all files by opening vim with:\nvim *.py\n\n(or the equivalent), followed by (untested):\n:argdo %s/^\\(\\s\\{2}\\)\\+/\\=repeat(' ', len(submatch(0))*2)/ | w\n\nAlternatively:\n\" Switch to hard tabs:\n:set noexpandtab\n\" Set the tab stop to the current setting\n:set tabstop=2\n\" Change all spaces to tabs based on tabstop\n:retab!\n\" Change the tab stop to the new setting\n:set tabstop=4\n\" Go back to soft tabs\n:set expandtab\n\" Replace all the tabs in the current file to spaces\n:retab\n\nOf course, many other tools will offer similar features: I would be surprised if something like sed, awk, perl or python couldn't do this very easily.\n",
"Identation and general coding style standards vary from language to language, project to project. There is one reason for adopting a coding style standard: so that the code look uniform, no matter who wrote it. That improves legibility in the project, and, to put it bluntly, it looks better.\nThere is one reason that is not valid when adopting a coding style standard: because you like it. Coding standards exists precisely because people's preferences vary, and if left to their own, chaos would ensue, to the detriment of all.\nIf you are writing code for yourself alone, which no one will ever read, go ahead and write it whatever you like. Otherwise, following the accepted standard of your community will make your code much more agreeable to everyone else's eyes. And remember, too, that if you DO decide to contribute code to a community in the future, you'll have an easier time if you are used to their coding style already.\nAs for changing the tab size, there are are many source code formatters out there which support Python, and most programmer's editors and IDEs also have this capability. You probably have it already, it's just a matter of consulting the documentation for the editor you are using.\n",
"It is easier to visually identify long nested code blocks with 4 spaces. Saves time when debugging.\n",
"One reason is that if you use less spaces for indentation, you will be able to nest more statements (since line length is normally restricted to 80).\nNow I'm pretty sure that some people still disagree on how many nested constructs should be the maximum.\n",
"If you want to write python code together with other programmers it becomes a problem if you use a different indention as them.\nMost Python programmers tend to use 4-space indention.\n",
"using 4 spaces or 2 spaces is entirely up to you. 4 spaces is just a convention. What is most important, don't mix tabs and spaces. Use the space bar \n"
] |
[
145,
86,
64,
17,
16,
7,
6,
5,
4,
2,
1,
1,
0
] |
[] |
[] |
[
"conventions",
"indentation",
"pep8",
"python"
] |
stackoverflow_0001125653_conventions_indentation_pep8_python.txt
|
Q:
regex for state abbreviations (python)
I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
CA
Ca
The string could be:
Boulder, CO 80303
Boulder, Co
Boulder CO
...
Here is what I have, which obviously doesn't work that well. I'm not very good with regular expressions and google didn't turn up much.
pat = re.compile("[A-Za-z]{2}")
st = pat.search(str)
stateAbb = st.group(0)
A:
A simple and reliable way is to have all the states listed:
states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN', 'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']
regex = re.compile(r'\b(' + '|'.join(states) + r')\b', re.IGNORECASE)
Use another state list if you want non-US states.
A:
re.search(r'\b[a-z]{2}\b', subject, re.I)
it will find double-letter names of towns, though
|
regex for state abbreviations (python)
|
I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
CA
Ca
The string could be:
Boulder, CO 80303
Boulder, Co
Boulder CO
...
Here is what I have, which obviously doesn't work that well. I'm not very good with regular expressions and google didn't turn up much.
pat = re.compile("[A-Za-z]{2}")
st = pat.search(str)
stateAbb = st.group(0)
|
[
"A simple and reliable way is to have all the states listed:\nstates = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN', 'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']\nregex = re.compile(r'\\b(' + '|'.join(states) + r')\\b', re.IGNORECASE)\n\nUse another state list if you want non-US states.\n",
"re.search(r'\\b[a-z]{2}\\b', subject, re.I)\n\nit will find double-letter names of towns, though\n"
] |
[
10,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002313032_python_regex.txt
|
Q:
Python: How to Access Linux Paths
Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.
Thanks
A:
This
import glob, os
glob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))
will give you a list of all files ending in ".default" in the current user's ~/.mozilla/firefox directory using os.path.expanduser to expand the ~ in the path and glob.glob to match the *.default file pattern.
A:
~ is expanded by the shell and not a real path. As such you have to navigate there manually.
import os
homeDir = os.environ['HOME']
f = open( homeDir + '/.mozilla/firefox/*.default' )
# ...
A:
It's important to remember:
use of the tilde ~ expands the home directory as per Poke's answer
use of the forward slash / is the separator for linux / *nix directories
by default, *nix systems such as linux for example has a wild card globbing in the shell, for instance echo *.* will return back all files that match the asterisk dot asterisk (as per Will McCutcheon's answer!)
A:
http://docs.python.org/library/os.html
Gives a complete reference if you would like to change directory or give paths.
You can for example give relative paths and access specific files.
If you would like to execute commands then http://docs.python.org/library/commands.html provides nice wrappers for the os.popen() function
|
Python: How to Access Linux Paths
|
Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.
Thanks
|
[
"This\nimport glob, os\nglob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))\n\nwill give you a list of all files ending in \".default\" in the current user's ~/.mozilla/firefox directory using os.path.expanduser to expand the ~ in the path and glob.glob to match the *.default file pattern.\n",
"~ is expanded by the shell and not a real path. As such you have to navigate there manually.\nimport os\n\nhomeDir = os.environ['HOME']\nf = open( homeDir + '/.mozilla/firefox/*.default' )\n# ...\n\n",
"It's important to remember:\n\nuse of the tilde ~ expands the home directory as per Poke's answer\nuse of the forward slash / is the separator for linux / *nix directories\nby default, *nix systems such as linux for example has a wild card globbing in the shell, for instance echo *.* will return back all files that match the asterisk dot asterisk (as per Will McCutcheon's answer!)\n\n",
"http://docs.python.org/library/os.html\nGives a complete reference if you would like to change directory or give paths.\nYou can for example give relative paths and access specific files.\nIf you would like to execute commands then http://docs.python.org/library/commands.html provides nice wrappers for the os.popen() function\n"
] |
[
9,
2,
2,
1
] |
[] |
[] |
[
"linux",
"path",
"python"
] |
stackoverflow_0002313053_linux_path_python.txt
|
Q:
Default value in a function in Python
I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
A:
Yes, it's correct behavior.
However, from your question, it appears that it's not what you expected.
If you want it to match your expectations, be aware of the following:
Rule 1. Do not use mutable objects as default values.
def anyFunction( arg=[] ):
Will not create a fresh list object. The default list object for arg will be shared all over the place.
Similarly
def anyFunction( arg={} ):
will not create a fresh dict object. This default dict will be shared.
class MyClass( object ):
def __init__( self, arg= None ):
self.myList= [] if arg is None else arg
That's a common way to provide a default argument value that is a fresh, empty list object.
A:
This is a classic pitfall. See http://zephyrfalcon.org/labs/python_pitfalls.html, section 5: "Mutable default arguments"
A:
Always make functions like this then:
def __init__ ( self, data = None ):
if data is None:
data = []
self._data = data
Alternatively you could also use data = data or [], but that prevents the user from passing empty parameters ('', 0, False etc.).
|
Default value in a function in Python
|
I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
|
[
"Yes, it's correct behavior.\nHowever, from your question, it appears that it's not what you expected.\nIf you want it to match your expectations, be aware of the following:\nRule 1. Do not use mutable objects as default values.\ndef anyFunction( arg=[] ):\n\nWill not create a fresh list object. The default list object for arg will be shared all over the place. \nSimilarly\ndef anyFunction( arg={} ):\n\nwill not create a fresh dict object. This default dict will be shared.\nclass MyClass( object ):\n def __init__( self, arg= None ):\n self.myList= [] if arg is None else arg \n\nThat's a common way to provide a default argument value that is a fresh, empty list object.\n",
"This is a classic pitfall. See http://zephyrfalcon.org/labs/python_pitfalls.html, section 5: \"Mutable default arguments\"\n",
"Always make functions like this then:\ndef __init__ ( self, data = None ):\n if data is None:\n data = []\n\n self._data = data\n\nAlternatively you could also use data = data or [], but that prevents the user from passing empty parameters ('', 0, False etc.).\n"
] |
[
12,
4,
1
] |
[] |
[] |
[
"default_value",
"python"
] |
stackoverflow_0002313075_default_value_python.txt
|
Q:
Programming language decision for C++ legacy project workflow
I have quite a lot of C++ legacy code modules from my colleagues, unfortunately poorly written. Each is doing a different job, but they are all GNU C++ code running under Linux.
I want to write a controller program, to make a singular C++ module for a workflow, for a very urgent demo. Also I need to write a front-end web-app allowing clients submitting jobs to the controller.
My main criteria are:
development speed (very urgent demo)
good binding with C++ (I have legacy code I do not want to rewrite in another language)
smooth introduction of new programming language to team (has some python, java and perl knowledge)
What programming language fits my needs best, and why?
Details:
I lean towards python for its perfect binding with C++, as writing JNI is too much work, and kind of obsolete nowadays. However, no one in my team is Python programmer; I do know some Python (no experience in server side programming at all). I have been developing Java EE apps last year, but I do not think JNI is a good solution. Only one team member knows some Perl, others are pure C++ programmers.
A:
Noting the "very urgent demo" part, assuming that that would take about a month, depending on the complexity, I'd stick to the familiar.
True, maintaining python would be easier in the end, and learning python should be a breeze, if you deem it viable.
I'd say, have the team learn python and do the basic stuff, as you learn the deeper parts, you could build classes for them to extend/implement. That way, you get things done as they learn.
A:
Given the urgency, I'd have to stick with C++.
Without that, I'd say keep what you got, but feel free to switch to a preferred language when refactoring. That would be the time to do it.
What you should not do, ever, is "port" anything to another language without rewriting or changing functionality in any way. It is a total waste of time, when the "best" outcome you can hope for is that it has no new bugs when you are done.
A:
I would use Python. You could write very basic wrappers using the Python C API and then call said functions from Python with relative ease.
|
Programming language decision for C++ legacy project workflow
|
I have quite a lot of C++ legacy code modules from my colleagues, unfortunately poorly written. Each is doing a different job, but they are all GNU C++ code running under Linux.
I want to write a controller program, to make a singular C++ module for a workflow, for a very urgent demo. Also I need to write a front-end web-app allowing clients submitting jobs to the controller.
My main criteria are:
development speed (very urgent demo)
good binding with C++ (I have legacy code I do not want to rewrite in another language)
smooth introduction of new programming language to team (has some python, java and perl knowledge)
What programming language fits my needs best, and why?
Details:
I lean towards python for its perfect binding with C++, as writing JNI is too much work, and kind of obsolete nowadays. However, no one in my team is Python programmer; I do know some Python (no experience in server side programming at all). I have been developing Java EE apps last year, but I do not think JNI is a good solution. Only one team member knows some Perl, others are pure C++ programmers.
|
[
"Noting the \"very urgent demo\" part, assuming that that would take about a month, depending on the complexity, I'd stick to the familiar.\nTrue, maintaining python would be easier in the end, and learning python should be a breeze, if you deem it viable.\nI'd say, have the team learn python and do the basic stuff, as you learn the deeper parts, you could build classes for them to extend/implement. That way, you get things done as they learn.\n",
"Given the urgency, I'd have to stick with C++.\nWithout that, I'd say keep what you got, but feel free to switch to a preferred language when refactoring. That would be the time to do it. \nWhat you should not do, ever, is \"port\" anything to another language without rewriting or changing functionality in any way. It is a total waste of time, when the \"best\" outcome you can hope for is that it has no new bugs when you are done.\n",
"I would use Python. You could write very basic wrappers using the Python C API and then call said functions from Python with relative ease.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"binding",
"java",
"java_native_interface",
"programming_languages",
"python"
] |
stackoverflow_0002313017_binding_java_java_native_interface_programming_languages_python.txt
|
Q:
Controlling VirtualBox from commandline with python
We are using python virtualbox API for controlling the virtualbox. For that we are using the "pyvb" package(as given in python API documentation).
al=pyvb.vb.VB()
m=pyvb.vm.vbVM()
al.startVM(m)
we have executed using the python interpreter. No error is shown but the virtualbox doesnt start. Could you please tell us what could be wrong(all necessary modules and packages have been imported)
A:
I found that I can use the following functions to find if a VM is running, restore a VM to a specific snapshot, and start a VM by name.
from subprocess import Popen, PIPE
def running_vms():
"""
Return list of running vms
"""
f = Popen(r'vboxmanage --nologo list runningvms', stdout=PIPE).stdout
data = [ eachLine.strip() for eachLine in f ]
return data
def restore_vm(name='', snapshot=''):
"""
Restore VM to specific snapshot uuid
name = VM Name
snapshot = uuid of snapshot (uuid can be found in the xml file of your machines folder)
"""
command = r'vboxmanage --nologo snapshot %s restore %s' % (name,snapshot)
f = Popen(command, stdout=PIPE).stdout
data = [ eachLine.strip() for eachLine in f ]
return data
def launch_vm(name=''):
"""
Launch VM
name = VM Name
"""
command = r'vboxmanage --nologo startvm %s ' % name
f = Popen(command, stdout=PIPE).stdout
data = [ eachLine.strip() for eachLine in f ]
return data
A:
The code quoted doesn't seem to specify what VM to run. Shouldn't you be doing a getVM call and then using that resulting VM instance in your startVM call? E.g.:
al=pyvb.vb.VB()
m=al.getVM(guid_of_vm)
al.startVM(m)
...would start the VM identified with the given GUID (all VirtualBox VMs have a GUID assigned when they're created). You can get the GUID from the VM's XML file. If you need to discover VMs at runtime, there's the handy listVMS call:
al=pyvb.vb.VB()
l=al.listVMS()
# choose a VM from the list, assign to 'm'
al.startVM(m)
|
Controlling VirtualBox from commandline with python
|
We are using python virtualbox API for controlling the virtualbox. For that we are using the "pyvb" package(as given in python API documentation).
al=pyvb.vb.VB()
m=pyvb.vm.vbVM()
al.startVM(m)
we have executed using the python interpreter. No error is shown but the virtualbox doesnt start. Could you please tell us what could be wrong(all necessary modules and packages have been imported)
|
[
"I found that I can use the following functions to find if a VM is running, restore a VM to a specific snapshot, and start a VM by name.\nfrom subprocess import Popen, PIPE\n\n def running_vms():\n \"\"\"\n Return list of running vms\n \"\"\"\n f = Popen(r'vboxmanage --nologo list runningvms', stdout=PIPE).stdout\n data = [ eachLine.strip() for eachLine in f ]\n return data\n\n def restore_vm(name='', snapshot=''):\n \"\"\"\n Restore VM to specific snapshot uuid\n\n name = VM Name\n snapshot = uuid of snapshot (uuid can be found in the xml file of your machines folder)\n \"\"\"\n command = r'vboxmanage --nologo snapshot %s restore %s' % (name,snapshot)\n f = Popen(command, stdout=PIPE).stdout\n data = [ eachLine.strip() for eachLine in f ]\n return data\n\n def launch_vm(name=''):\n \"\"\"\n Launch VM\n\n name = VM Name\n \"\"\"\n command = r'vboxmanage --nologo startvm %s ' % name\n f = Popen(command, stdout=PIPE).stdout\n data = [ eachLine.strip() for eachLine in f ]\n return data\n\n",
"The code quoted doesn't seem to specify what VM to run. Shouldn't you be doing a getVM call and then using that resulting VM instance in your startVM call? E.g.:\nal=pyvb.vb.VB()\nm=al.getVM(guid_of_vm)\nal.startVM(m)\n\n...would start the VM identified with the given GUID (all VirtualBox VMs have a GUID assigned when they're created). You can get the GUID from the VM's XML file. If you need to discover VMs at runtime, there's the handy listVMS call:\nal=pyvb.vb.VB()\nl=al.listVMS()\n# choose a VM from the list, assign to 'm'\nal.startVM(m)\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"virtualbox"
] |
stackoverflow_0002313010_python_virtualbox.txt
|
Q:
Django models - how to filter out duplicate values by PK after the fact?
I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable.
Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.
A:
In general it's better to combine all your queries into a single query if possible. Ie.
q = Model.objects.filter(Q(field1=f1)|Q(field2=f2))
instead of
q1 = Models.object.filter(field1=f1)
q2 = Models.object.filter(field2=f2)
If the first query is returning duplicated Models then use distinct()
q = Model.objects.filter(Q(field1=f1)|Q(field2=f2)).distinct()
If your query really is impossible to execute with a single command, then you'll have to resort to using a dict or other technique recommended in the other answers. It might be helpful if you posted the exact query on SO and we could see if it would be possible to combine into a single query. In my experience, most queries can be done with a single queryset.
A:
Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.
That's exactly what I would do if you were locked into your current structure of making several queries. Then a simply dictionary.values() will return your list back.
If you have a little more flexibility, why not use Q objects? Instead of actually making the queries, store each query in a Q object and use a bitwise or ("|") to execute a single query. This will achieve your goal and save database hits.
Django Q objects
A:
You can use a set if you add the __hash__ function to your model definition so that it returns the id (assuming this doesn't interfere with other hash behaviour you may have in your app):
class MyModel(models.Model):
def __hash__(self):
return self.pk
A:
If the order doesn't matter, use a dict.
A:
Remove "duplicates" depends on how you define "duplicated".
If you want EVERY column (except the PK) to match, that's a pain in the neck -- it's a lot of comparing.
If, on the other hand, you have some "natural key" column (or short set of columns) than you can easily query and remove these.
master = MyModel.objects.get( id=theMasterKey )
dups = MyModel.objects.filter( fld1=master.fld1, fld2=master.fld2 )
dups.all().delete()
If you can identify some shorter set of key fields for duplicate identification, this works pretty well.
Edit
If the model objects haven't been saved to the database yet, you can make a dictionary on a tuple of these keys.
unique = {}
...
key = (anObject.fld1,anObject.fld2)
if key not in unique:
unique[key]= anObject
A:
I use this one:
dict(zip(map(lambda x: x.pk,items),items)).values()
|
Django models - how to filter out duplicate values by PK after the fact?
|
I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable.
Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.
|
[
"In general it's better to combine all your queries into a single query if possible. Ie.\nq = Model.objects.filter(Q(field1=f1)|Q(field2=f2))\n\ninstead of\nq1 = Models.object.filter(field1=f1)\nq2 = Models.object.filter(field2=f2)\n\nIf the first query is returning duplicated Models then use distinct()\nq = Model.objects.filter(Q(field1=f1)|Q(field2=f2)).distinct()\n\nIf your query really is impossible to execute with a single command, then you'll have to resort to using a dict or other technique recommended in the other answers. It might be helpful if you posted the exact query on SO and we could see if it would be possible to combine into a single query. In my experience, most queries can be done with a single queryset.\n",
"\nIs there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.\n\nThat's exactly what I would do if you were locked into your current structure of making several queries. Then a simply dictionary.values() will return your list back.\nIf you have a little more flexibility, why not use Q objects? Instead of actually making the queries, store each query in a Q object and use a bitwise or (\"|\") to execute a single query. This will achieve your goal and save database hits.\nDjango Q objects\n",
"You can use a set if you add the __hash__ function to your model definition so that it returns the id (assuming this doesn't interfere with other hash behaviour you may have in your app):\nclass MyModel(models.Model):\n\n def __hash__(self):\n return self.pk\n\n",
"If the order doesn't matter, use a dict.\n",
"Remove \"duplicates\" depends on how you define \"duplicated\".\nIf you want EVERY column (except the PK) to match, that's a pain in the neck -- it's a lot of comparing.\nIf, on the other hand, you have some \"natural key\" column (or short set of columns) than you can easily query and remove these.\nmaster = MyModel.objects.get( id=theMasterKey )\ndups = MyModel.objects.filter( fld1=master.fld1, fld2=master.fld2 )\ndups.all().delete()\n\nIf you can identify some shorter set of key fields for duplicate identification, this works pretty well.\n\nEdit\nIf the model objects haven't been saved to the database yet, you can make a dictionary on a tuple of these keys.\nunique = {}\n...\nkey = (anObject.fld1,anObject.fld2)\nif key not in unique:\n unique[key]= anObject\n\n",
"I use this one:\ndict(zip(map(lambda x: x.pk,items),items)).values()\n\n"
] |
[
13,
6,
2,
0,
0,
0
] |
[] |
[] |
[
"data_structures",
"django",
"python",
"set",
"unique"
] |
stackoverflow_0000744424_data_structures_django_python_set_unique.txt
|
Q:
Segmentation fault when importing pylab in a python script
I have installed Ubuntu 8.10. I am using python 2.6.4. I have installed the following packages
networkx 1.0rc1
matplotlib 0.99.1.2
scipy 0.7.1
numpy 1.3
when I write the following statement in my code
import pylab
Also this statement gives a segmentation fault
import matplotlib.pyplot as plt
I receive a segmentation fault. What do I do?
The same code works perfectly well on my Windows machine.
A:
try running python through gdb. The top frame of the stacktrace is the (assumed) origin of the segmentation fault. This should give you a rough idea what to write in a bug report. If all of the above packages are from the ubuntu repositories, there should be a good chance that someone in the ubuntu community has an idea of what's going on.
|
Segmentation fault when importing pylab in a python script
|
I have installed Ubuntu 8.10. I am using python 2.6.4. I have installed the following packages
networkx 1.0rc1
matplotlib 0.99.1.2
scipy 0.7.1
numpy 1.3
when I write the following statement in my code
import pylab
Also this statement gives a segmentation fault
import matplotlib.pyplot as plt
I receive a segmentation fault. What do I do?
The same code works perfectly well on my Windows machine.
|
[
"try running python through gdb. The top frame of the stacktrace is the (assumed) origin of the segmentation fault. This should give you a rough idea what to write in a bug report. If all of the above packages are from the ubuntu repositories, there should be a good chance that someone in the ubuntu community has an idea of what's going on.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002311941_python.txt
|
Q:
Conversion from imperative to functional programming [Python to Standard ML]
I have a function specification that states it that should evaluate a polynomial function of one variable. The coefficient of the function is given as a list. It also accepts the value of the variable as a real.
For example: eval(2, [4, 3, 2, 1]) = 26 (1*x^3 + 2*x^2 + 3*x^1 + 4*x^0, where x = 2)
Here's the function in python, but I'm not sure how to convert it to SML. I'm having trouble finding a way to pass it the iteration value without changing the parameters of the function. It needs to remain a real * real list -> real function.
def eval(r, L):
sum = 0
for i in range(0, len(L)):
sum = sum + L[i] * (r ** i)
return sum
A:
The usual way to express sums in functional languages is a fold. You can get rid of the need for an index (and a function to raise an int to the power of another int) by multiplying the sum with r in each iteration:
fun eval radix lst = let
fun f (element, sum) = sum * radix + element
in
foldr f 0 lst
end
Now the function can be used like this:
- eval 10 [1,2,3];
val it = 321 : int
A:
You can use explicit recursion to walk through the list of coefficients, exponentiate the radix, and sum up the total.
fun eval r =
let fun step (power, sum) (coeff :: rest) =
step (power * r, sum + coeff * power) rest
| step (_, sum) nil = sum
in step (1, 0)
end
Structurally, this is exactly like a fold, and it becomes clearer if we replace it with one.
fun eval r lst =
let fun step (coeff, (power, sum)) = (power * r, sum + coeff * power)
val (_, sum) = foldl step (1, 0) lst
in sum
end
You can reverse the order of operations to use Horner's scheme, as mentioned in KennyTM's comment: that would result in sepp2k's answer, which requires half as many multiplications, but uses more stack space.
|
Conversion from imperative to functional programming [Python to Standard ML]
|
I have a function specification that states it that should evaluate a polynomial function of one variable. The coefficient of the function is given as a list. It also accepts the value of the variable as a real.
For example: eval(2, [4, 3, 2, 1]) = 26 (1*x^3 + 2*x^2 + 3*x^1 + 4*x^0, where x = 2)
Here's the function in python, but I'm not sure how to convert it to SML. I'm having trouble finding a way to pass it the iteration value without changing the parameters of the function. It needs to remain a real * real list -> real function.
def eval(r, L):
sum = 0
for i in range(0, len(L)):
sum = sum + L[i] * (r ** i)
return sum
|
[
"The usual way to express sums in functional languages is a fold. You can get rid of the need for an index (and a function to raise an int to the power of another int) by multiplying the sum with r in each iteration:\nfun eval radix lst = let\n fun f (element, sum) = sum * radix + element\nin\n foldr f 0 lst\nend\n\nNow the function can be used like this:\n- eval 10 [1,2,3];\nval it = 321 : int\n\n",
"You can use explicit recursion to walk through the list of coefficients, exponentiate the radix, and sum up the total.\nfun eval r =\n let fun step (power, sum) (coeff :: rest) =\n step (power * r, sum + coeff * power) rest\n | step (_, sum) nil = sum\n in step (1, 0)\n end\n\nStructurally, this is exactly like a fold, and it becomes clearer if we replace it with one.\nfun eval r lst =\n let fun step (coeff, (power, sum)) = (power * r, sum + coeff * power)\n val (_, sum) = foldl step (1, 0) lst\n in sum\n end\n\nYou can reverse the order of operations to use Horner's scheme, as mentioned in KennyTM's comment: that would result in sepp2k's answer, which requires half as many multiplications, but uses more stack space.\n"
] |
[
4,
1
] |
[] |
[] |
[
"functional_programming",
"parameters",
"python",
"recursion",
"sml"
] |
stackoverflow_0002313141_functional_programming_parameters_python_recursion_sml.txt
|
Q:
Genshi TemplateSyntaxError on python block where it should work
<?python class += 1 ?>
One really simple line of code which definitely should work, but still it gives me this error:
TemplateSyntaxError: invalid syntax (file.html, line 22)
I shorted the filepath for readability, but that's the exact error. I'm definitely sure it should work, as I've used
<?python
i += 1
?>
In another file, and it worked just fine there. Almost exact same structure; a table and a py:for loop. Tried everything, but can't get it to work! Any help?
A:
class is a Python keyword. You can't name a variable that.
|
Genshi TemplateSyntaxError on python block where it should work
|
<?python class += 1 ?>
One really simple line of code which definitely should work, but still it gives me this error:
TemplateSyntaxError: invalid syntax (file.html, line 22)
I shorted the filepath for readability, but that's the exact error. I'm definitely sure it should work, as I've used
<?python
i += 1
?>
In another file, and it worked just fine there. Almost exact same structure; a table and a py:for loop. Tried everything, but can't get it to work! Any help?
|
[
"class is a Python keyword. You can't name a variable that.\n"
] |
[
1
] |
[] |
[] |
[
"codeblocks",
"genshi",
"python",
"syntax_error"
] |
stackoverflow_0002313590_codeblocks_genshi_python_syntax_error.txt
|
Q:
How to improve performance when interpolating on 3d data with SciPy
I have 3d-data representing the atmosphere. Now I want to interpolate this data to a common Z coordinate (what I mean by that should be clear from the function's doctring). The following code works fine, but I was wondering if there were a way to improve the performance ...
def interpLevel(grid,value,data,interp='linear'):
"""
Interpolate 3d data to a common z coordinate.
Can be used to calculate the wind/pv/whatsoever values for a common
potential temperature / pressure level.
grid : numpy.ndarray
The grid. For example the potential temperature values for the whole 3d
grid.
value : float
The common value in the grid, to which the data shall be interpolated.
For example, 350.0
data : numpy.ndarray
The data which shall be interpolated. For example, the PV values for
the whole 3d grid.
kind : str
This indicates which kind of interpolation will be done. It is directly
passed on to scipy.interpolate.interp1d().
returs : numpy.ndarray
A 2d array containing the *data* values at *value*.
"""
ret = np.zeros_like(data[0,:,:])
# we need to copy the grid to a new one, because otherwise the flipping
# done below will be messed up
gr = np.zeros_like(grid)
da = np.zeros_like(data)
for latIdx in xrange(grid.shape[1]):
for lonIdx in xrange(grid.shape[2]):
# check if we need to flip the column
if grid[0,latIdx,lonIdx] > grid[-1,latIdx,lonIdx]:
gr[:,latIdx,lonIdx] = grid[::-1,latIdx,lonIdx]
da[:,latIdx,lonIdx] = data[::-1,latIdx,lonIdx]
else:
gr[:,latIdx,lonIdx] = grid[:,latIdx,lonIdx]
da[:,latIdx,lonIdx] = data[:,latIdx,lonIdx]
f = interpolate.interp1d(gr[:,latIdx,lonIdx], \
da[:,latIdx,lonIdx], \
kind=interp)
ret[latIdx,lonIdx] = f(value)
return ret
A:
Well, this might give a small speed-up just because it uses less memory.
ret = np.zeros_like(data[0,:,:])
for latIdx in xrange(grid.shape[1]):
for lonIdx in xrange(grid.shape[2]):
# check if we need to flip the column
if grid[0,latIdx,lonIdx] > grid[-1,latIdx,lonIdx]:
ind = -1
else:
ind = 1
f = interpolate.interp1d(grid[::ind,latIdx,lonIdx], \
data[::ind,latIdx,lonIdx], \
kind=interp)
ret[latIdx,lonIdx] = f(value)
return ret
All I've done is get rid of gr and da really.
Other than that, are you calling this function with a whole lot of different values(i.e. value being different but other parameters the same)? If so, you might want to make the function be able to handle multiple values (add another dimension to ret in other words that is as long as the length of values). Then you are making better use of the interpolation function that you've created.
The last suggestion is to try a profiler. It will allow you to see what is taking the most time.
|
How to improve performance when interpolating on 3d data with SciPy
|
I have 3d-data representing the atmosphere. Now I want to interpolate this data to a common Z coordinate (what I mean by that should be clear from the function's doctring). The following code works fine, but I was wondering if there were a way to improve the performance ...
def interpLevel(grid,value,data,interp='linear'):
"""
Interpolate 3d data to a common z coordinate.
Can be used to calculate the wind/pv/whatsoever values for a common
potential temperature / pressure level.
grid : numpy.ndarray
The grid. For example the potential temperature values for the whole 3d
grid.
value : float
The common value in the grid, to which the data shall be interpolated.
For example, 350.0
data : numpy.ndarray
The data which shall be interpolated. For example, the PV values for
the whole 3d grid.
kind : str
This indicates which kind of interpolation will be done. It is directly
passed on to scipy.interpolate.interp1d().
returs : numpy.ndarray
A 2d array containing the *data* values at *value*.
"""
ret = np.zeros_like(data[0,:,:])
# we need to copy the grid to a new one, because otherwise the flipping
# done below will be messed up
gr = np.zeros_like(grid)
da = np.zeros_like(data)
for latIdx in xrange(grid.shape[1]):
for lonIdx in xrange(grid.shape[2]):
# check if we need to flip the column
if grid[0,latIdx,lonIdx] > grid[-1,latIdx,lonIdx]:
gr[:,latIdx,lonIdx] = grid[::-1,latIdx,lonIdx]
da[:,latIdx,lonIdx] = data[::-1,latIdx,lonIdx]
else:
gr[:,latIdx,lonIdx] = grid[:,latIdx,lonIdx]
da[:,latIdx,lonIdx] = data[:,latIdx,lonIdx]
f = interpolate.interp1d(gr[:,latIdx,lonIdx], \
da[:,latIdx,lonIdx], \
kind=interp)
ret[latIdx,lonIdx] = f(value)
return ret
|
[
"Well, this might give a small speed-up just because it uses less memory.\nret = np.zeros_like(data[0,:,:])\nfor latIdx in xrange(grid.shape[1]):\n for lonIdx in xrange(grid.shape[2]):\n # check if we need to flip the column\n if grid[0,latIdx,lonIdx] > grid[-1,latIdx,lonIdx]:\n ind = -1\n else:\n ind = 1\n f = interpolate.interp1d(grid[::ind,latIdx,lonIdx], \\\n data[::ind,latIdx,lonIdx], \\\n kind=interp)\n ret[latIdx,lonIdx] = f(value)\nreturn ret\n\nAll I've done is get rid of gr and da really.\nOther than that, are you calling this function with a whole lot of different values(i.e. value being different but other parameters the same)? If so, you might want to make the function be able to handle multiple values (add another dimension to ret in other words that is as long as the length of values). Then you are making better use of the interpolation function that you've created.\nThe last suggestion is to try a profiler. It will allow you to see what is taking the most time.\n"
] |
[
2
] |
[] |
[] |
[
"interpolation",
"numpy",
"python",
"scipy"
] |
stackoverflow_0002312665_interpolation_numpy_python_scipy.txt
|
Q:
How can I use the Whirlpool hash with Django authentication?
We have a system written in PHP where account passwords are stored as the first 128 chars of a whirlpool hash of the password.
I'd like to transition to handling the logins with Django without changing the database or asking users to change their passwords. Also, I'd prefer to stick with whirlpool vs. the less secure hashes Django has built in. I found a python (C) implementation of Whirlpool which seems to work fine.
How can I change the Django password checking function to use Whirlpool rather than SHA1/MD5?
A:
Basically you want to write your own authentication back-end. Fortunately, this can be done very easily.
It's as easy as:
class MyBackend:
def authenticate(self, username=None, password=None):
# Check the username/password and return a User.
Then all you need to do is specify the back-end class by setting AUTHENTICATION_BACKENDS to be ('django.contrib.auth.backends.YourCustomBackend',).
See: http://docs.djangoproject.com/en/dev/topics/auth/#specifying-authentication-backends
|
How can I use the Whirlpool hash with Django authentication?
|
We have a system written in PHP where account passwords are stored as the first 128 chars of a whirlpool hash of the password.
I'd like to transition to handling the logins with Django without changing the database or asking users to change their passwords. Also, I'd prefer to stick with whirlpool vs. the less secure hashes Django has built in. I found a python (C) implementation of Whirlpool which seems to work fine.
How can I change the Django password checking function to use Whirlpool rather than SHA1/MD5?
|
[
"Basically you want to write your own authentication back-end. Fortunately, this can be done very easily.\nIt's as easy as:\nclass MyBackend:\n def authenticate(self, username=None, password=None):\n # Check the username/password and return a User.\n\nThen all you need to do is specify the back-end class by setting AUTHENTICATION_BACKENDS to be ('django.contrib.auth.backends.YourCustomBackend',).\nSee: http://docs.djangoproject.com/en/dev/topics/auth/#specifying-authentication-backends\n"
] |
[
2
] |
[] |
[] |
[
"authentication",
"django",
"python",
"sha1"
] |
stackoverflow_0002314405_authentication_django_python_sha1.txt
|
Q:
How to plot the lines first and points last in matplotlib
I have a simple plot with several sets of points and lines connecting each set. I want the points to be plotted on top of the lines (so that the line doesn't show inside the point). Regardless of order of the plot and scatter calls, this plot comes out the same, and not as I'd like. Is there a simple way to do it?
import math
import matplotlib.pyplot as plt
def poisson(m):
def f(k):
e = math.e**(-m)
f = math.factorial(k)
g = m**k
return g*e/f
return f
R = range(20)
L = list()
means = (1,4,10)
for m in means:
f = poisson(m)
L.append([f(k) for k in R])
colors = ['r','b','purple']
for c,P in zip(colors,L):
plt.plot(R,P,color='0.2',lw=1.5)
plt.scatter(R,P,s=150,color=c)
ax = plt.axes()
ax.set_xlim(-0.5,20)
ax.set_ylim(-0.01,0.4)
plt.savefig('example.png')
A:
You need to set the Z-order.
plt.plot(R,P,color='0.2',lw=1.5, zorder=1)
plt.scatter(R,P,s=150,color=c, zorder=2)
Check out this example.
http://matplotlib.sourceforge.net/examples/pylab_examples/zorder_demo.html
|
How to plot the lines first and points last in matplotlib
|
I have a simple plot with several sets of points and lines connecting each set. I want the points to be plotted on top of the lines (so that the line doesn't show inside the point). Regardless of order of the plot and scatter calls, this plot comes out the same, and not as I'd like. Is there a simple way to do it?
import math
import matplotlib.pyplot as plt
def poisson(m):
def f(k):
e = math.e**(-m)
f = math.factorial(k)
g = m**k
return g*e/f
return f
R = range(20)
L = list()
means = (1,4,10)
for m in means:
f = poisson(m)
L.append([f(k) for k in R])
colors = ['r','b','purple']
for c,P in zip(colors,L):
plt.plot(R,P,color='0.2',lw=1.5)
plt.scatter(R,P,s=150,color=c)
ax = plt.axes()
ax.set_xlim(-0.5,20)
ax.set_ylim(-0.01,0.4)
plt.savefig('example.png')
|
[
"You need to set the Z-order.\nplt.plot(R,P,color='0.2',lw=1.5, zorder=1)\nplt.scatter(R,P,s=150,color=c, zorder=2)\n\nCheck out this example.\nhttp://matplotlib.sourceforge.net/examples/pylab_examples/zorder_demo.html\n"
] |
[
96
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0002314379_matplotlib_python.txt
|
Q:
In model save() how to get all field starting with 'foo'
I've this django model:
from django.db import models
class MyModel(models.Model):
foo_it = model.CharField(max_length=100)
foo_en = model.CharField(max_length=100)
def save(self):
print_all_field_starting_with('foo_')
super(MyModel, self).save()
So I want to get all field starting with foo (as an example) and do something with this.
I can't do this in the code because I don't know all fields from model (I'm using django-transmeta)
so, how can I do this?
Thanks in advance ;)
A:
You can do:
for field in dir(self):
if field.startswith('foo_'):
# getting with getattr(self, field)
# setting with setattr(self, field, value)
If you want to get the list of fields you can also so this:
foo_fields = [field for field in dir(self) if field.startswith('foo_')]
Or print a list of values of foo fields:
print map(lambda x: getattr(self, x), [field for field in dir(self) if field.startswith('foo_')])
A:
This will do the trick, though you need to also pass in the object whose fields you want to print:
import inspect
def print_all_field_starting_with(prefix, object):
for name, value in inspect.getmembers(object):
if name.startswith(prefix):
print name # or do something else
See the documentation for the inspect module for more info.
A:
There is a get_all_field_names() method that is built into the Meta subclass for all models, and can be found in foo._meta.get_all_field_names():
>>> from foo.models import Foo
>>> f = Foo.objects.get(pk=1)
>>> f._meta.get_all_field_names()
['active', 'created', 'expires', 'id', , 'inputter', 'reason', 'requester', 'updated']
So this would be a simple thing:
def print_all_fields_starting_with(obj, starter):
fields = [x for x in obj._meta.get_all_field_names() if x.startswith(starter)]
for field in fields:
print getattr(obj, field)
And in your custom save():
def save(self):
print_all_fields_starting_with(self, "foo_")
super(MyModel, self).save()
|
In model save() how to get all field starting with 'foo'
|
I've this django model:
from django.db import models
class MyModel(models.Model):
foo_it = model.CharField(max_length=100)
foo_en = model.CharField(max_length=100)
def save(self):
print_all_field_starting_with('foo_')
super(MyModel, self).save()
So I want to get all field starting with foo (as an example) and do something with this.
I can't do this in the code because I don't know all fields from model (I'm using django-transmeta)
so, how can I do this?
Thanks in advance ;)
|
[
"You can do:\nfor field in dir(self):\n if field.startswith('foo_'):\n # getting with getattr(self, field)\n # setting with setattr(self, field, value)\n\nIf you want to get the list of fields you can also so this:\nfoo_fields = [field for field in dir(self) if field.startswith('foo_')]\n\nOr print a list of values of foo fields:\nprint map(lambda x: getattr(self, x), [field for field in dir(self) if field.startswith('foo_')])\n\n",
"This will do the trick, though you need to also pass in the object whose fields you want to print:\nimport inspect\ndef print_all_field_starting_with(prefix, object):\n for name, value in inspect.getmembers(object):\n if name.startswith(prefix):\n print name # or do something else\n\nSee the documentation for the inspect module for more info.\n",
"There is a get_all_field_names() method that is built into the Meta subclass for all models, and can be found in foo._meta.get_all_field_names():\n>>> from foo.models import Foo\n>>> f = Foo.objects.get(pk=1)\n>>> f._meta.get_all_field_names()\n['active', 'created', 'expires', 'id', , 'inputter', 'reason', 'requester', 'updated']\n\nSo this would be a simple thing:\ndef print_all_fields_starting_with(obj, starter):\n fields = [x for x in obj._meta.get_all_field_names() if x.startswith(starter)]\n for field in fields:\n print getattr(obj, field)\n\nAnd in your custom save():\ndef save(self):\n print_all_fields_starting_with(self, \"foo_\")\n super(MyModel, self).save()\n\n"
] |
[
2,
2,
2
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002314292_django_django_models_python.txt
|
Q:
Does PIL create artifacting on the bottom edge of the image when you thumbnail() then crop()? If so, what is your workaround?
When I call PIL to thumbnail() an image, and then crop(), I get artifacting on the last row of pixels -- they're either mostly black with specks of intense color, or what seems to be a not-resized area of the image ( ie, that line of pixels is at the original resolution and did not scale down with the rest )
This does not seem to happen on a thumbnail() without a crop.
This happens whether or not I call a load() on the cropped image either.
To get around this visually, i've been thumbnailing to a 1pixel larger image, and then cropping to the same size. That seems to work. It's kind of a dirty hack though. I'm wondering if there's a proper fix.
A:
Yes, this happens to me also. This was a learning exercise for me because I have never cropped or created thumbnails using the PIL...
thumbnail(size,filter=None)
Replaces the original image, in place, with a new image of the given size (p. 2). The optional
filter argument works in the same way as in the .resize() method.
The aspect ratio (height : width) is preserved by this operation. The resulting image will be as large
as possible while still fitting within the given size. For example, if image im has size (400,150), its
size after im.thumbnail((40,40)) will be (40,15).
So what is happening is
You use thumbnail which maintains
the aspect
You're expecting the
image to be 40 x 40
You're cropping beyond the actual size of the thumbnail
A black strip most likely on the bottom due to cropping beyond the size
Code I wrote to repeat the issue:
def croptest(file, width, height):
import Image as pil
import os
max_width = width
max_height = height
file, ext = os.path.splitext(file)
img = pil.open(file)
img.thumbnail((max_width, max_height), pil.ANTIALIAS)
img.save(file + ".thumb.jpeg", 'JPEG')
croppedImage = img.crop((10, 10, 40, 40))
croppedImage.save(file + ".croppedthumb.jpeg", 'JPEG')
if __name__ == "__main__":
croptest("Desktop.bmp", 50, 50)
Desktop.thumb.jpeg was 50 x 37 whereas Desktop.croppedthumb.jpeg was 30 x 30 so I had a 3 pixel high black line across the bottom.
Your solution would be either to crop inside the actual size of the thumbnail or figure out how to create a thumbnail ignoring the aspect ratio.
|
Does PIL create artifacting on the bottom edge of the image when you thumbnail() then crop()? If so, what is your workaround?
|
When I call PIL to thumbnail() an image, and then crop(), I get artifacting on the last row of pixels -- they're either mostly black with specks of intense color, or what seems to be a not-resized area of the image ( ie, that line of pixels is at the original resolution and did not scale down with the rest )
This does not seem to happen on a thumbnail() without a crop.
This happens whether or not I call a load() on the cropped image either.
To get around this visually, i've been thumbnailing to a 1pixel larger image, and then cropping to the same size. That seems to work. It's kind of a dirty hack though. I'm wondering if there's a proper fix.
|
[
"Yes, this happens to me also. This was a learning exercise for me because I have never cropped or created thumbnails using the PIL...\nthumbnail(size,filter=None)\nReplaces the original image, in place, with a new image of the given size (p. 2). The optional\nfilter argument works in the same way as in the .resize() method.\nThe aspect ratio (height : width) is preserved by this operation. The resulting image will be as large\nas possible while still fitting within the given size. For example, if image im has size (400,150), its\nsize after im.thumbnail((40,40)) will be (40,15).\nSo what is happening is\n\nYou use thumbnail which maintains\nthe aspect\nYou're expecting the\nimage to be 40 x 40\nYou're cropping beyond the actual size of the thumbnail\nA black strip most likely on the bottom due to cropping beyond the size\n\nCode I wrote to repeat the issue:\ndef croptest(file, width, height):\n import Image as pil\n import os\n\n max_width = width\n max_height = height\n file, ext = os.path.splitext(file)\n\n img = pil.open(file)\n img.thumbnail((max_width, max_height), pil.ANTIALIAS)\n img.save(file + \".thumb.jpeg\", 'JPEG')\n croppedImage = img.crop((10, 10, 40, 40))\n croppedImage.save(file + \".croppedthumb.jpeg\", 'JPEG')\n\nif __name__ == \"__main__\":\n croptest(\"Desktop.bmp\", 50, 50)\n\nDesktop.thumb.jpeg was 50 x 37 whereas Desktop.croppedthumb.jpeg was 30 x 30 so I had a 3 pixel high black line across the bottom.\nYour solution would be either to crop inside the actual size of the thumbnail or figure out how to create a thumbnail ignoring the aspect ratio.\n"
] |
[
2
] |
[] |
[] |
[
"imaging",
"python",
"python_imaging_library"
] |
stackoverflow_0002312438_imaging_python_python_imaging_library.txt
|
Q:
speed-up python function to process files with data segments separated by a blank space
I need to process files with data segments separated by a blank space, for example:
93.18 15.21 36.69 33.85 16.41 16.81 29.17
21.69 23.71 26.38 63.70 66.69 0.89 39.91
86.55 56.34 57.80 98.38 0.24 17.19 75.46
[...]
1.30 73.02 56.79 39.28 96.39 18.77 55.03
99.95 28.88 90.90 26.70 62.37 86.58 65.05
25.16 32.61 17.47 4.23 34.82 26.63 57.24
36.72 83.30 97.29 73.31 31.79 80.03 25.71
[...]
2.74 75.92 40.19 54.57 87.41 75.59 22.79
.
.
.
for this I am using the following function.
In every call I get the necessary data, but I need to speed-up the code.
Is there a more efficient way?
EDIT: I will be updating the code with the changes that achieve improvements
ORIGINAL:
def get_pos_nextvalues(pos_file, indices):
result = []
for line in pos_file:
line = line.strip()
if not line:
break
values = [float(value) for value in line.split()]
result.append([float(values[i]) for i in indices])
return np.array(result)
NEW:
def get_pos_nextvalues(pos_file, indices):
result = ''
for line in pos_file:
if len(line) > 1:
s = line.split()
result += ' '.join([s [i] for i in indices])
else:
break
else:
return np.array([])
result = np.fromstring(result, dtype=float, sep=' ')
result = result.reshape(result.size/len(indices), len(indices))
return result
.
pos_file = open(filename, 'r', buffering=1024*10)
[...]
while(some_condition):
vs = get_pos_nextvalues(pos_file, (4,5,6))
[...]
speedup = 2.36
A:
not to convert floats to floats would be the first step. I would suggest, however, to first profile your code and then try to optimize the bottleneck parts.
I understand that you've changed your code from the original, but
values = [value for value in line.split()]
is not a good thing either. just write values = line.split() if this is what you mean.
Seeing how you're using NumPy, I'd suggest some methods of file reading that are demonstrated in their docs.
A:
You are only reading every character exactly once, so there isn't any real performance to gain.
You could combine strip and split if the empty lines contain a lot of whitespace.
You could also save some time initializing the numpy array from start, instead of first creating a python array and then converting.
A:
try increasing the read buffer, IO is probably the bottle neck of your code
open('file.txt', 'r', 1024 * 10)
also if the data is fully sequential you can try to skip the line by line code and convert a bunch of lines at once
A:
Instead of :
if len(line) <= 1: # only '\n' in «empty» lines
break
values = line.split()
try this:
values = line.split()
if not values: # line is wholly whitespace, end of segment
break
A:
numpy.fromfile doesn't work for you?
arr = fromfile('tmp.txt', sep=' ', dtype=int)
A:
Here's a variant that might be faster for few indices. It builds a string of only the desired values so that np.fromstring does less work.
def get_pos_nextvalues_fewindices(pos_file, indices):
result = ''
for line in pos_file:
if len(line) > 1:
s = line.split()
for i in indices:
result += s[i] + ' '
else:
return np.array([])
result = np.fromstring(result, dtype=float, sep=' ')
result = result.reshape(result.size/len(indeces), len(indeces))
return result
This trades off the overhead of split() and an added loop for less parsing. Or perhaps there's some clever regex trick you can do to extract the desired substrings directly?
Old Answer
np.mat('1.23 2.34 3.45 6\n1.32 2.43 7 3.54') converts the string to a numpy matrix of floating point values. This might be a faster kernel for you to use. For instance:
import numpy as np
def ReadFileChunk(pos_file):
chunktxt = ""
for line in pos_file:
if len(line) > 1:
chunktxt = chunktxt + line
else:
break
return np.mat(chunktxt).tolist()
# or alternatively
#return np.array(np.mat(s))
Then you can move your indexing stuff to another function. Hopefully having numpy parse the string internally is faster than calling float() repetitively.
|
speed-up python function to process files with data segments separated by a blank space
|
I need to process files with data segments separated by a blank space, for example:
93.18 15.21 36.69 33.85 16.41 16.81 29.17
21.69 23.71 26.38 63.70 66.69 0.89 39.91
86.55 56.34 57.80 98.38 0.24 17.19 75.46
[...]
1.30 73.02 56.79 39.28 96.39 18.77 55.03
99.95 28.88 90.90 26.70 62.37 86.58 65.05
25.16 32.61 17.47 4.23 34.82 26.63 57.24
36.72 83.30 97.29 73.31 31.79 80.03 25.71
[...]
2.74 75.92 40.19 54.57 87.41 75.59 22.79
.
.
.
for this I am using the following function.
In every call I get the necessary data, but I need to speed-up the code.
Is there a more efficient way?
EDIT: I will be updating the code with the changes that achieve improvements
ORIGINAL:
def get_pos_nextvalues(pos_file, indices):
result = []
for line in pos_file:
line = line.strip()
if not line:
break
values = [float(value) for value in line.split()]
result.append([float(values[i]) for i in indices])
return np.array(result)
NEW:
def get_pos_nextvalues(pos_file, indices):
result = ''
for line in pos_file:
if len(line) > 1:
s = line.split()
result += ' '.join([s [i] for i in indices])
else:
break
else:
return np.array([])
result = np.fromstring(result, dtype=float, sep=' ')
result = result.reshape(result.size/len(indices), len(indices))
return result
.
pos_file = open(filename, 'r', buffering=1024*10)
[...]
while(some_condition):
vs = get_pos_nextvalues(pos_file, (4,5,6))
[...]
speedup = 2.36
|
[
"not to convert floats to floats would be the first step. I would suggest, however, to first profile your code and then try to optimize the bottleneck parts.\nI understand that you've changed your code from the original, but \nvalues = [value for value in line.split()]\n\nis not a good thing either. just write values = line.split() if this is what you mean.\nSeeing how you're using NumPy, I'd suggest some methods of file reading that are demonstrated in their docs.\n",
"You are only reading every character exactly once, so there isn't any real performance to gain.\nYou could combine strip and split if the empty lines contain a lot of whitespace.\nYou could also save some time initializing the numpy array from start, instead of first creating a python array and then converting.\n",
"try increasing the read buffer, IO is probably the bottle neck of your code\nopen('file.txt', 'r', 1024 * 10) \n\nalso if the data is fully sequential you can try to skip the line by line code and convert a bunch of lines at once\n",
"Instead of :\nif len(line) <= 1: # only '\\n' in «empty» lines\n break\nvalues = line.split()\n\ntry this:\nvalues = line.split()\nif not values: # line is wholly whitespace, end of segment\n break\n\n",
"numpy.fromfile doesn't work for you?\narr = fromfile('tmp.txt', sep=' ', dtype=int)\n\n",
"Here's a variant that might be faster for few indices. It builds a string of only the desired values so that np.fromstring does less work.\ndef get_pos_nextvalues_fewindices(pos_file, indices):\n result = ''\n for line in pos_file:\n if len(line) > 1:\n s = line.split()\n for i in indices:\n result += s[i] + ' '\n else:\n return np.array([])\n result = np.fromstring(result, dtype=float, sep=' ')\n result = result.reshape(result.size/len(indeces), len(indeces))\n return result\n\nThis trades off the overhead of split() and an added loop for less parsing. Or perhaps there's some clever regex trick you can do to extract the desired substrings directly?\nOld Answer\nnp.mat('1.23 2.34 3.45 6\\n1.32 2.43 7 3.54') converts the string to a numpy matrix of floating point values. This might be a faster kernel for you to use. For instance:\nimport numpy as np\ndef ReadFileChunk(pos_file):\n chunktxt = \"\"\n for line in pos_file:\n if len(line) > 1:\n chunktxt = chunktxt + line\n else:\n break\n\n return np.mat(chunktxt).tolist()\n # or alternatively\n #return np.array(np.mat(s))\n\nThen you can move your indexing stuff to another function. Hopefully having numpy parse the string internally is faster than calling float() repetitively. \n"
] |
[
2,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"numpy",
"performance",
"python"
] |
stackoverflow_0002311376_numpy_performance_python.txt
|
Q:
Efficiently reading a csv file with windows newline on linux in Python
The following is working under windows for reading csv files line by line.
f = open(filename, 'r')
for line in f:
Though when copying the csv file to a linux server, it fails.
It should be mentioned that performance is an issue as the csv files are huge. I am therefore concerned about the string copying when using things like strip.
A:
Python has builtin support for Windows, Linux and Mac line endings:
f = open(filename, 'rtU')
for line in f:
...
If you really want don't want slow string operations, you should strip the files before processing them. You can either use dos2unix (can be found in the Debian package "tofrodos") or (easier) use FTP text mode which should do that automatically.
A:
If performance is important, why are you not using csv.reader?
A:
Ummm .... You have csv files, you are using Python, why not read the files using the Python csv module?
A:
The dos2unix utility will do this very efficiently. If the files are that large I would run that command as part of the copy.
A:
Actually, the most efficient way to read any file is in one big I/O. There isn't always enough RAM to do that, but the less I/Os the better.
|
Efficiently reading a csv file with windows newline on linux in Python
|
The following is working under windows for reading csv files line by line.
f = open(filename, 'r')
for line in f:
Though when copying the csv file to a linux server, it fails.
It should be mentioned that performance is an issue as the csv files are huge. I am therefore concerned about the string copying when using things like strip.
|
[
"Python has builtin support for Windows, Linux and Mac line endings:\nf = open(filename, 'rtU')\n\nfor line in f:\n ...\n\nIf you really want don't want slow string operations, you should strip the files before processing them. You can either use dos2unix (can be found in the Debian package \"tofrodos\") or (easier) use FTP text mode which should do that automatically.\n",
"If performance is important, why are you not using csv.reader?\n",
"Ummm .... You have csv files, you are using Python, why not read the files using the Python csv module?\n",
"The dos2unix utility will do this very efficiently. If the files are that large I would run that command as part of the copy.\n",
"Actually, the most efficient way to read any file is in one big I/O. There isn't always enough RAM to do that, but the less I/Os the better.\n"
] |
[
7,
6,
4,
1,
0
] |
[] |
[] |
[
"csv",
"python",
"python_3.x"
] |
stackoverflow_0002314501_csv_python_python_3.x.txt
|
Q:
Integer comparison in python slows everything down to a crawl
The following code is causing me enormous headaches:
def extract_by_letters(letters, dictionary):
for word in dictionary:
for letter in letters:
if word.count(letter) != letters.count(letter):
if word in dictionary: #I cant leave this line out
dictionary.remove(word)
return dictionary
First of all: the 'if word in dictionary' line. Why can't I leave this out? I get an error saying ValueError: list.remove(x): x not in list
But it is, obviously.
Second: Dictionary is a file of about 50,000 words separated by linebreaks. The above code takes about 2 minutes to run... Wayyy too long. I played with the code for a bit, and I found that the line:
if word.count(letter) != letters.count(letter):
seems to be causing all my problems. If I take that line out (which totally screws up the output), the function takes about 2 seconds to go through the dictionary.
I thought it was the count functions, but it's not.
if I change the if statement to something like:
print word.count(letter)
print letters.count(letter)
the function takes about 3 seconds to run.
I'm convinced it's the comparison. Any other suggestions? Is there a better way to do this?
Thanks in advance!
A:
The reason you get the exception is that if the letter count matches for more than one letter, you are trying to remove the word more than once
The reason it is so slow is that you have loops inside loops inside loops.
If you would write a sentence or two about what the function is supposed to do, it would be much easier to refactor it. In the mean time, this would stop you checking whether a word needs to be removed once you have already removed it.
def extract_by_letters(letters, dictionary):
for word in dictionary[:]: # bad idea to change this while you iterate over it
for letter in letters:
if word.count(letter) != letters.count(letter):
dictionary.remove(word)
break
return dictionary
If dictionary is a set you should get some speed up. If dictionary is a list this should give a huge speedup
A:
Try building the output instead of deleting from it:
def extract_by_letters(letters, dictionary):
d = []
for word in dictionary:
for letter in letters:
if word.count(letter)>0:
d.append(word)
break
return d
Or, you could use regular expressions:
import re
def extract_by_letters(letters, dictionary):
regex = re.compile('['+letters+']')
d=[]
for word in dictionary:
if regex.search(word):
d.append(word)
return d
Or, perhaps the simplest way:
import re
def extract_by_letters(letters, dictionary):
regex = re.compile('['+letters+']')
return [word for word in dictionary if regex.search(word)]
This last one takes no noticeable time to scan /usr/share/dict/words on my Mac, which is a list of 234936 words.
A:
Here's a function that should offer a major speed-up:
def extract_by_letters(letters,dictionary):
letdict = zip(set(letters),[letters.count(let) for let in set(letters)])
outarr = []
for word in dictionary:
goodword = True
for letter in letdict:
if word.count(letter) != letdict[letter]:
goodword = False
break
if goodword:
outarr.append(word)
return outarr
Here are the optimizations I did:
Made a dictionary of the letters with their corresponding frequencies. This way, you aren't using letters.count over and over again when you only need to do this process once and store the results.
Rather than removing the words from dictionary, I add them to an array that is returned from the function. If you have a huge dictionary, chances are that only a few words will match. Also, if the dictionary variable is an array (which I suspect), then every time you called remove it had to first search for the word in dictionary (linearly starting at the beginning) and then remove it. It is faster to remove by popping using the index of the word to be removed.
Breaking out of the loop checking the letter counts whenever a mismatch is found. This prevents us from doing needless checks when we already have our answer.
I wasn't sure if you had repeated letters in the letters variable or not so I made sure that it could handle that by using letdict. If you had letters repeated in your letters variable before, then you were checking the counts of those letters in the word repeatedly.
A:
import pprint
from collections import defaultdict
# This is a best approximation to what Bryan is trying to do.
# However the results are meaningless because the list is being
# mutated during iteration over it. So I haven't shown the output.
def extract_by_letters_0(letters, input_list):
dictionary = input_list.copy()
for word in dictionary:
for letter in letters:
if word.count(letter) != letters.count(letter):
if word in dictionary: #I cant leave this line out
dictionary.remove(word)
return dictionary
# This avoids the mutation.
# The results are anagrams PLUS letters that don't occur
# in the query. E.g. "same" produces "samehood" but not "sameness"
# ("sameness" has 3*"s" and 2*"e" instead of 1 of each)
def extract_by_letters_1(letters, input_list):
dictionary = set(input_list)
ripouts = set()
for word in dictionary:
for letter in letters:
if word.count(letter) != letters.count(letter):
ripouts.add(word)
return dictionary - ripouts
def anagram_key(strg):
return ''.join(sorted(list(strg)))
def check_anagrams(str1, str2):
return sorted(list(str1)) == sorted(list(str2))
# Advice: try algorithms like this out on a SMALL data set first.
# Get it working correctly. Use different test cases. Have test code
# however primitive that check your results.
# Then if it runs slowly, helpers
# don't have to guess what you are doing.
raw_text = """
twas brillig and the slithy toves
did gyre and gimble in the wabe
same mesa seam sameness samehood
"""
lexicon = sorted(set(raw_text.split()))
print "\nlexicon:", lexicon
#
# Assuming we want anagrams:
#
# Build an anagram dictionary
#
anagram_dict = defaultdict(set)
for word in lexicon:
anagram_dict[anagram_key(word)].add(word)
print "\nanagram_dict (len == %d):" % len(anagram_dict)
pprint.pprint(anagram_dict)
# now purge trivial entries
temp = {}
for k, v in anagram_dict.iteritems():
if len(v) != 1:
temp[k] = v
anagram_dict = temp
print "\nanagram_dict (len == %d):" % len(anagram_dict)
pprint.pprint(anagram_dict)
# Test cases
tests = "sam same mesa sameness samehood xsame samex".split()
default_set = frozenset()
for test in tests:
print
results = extract_by_letters_1(test, lexicon)
print test, [(result, check_anagrams(test, result)) for result in results]
# In the following statement, you can use set([test]) as the default
# if that produces a more useful or orthogonal result.
results = anagram_dict.get(anagram_key(test), default_set)
print test, [(result, check_anagrams(test, result)) for result in results]
Output:
lexicon: ['and', 'brillig', 'did', 'gimble', 'gyre', 'in', 'mesa', 'same', 'samehood', 'sameness', 'seam', 'slithy', 'the', 'toves', 'twas', 'wabe']
anagram_dict (len == 14):
defaultdict(<type 'set'>, {'abew': set(['wabe']), 'eht': set(['the']), 'egry': set(['gyre']), 'begilm': set(['gimble']), 'hilsty': set(['slithy']), 'aems': set(['mesa', 'seam', 'same']), 'bgiillr': set(['brillig']), 'ddi': set(['did']), 'eostv': set(['toves']), 'adehmoos': set(['samehood']), 'in': set(['in']), 'adn': set(['and']), 'aeemnsss': set(['sameness']), 'astw': set(['twas'])})
anagram_dict (len == 1):
{'aems': set(['mesa', 'same', 'seam'])}
sam [('mesa', False), ('samehood', False), ('seam', False), ('same', False)]
sam []
same [('mesa', True), ('samehood', False), ('seam', True), ('same', True)]
same [('mesa', True), ('seam', True), ('same', True)]
mesa [('mesa', True), ('samehood', False), ('seam', True), ('same', True)]
mesa [('mesa', True), ('seam', True), ('same', True)]
sameness [('sameness', True)]
sameness []
samehood [('samehood', True)]
samehood []
xsame []
xsame []
samex []
samex []
A:
You're trying to find all anagrams of 'letters'?
def anagrams(letters, words):
letters = sorted(letters)
result = []
for word in words:
if sorted(word.strip()) == letters:
result.append(word)
return result
|
Integer comparison in python slows everything down to a crawl
|
The following code is causing me enormous headaches:
def extract_by_letters(letters, dictionary):
for word in dictionary:
for letter in letters:
if word.count(letter) != letters.count(letter):
if word in dictionary: #I cant leave this line out
dictionary.remove(word)
return dictionary
First of all: the 'if word in dictionary' line. Why can't I leave this out? I get an error saying ValueError: list.remove(x): x not in list
But it is, obviously.
Second: Dictionary is a file of about 50,000 words separated by linebreaks. The above code takes about 2 minutes to run... Wayyy too long. I played with the code for a bit, and I found that the line:
if word.count(letter) != letters.count(letter):
seems to be causing all my problems. If I take that line out (which totally screws up the output), the function takes about 2 seconds to go through the dictionary.
I thought it was the count functions, but it's not.
if I change the if statement to something like:
print word.count(letter)
print letters.count(letter)
the function takes about 3 seconds to run.
I'm convinced it's the comparison. Any other suggestions? Is there a better way to do this?
Thanks in advance!
|
[
"The reason you get the exception is that if the letter count matches for more than one letter, you are trying to remove the word more than once\nThe reason it is so slow is that you have loops inside loops inside loops.\nIf you would write a sentence or two about what the function is supposed to do, it would be much easier to refactor it. In the mean time, this would stop you checking whether a word needs to be removed once you have already removed it.\ndef extract_by_letters(letters, dictionary):\n for word in dictionary[:]: # bad idea to change this while you iterate over it\n for letter in letters:\n if word.count(letter) != letters.count(letter):\n dictionary.remove(word)\n break\n return dictionary\n\nIf dictionary is a set you should get some speed up. If dictionary is a list this should give a huge speedup\n",
"Try building the output instead of deleting from it:\ndef extract_by_letters(letters, dictionary):\n d = []\n for word in dictionary:\n for letter in letters:\n if word.count(letter)>0:\n d.append(word)\n break\n return d\n\nOr, you could use regular expressions:\nimport re\ndef extract_by_letters(letters, dictionary):\n regex = re.compile('['+letters+']')\n d=[]\n for word in dictionary:\n if regex.search(word):\n d.append(word)\n return d\n\nOr, perhaps the simplest way:\nimport re\ndef extract_by_letters(letters, dictionary):\n regex = re.compile('['+letters+']')\n return [word for word in dictionary if regex.search(word)]\n\nThis last one takes no noticeable time to scan /usr/share/dict/words on my Mac, which is a list of 234936 words.\n",
"Here's a function that should offer a major speed-up:\ndef extract_by_letters(letters,dictionary):\n letdict = zip(set(letters),[letters.count(let) for let in set(letters)])\n outarr = []\n for word in dictionary:\n goodword = True\n for letter in letdict:\n if word.count(letter) != letdict[letter]:\n goodword = False\n break\n if goodword:\n outarr.append(word)\n return outarr\n\nHere are the optimizations I did:\n\nMade a dictionary of the letters with their corresponding frequencies. This way, you aren't using letters.count over and over again when you only need to do this process once and store the results.\nRather than removing the words from dictionary, I add them to an array that is returned from the function. If you have a huge dictionary, chances are that only a few words will match. Also, if the dictionary variable is an array (which I suspect), then every time you called remove it had to first search for the word in dictionary (linearly starting at the beginning) and then remove it. It is faster to remove by popping using the index of the word to be removed.\nBreaking out of the loop checking the letter counts whenever a mismatch is found. This prevents us from doing needless checks when we already have our answer.\n\nI wasn't sure if you had repeated letters in the letters variable or not so I made sure that it could handle that by using letdict. If you had letters repeated in your letters variable before, then you were checking the counts of those letters in the word repeatedly.\n",
"import pprint\nfrom collections import defaultdict\n\n# This is a best approximation to what Bryan is trying to do.\n# However the results are meaningless because the list is being\n# mutated during iteration over it. So I haven't shown the output.\n\ndef extract_by_letters_0(letters, input_list):\n dictionary = input_list.copy()\n for word in dictionary:\n for letter in letters:\n if word.count(letter) != letters.count(letter):\n if word in dictionary: #I cant leave this line out\n dictionary.remove(word)\n return dictionary\n\n# This avoids the mutation.\n# The results are anagrams PLUS letters that don't occur\n# in the query. E.g. \"same\" produces \"samehood\" but not \"sameness\"\n# (\"sameness\" has 3*\"s\" and 2*\"e\" instead of 1 of each)\n\ndef extract_by_letters_1(letters, input_list):\n dictionary = set(input_list)\n ripouts = set()\n for word in dictionary:\n for letter in letters:\n if word.count(letter) != letters.count(letter):\n ripouts.add(word)\n return dictionary - ripouts\n\ndef anagram_key(strg):\n return ''.join(sorted(list(strg)))\n\ndef check_anagrams(str1, str2):\n return sorted(list(str1)) == sorted(list(str2))\n\n# Advice: try algorithms like this out on a SMALL data set first.\n# Get it working correctly. Use different test cases. Have test code\n# however primitive that check your results.\n# Then if it runs slowly, helpers\n# don't have to guess what you are doing.\n\nraw_text = \"\"\"\ntwas brillig and the slithy toves\ndid gyre and gimble in the wabe\nsame mesa seam sameness samehood\n\"\"\"\n\nlexicon = sorted(set(raw_text.split()))\nprint \"\\nlexicon:\", lexicon\n#\n# Assuming we want anagrams:\n#\n# Build an anagram dictionary\n#\nanagram_dict = defaultdict(set)\nfor word in lexicon:\n anagram_dict[anagram_key(word)].add(word)\n\nprint \"\\nanagram_dict (len == %d):\" % len(anagram_dict)\npprint.pprint(anagram_dict)\n\n# now purge trivial entries\n\ntemp = {}\nfor k, v in anagram_dict.iteritems():\n if len(v) != 1:\n temp[k] = v\nanagram_dict = temp\nprint \"\\nanagram_dict (len == %d):\" % len(anagram_dict)\npprint.pprint(anagram_dict)\n\n# Test cases\n\ntests = \"sam same mesa sameness samehood xsame samex\".split()\ndefault_set = frozenset()\nfor test in tests:\n print\n results = extract_by_letters_1(test, lexicon)\n print test, [(result, check_anagrams(test, result)) for result in results]\n # In the following statement, you can use set([test]) as the default\n # if that produces a more useful or orthogonal result.\n results = anagram_dict.get(anagram_key(test), default_set)\n print test, [(result, check_anagrams(test, result)) for result in results]\n\nOutput: \nlexicon: ['and', 'brillig', 'did', 'gimble', 'gyre', 'in', 'mesa', 'same', 'samehood', 'sameness', 'seam', 'slithy', 'the', 'toves', 'twas', 'wabe']\n\nanagram_dict (len == 14):\ndefaultdict(<type 'set'>, {'abew': set(['wabe']), 'eht': set(['the']), 'egry': set(['gyre']), 'begilm': set(['gimble']), 'hilsty': set(['slithy']), 'aems': set(['mesa', 'seam', 'same']), 'bgiillr': set(['brillig']), 'ddi': set(['did']), 'eostv': set(['toves']), 'adehmoos': set(['samehood']), 'in': set(['in']), 'adn': set(['and']), 'aeemnsss': set(['sameness']), 'astw': set(['twas'])})\n\nanagram_dict (len == 1):\n{'aems': set(['mesa', 'same', 'seam'])}\n\nsam [('mesa', False), ('samehood', False), ('seam', False), ('same', False)]\nsam []\n\nsame [('mesa', True), ('samehood', False), ('seam', True), ('same', True)]\nsame [('mesa', True), ('seam', True), ('same', True)]\n\nmesa [('mesa', True), ('samehood', False), ('seam', True), ('same', True)]\nmesa [('mesa', True), ('seam', True), ('same', True)]\n\nsameness [('sameness', True)]\nsameness []\n\nsamehood [('samehood', True)]\nsamehood []\n\nxsame []\nxsame []\n\nsamex []\nsamex []\n\n",
"You're trying to find all anagrams of 'letters'?\ndef anagrams(letters, words):\n letters = sorted(letters)\n result = []\n for word in words:\n if sorted(word.strip()) == letters:\n result.append(word)\n return result\n\n"
] |
[
4,
2,
2,
1,
0
] |
[] |
[] |
[
"integer",
"loops",
"python"
] |
stackoverflow_0002309996_integer_loops_python.txt
|
Q:
Using Django, why would REMOTE_ADDR return 127.0.0.1 on a web server?
When getting the IP with request.META['REMOTE_ADDR'] code. This works fine on the local system but when hosted on a web server the ip got is 127.0.0.1 - How can this be resolved?
A:
Your web server is probably behind a load balancer. You can try using request.META['HTTP_X_FORWARDED_FOR'].
Or better, look at the django book, chapter 15 - What’s Middleware? and Reverse Proxy Support (X-Forwarded-For Middleware) sections.
A:
If you are behind a proxy and running apache as the webserver you could use mod_rpaf. The proxy only needs to send X-Forwarded-For or X-Real-IP headers.
http://stderr.net/apache/rpaf/
|
Using Django, why would REMOTE_ADDR return 127.0.0.1 on a web server?
|
When getting the IP with request.META['REMOTE_ADDR'] code. This works fine on the local system but when hosted on a web server the ip got is 127.0.0.1 - How can this be resolved?
|
[
"Your web server is probably behind a load balancer. You can try using request.META['HTTP_X_FORWARDED_FOR'].\nOr better, look at the django book, chapter 15 - What’s Middleware? and Reverse Proxy Support (X-Forwarded-For Middleware) sections.\n",
"If you are behind a proxy and running apache as the webserver you could use mod_rpaf. The proxy only needs to send X-Forwarded-For or X-Real-IP headers.\nhttp://stderr.net/apache/rpaf/\n"
] |
[
10,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002144848_django_python.txt
|
Q:
Django: request.META['REMOTE_ADDR'] is always '127.0.0.1'
I have an application running with debug=True on a remote host somewhere. Now somehow every time I access REMOTE_ADDR it returns 127.0.0.1 no matter where the request is from.
I'm not sure where to start and why this is happening.
A:
Do you have any kind of proxy, gateway, or load balancer running on that remote host? That's the sort of thing that would cause connections to appear to be from 127.0.0.1 (because that's where the immediate connection is from, as far as the web server is concerned).
A:
If you are behind a proxy and running apache as the webserver you could use mod_rpaf. The proxy only needs to send X-Forwarded-For or X-Real-IP headers.
http://stderr.net/apache/rpaf/
|
Django: request.META['REMOTE_ADDR'] is always '127.0.0.1'
|
I have an application running with debug=True on a remote host somewhere. Now somehow every time I access REMOTE_ADDR it returns 127.0.0.1 no matter where the request is from.
I'm not sure where to start and why this is happening.
|
[
"Do you have any kind of proxy, gateway, or load balancer running on that remote host? That's the sort of thing that would cause connections to appear to be from 127.0.0.1 (because that's where the immediate connection is from, as far as the web server is concerned).\n",
"If you are behind a proxy and running apache as the webserver you could use mod_rpaf. The proxy only needs to send X-Forwarded-For or X-Real-IP headers.\nhttp://stderr.net/apache/rpaf/\n"
] |
[
7,
0
] |
[] |
[] |
[
"django",
"http",
"python"
] |
stackoverflow_0001779464_django_http_python.txt
|
Q:
How to generate a module object from a code object in Python
Given that I have the code object for a module, how do I get the corresponding module object?
It looks like moduleNames = {}; exec code in moduleNames does something very close to what I want. It returns the globals declared in the module into a dictionary. But if I want the actual module object, how do I get it?
EDIT:
It looks like you can roll your own module object. The module type isn't conveniently documented, but you can do something like this:
import sys
module = sys.__class__
del sys
foo = module('foo', 'Doc string')
foo.__file__ = 'foo.pyc'
exec code in foo.__dict__
A:
As a comment already indicates, in today's Python the preferred way to instantiate types that don't have built-in names is to call the type obtained via the types module from the standard library:
>>> import types
>>> m = types.ModuleType('m', 'The m module')
note that this does not automatically insert the new module in sys.modules:
>>> import sys
>>> sys.modules['m']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'm'
That's a task you must perform by hand:
>>> sys.modules['m'] = m
>>> sys.modules['m']
<module 'm' (built-in)>
This can be important, since a module's code object normally executes after the module's added to sys.modules -- for example, it's perfectly correct for such code to refer to sys.modules[__name__], and that would fail (KeyError) if you forgot this step. After this step, and setting m.__file__ as you already have in your edit,
>>> code = compile("a=23", "m.py", "exec")
>>> exec code in m.__dict__
>>> m.a
23
(or the Python 3 equivalent where exec is a function, if Python 3 is what you're using, of course;-) is correct (of course, you'll normally have obtained the code object by subtler means than compiling a string, but that's not material to your question;-).
In older versions of Python you would have used the new module instead of the types module to make a new module object at the start, but new is deprecated since Python 2.6 and removed in Python 3.
|
How to generate a module object from a code object in Python
|
Given that I have the code object for a module, how do I get the corresponding module object?
It looks like moduleNames = {}; exec code in moduleNames does something very close to what I want. It returns the globals declared in the module into a dictionary. But if I want the actual module object, how do I get it?
EDIT:
It looks like you can roll your own module object. The module type isn't conveniently documented, but you can do something like this:
import sys
module = sys.__class__
del sys
foo = module('foo', 'Doc string')
foo.__file__ = 'foo.pyc'
exec code in foo.__dict__
|
[
"As a comment already indicates, in today's Python the preferred way to instantiate types that don't have built-in names is to call the type obtained via the types module from the standard library:\n>>> import types\n>>> m = types.ModuleType('m', 'The m module')\n\nnote that this does not automatically insert the new module in sys.modules:\n>>> import sys\n>>> sys.modules['m']\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nKeyError: 'm'\n\nThat's a task you must perform by hand:\n>>> sys.modules['m'] = m\n>>> sys.modules['m']\n<module 'm' (built-in)>\n\nThis can be important, since a module's code object normally executes after the module's added to sys.modules -- for example, it's perfectly correct for such code to refer to sys.modules[__name__], and that would fail (KeyError) if you forgot this step. After this step, and setting m.__file__ as you already have in your edit,\n>>> code = compile(\"a=23\", \"m.py\", \"exec\")\n>>> exec code in m.__dict__\n>>> m.a\n23\n\n(or the Python 3 equivalent where exec is a function, if Python 3 is what you're using, of course;-) is correct (of course, you'll normally have obtained the code object by subtler means than compiling a string, but that's not material to your question;-).\nIn older versions of Python you would have used the new module instead of the types module to make a new module object at the start, but new is deprecated since Python 2.6 and removed in Python 3.\n"
] |
[
25
] |
[] |
[] |
[
"bytecode",
"python"
] |
stackoverflow_0002315044_bytecode_python.txt
|
Q:
Python daemon to watch a folder and update a database
This is specifically geared towards managing MP3 files, but it should easily work for any directory structure with a lot of files.
I want to find or write a daemon (preferably in Python) that will watch a folder with many subfolders that should all contain X number of MP3 files. Any time a file is added, updated or deleted, it should reflect that in a database (preferably PostgreSQL). I am willing to accept if a file is simply moved that the respective rows are deleted and recreated anew but updating existing rows would make me the happiest.
The Stack Overflow question Managing a large collection of music has a little of what I want.
I basically just want a database that I can then do whatever I want to with. My most up-to-date database as of now is my iTunes.xml file, but I don't want to rely on that too much as I don't always want to rely on iTunes for my music management. I see plenty of projects out there that do a little of what I want but in a format that either I can't access or is just more complex than I want. If there is some media player out there that can watch a folder and update a database that is easily accessible then I am all for it.
The reason I'm leaning towards writing my own is because it would be nice to choose my database and schema myself.
A:
Another answer already suggested pyinotify for Linux, let me add watch_directory for Windows (a good discussion of the possibilities in Windows is here, the module's an example) and fsevents on the Mac (unfortunately I don't think there's a single cross-platform module offering a uniform interface to these various system-specific ways to get directory-change notification events).
Once you manage to get such events, updating an appropriate SQL database is simple!-)
A:
If you use Linux, you can use PyInotify.
inotify can notify you about filesystem events when your program is running.
A:
IMO, the best media player that has these features is Winamp. It rescans the music folders every X minutes, which is enough for music (but of course a little less efficient than letting the operating system watch for changes).
But as you were asking for suggestions on writing your own, you could make use of pyinotify (Linux only). If you're running Windows, you can use the ReadDirectoryChangesW API call
|
Python daemon to watch a folder and update a database
|
This is specifically geared towards managing MP3 files, but it should easily work for any directory structure with a lot of files.
I want to find or write a daemon (preferably in Python) that will watch a folder with many subfolders that should all contain X number of MP3 files. Any time a file is added, updated or deleted, it should reflect that in a database (preferably PostgreSQL). I am willing to accept if a file is simply moved that the respective rows are deleted and recreated anew but updating existing rows would make me the happiest.
The Stack Overflow question Managing a large collection of music has a little of what I want.
I basically just want a database that I can then do whatever I want to with. My most up-to-date database as of now is my iTunes.xml file, but I don't want to rely on that too much as I don't always want to rely on iTunes for my music management. I see plenty of projects out there that do a little of what I want but in a format that either I can't access or is just more complex than I want. If there is some media player out there that can watch a folder and update a database that is easily accessible then I am all for it.
The reason I'm leaning towards writing my own is because it would be nice to choose my database and schema myself.
|
[
"Another answer already suggested pyinotify for Linux, let me add watch_directory for Windows (a good discussion of the possibilities in Windows is here, the module's an example) and fsevents on the Mac (unfortunately I don't think there's a single cross-platform module offering a uniform interface to these various system-specific ways to get directory-change notification events).\nOnce you manage to get such events, updating an appropriate SQL database is simple!-)\n",
"If you use Linux, you can use PyInotify.\ninotify can notify you about filesystem events when your program is running.\n",
"IMO, the best media player that has these features is Winamp. It rescans the music folders every X minutes, which is enough for music (but of course a little less efficient than letting the operating system watch for changes).\nBut as you were asking for suggestions on writing your own, you could make use of pyinotify (Linux only). If you're running Windows, you can use the ReadDirectoryChangesW API call\n"
] |
[
8,
3,
0
] |
[] |
[] |
[
"daemon",
"database",
"filesystems",
"python"
] |
stackoverflow_0002314892_daemon_database_filesystems_python.txt
|
Q:
UTF-8 and upper()
I want to transform UTF-8 strings using built-in functions such as upper() and capitalize().
For example:
>>> mystring = "işğüı"
>>> print mystring.upper()
Işğüı # should be İŞĞÜI instead.
How can I fix this?
A:
Do not perform actions on encoded strings; decode to unicode first.
>>> mystring = "işğüı"
>>> print mystring.decode('utf-8').upper()
IŞĞÜI
A:
It's actually best, as a general strategy, to always keep your text as Unicode once it's in memory: decode it at the moment it's input, and encode it exactly at the moment you need to output it, if there are specific encoding requirements at input and/or input times.
Even if you don't choose to adopt this general strategy (and you should!), the only sound way to perform the task you require is still to decode, process, encode again -- never to work on the encoded forms. I.e.:
mystring = "işğüı"
print mystring.decode('utf-8').upper().encode('utf-8')
assuming you're constrained to encoded strings at assignment and for output purposes. (The output constraint is unfortunately realistic, the assignment constraint isn't -- just do mystring = u"işğüı", making it unicode from the start, and save yourself at least the .decode call!-)
|
UTF-8 and upper()
|
I want to transform UTF-8 strings using built-in functions such as upper() and capitalize().
For example:
>>> mystring = "işğüı"
>>> print mystring.upper()
Işğüı # should be İŞĞÜI instead.
How can I fix this?
|
[
"Do not perform actions on encoded strings; decode to unicode first.\n>>> mystring = \"işğüı\"\n>>> print mystring.decode('utf-8').upper()\nIŞĞÜI\n\n",
"It's actually best, as a general strategy, to always keep your text as Unicode once it's in memory: decode it at the moment it's input, and encode it exactly at the moment you need to output it, if there are specific encoding requirements at input and/or input times.\nEven if you don't choose to adopt this general strategy (and you should!), the only sound way to perform the task you require is still to decode, process, encode again -- never to work on the encoded forms. I.e.:\nmystring = \"işğüı\"\nprint mystring.decode('utf-8').upper().encode('utf-8')\n\nassuming you're constrained to encoded strings at assignment and for output purposes. (The output constraint is unfortunately realistic, the assignment constraint isn't -- just do mystring = u\"işğüı\", making it unicode from the start, and save yourself at least the .decode call!-)\n"
] |
[
14,
9
] |
[] |
[] |
[
"case_sensitive",
"python"
] |
stackoverflow_0002315451_case_sensitive_python.txt
|
Q:
Using python to run other programs
I have a command that works great on the command line. It has lots of arguments like cmd --thing foo --stuff bar -a b input output
I want to run this from python and block waiting for it to complete. As the script prints things to stdout and stderr I want it to be immediately shown to the user.
What is the right module for this?
I've tried:
import commands
output = commands.getoutput("cmd --thing foo --stuff bar -a b input output")
print output
this works great except the stdout isn't returned until the end.
import os
os.system("cmd --thing foo --stuff bar -a b input output")
this prints all the output when the cmd is actually finished.
import subprocess
subprocess.call(["cmd", "--thing foo", "--stuff bar", "-a b", "input", "output"])
this doesn't pass the parameters correctly somehow (I haven't been able to find the exact problem, but cmd is rejecting my input). If I put echo as the first parameter, it prints out the command which works perfectly when I paste it directly into the terminal.
import subprocess
subprocess.call("cmd --thing foo --stuff bar -a b input output")
exactly the same as above.
A:
You have to quote each field separately, ie. split the options from their arguments.
import subprocess
output = subprocess.call(["cmd", "--thing", "foo", "--stuff", "bar", "-a", "b", "input", "output"])
otherwise you are effectively running cmd like this
$ cmd --thing\ foo --stuff\ bar -a\ b input output
To get the output into a pipe you need to call it slightly differently
import subprocess
output = subprocess.Popen(["cmd", "--thing", "foo", "--stuff", "bar", "-a", "b", "input", "output"],stdout=subprocess.PIPE)
output.stdout # <open file '<fdopen>', mode 'rb'>
A:
If you don't need to process the output in your code, only to show it to the user as it happens (it's not clear from your Q, and it seems that way from your own self-answer), simplest is:
rc = subprocess.call(
["cmd", "--thing", "foo", "--stuff", "bar",
"-a", "b", "input", "output"])
print "Return code was", rc
i.e., just avoid any use of pipes -- let stdout and stderr just show on the terminal. That should avoid any problem with buffering. Once you put pipes in the picture, buffering generally is a problem if you want to show output as it happens (I'm surprised your self-answer doesn't have that problem;-).
For both showing and capturing, BTW, I always recomment pexpect (and wexpect on Windows) exactly to work around the buffering issue.
A:
Wouldn't commands.getstatusoutput() work? It'll return your status right away pretty sure.
A:
A coworker just showed me this:
import os
import sys
for line in os.popen("cmd --thing foo --stuff bar -a b input output", "r"):
print line
sys.stdout.flush()
and it is working :)
|
Using python to run other programs
|
I have a command that works great on the command line. It has lots of arguments like cmd --thing foo --stuff bar -a b input output
I want to run this from python and block waiting for it to complete. As the script prints things to stdout and stderr I want it to be immediately shown to the user.
What is the right module for this?
I've tried:
import commands
output = commands.getoutput("cmd --thing foo --stuff bar -a b input output")
print output
this works great except the stdout isn't returned until the end.
import os
os.system("cmd --thing foo --stuff bar -a b input output")
this prints all the output when the cmd is actually finished.
import subprocess
subprocess.call(["cmd", "--thing foo", "--stuff bar", "-a b", "input", "output"])
this doesn't pass the parameters correctly somehow (I haven't been able to find the exact problem, but cmd is rejecting my input). If I put echo as the first parameter, it prints out the command which works perfectly when I paste it directly into the terminal.
import subprocess
subprocess.call("cmd --thing foo --stuff bar -a b input output")
exactly the same as above.
|
[
"You have to quote each field separately, ie. split the options from their arguments.\nimport subprocess\noutput = subprocess.call([\"cmd\", \"--thing\", \"foo\", \"--stuff\", \"bar\", \"-a\", \"b\", \"input\", \"output\"])\n\notherwise you are effectively running cmd like this\n$ cmd --thing\\ foo --stuff\\ bar -a\\ b input output\n\nTo get the output into a pipe you need to call it slightly differently\nimport subprocess\noutput = subprocess.Popen([\"cmd\", \"--thing\", \"foo\", \"--stuff\", \"bar\", \"-a\", \"b\", \"input\", \"output\"],stdout=subprocess.PIPE)\noutput.stdout # <open file '<fdopen>', mode 'rb'>\n\n",
"If you don't need to process the output in your code, only to show it to the user as it happens (it's not clear from your Q, and it seems that way from your own self-answer), simplest is:\nrc = subprocess.call(\n [\"cmd\", \"--thing\", \"foo\", \"--stuff\", \"bar\", \n \"-a\", \"b\", \"input\", \"output\"])\nprint \"Return code was\", rc\n\ni.e., just avoid any use of pipes -- let stdout and stderr just show on the terminal. That should avoid any problem with buffering. Once you put pipes in the picture, buffering generally is a problem if you want to show output as it happens (I'm surprised your self-answer doesn't have that problem;-).\nFor both showing and capturing, BTW, I always recomment pexpect (and wexpect on Windows) exactly to work around the buffering issue.\n",
"Wouldn't commands.getstatusoutput() work? It'll return your status right away pretty sure.\n",
"A coworker just showed me this:\nimport os\nimport sys\nfor line in os.popen(\"cmd --thing foo --stuff bar -a b input output\", \"r\"):\n print line\n sys.stdout.flush()\n\nand it is working :)\n"
] |
[
7,
4,
2,
1
] |
[] |
[] |
[
"python",
"subprocess",
"unix"
] |
stackoverflow_0002314206_python_subprocess_unix.txt
|
Q:
In Django, why does this error say that my column can't be null?
picture_url = models.CharField(max_length=2000)
A:
You'll need to add null=True if the column can be null:
picture_url = models.CharField(max_length=2000, null=True)
A:
By default fields have null set to False try this
picture_url = models.CharField(max_length=2000, blank=True)
http://docs.djangoproject.com/en/1.1/ref/models/fields/#null
|
In Django, why does this error say that my column can't be null?
|
picture_url = models.CharField(max_length=2000)
|
[
"You'll need to add null=True if the column can be null:\npicture_url = models.CharField(max_length=2000, null=True)\n\n",
"By default fields have null set to False try this\npicture_url = models.CharField(max_length=2000, blank=True)\n\nhttp://docs.djangoproject.com/en/1.1/ref/models/fields/#null\n"
] |
[
3,
0
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002315506_database_django_mysql_python.txt
|
Q:
How to sort a collection of objects by an variable they all hold?
I have a class named Individual, which has a variable, self.fitness. I have a collection of these Individual instances and I'd like to sort them by their fitness. How is this done in python?
A:
from operator import attrgetter
sorted(item_list, key=attrgetter('fitness'))
item_list can be any iterable. Here is an example
>>> class C(object):
... def __init__(self, fitness):
... self.fitness=fitness
... def __repr__(self):
... return "fitness: %s"%self.fitness
...
>>>
>>> from operator import attrgetter
>>> L=[C(10),C(4),C(1),C(99)]
>>> sorted(L, key=attrgetter('fitness'))
[fitness: 1, fitness: 4, fitness: 10, fitness: 99]
>>> S=set(L)
>>> sorted(S, key=attrgetter('fitness'))
[fitness: 1, fitness: 4, fitness: 10, fitness: 99]
|
How to sort a collection of objects by an variable they all hold?
|
I have a class named Individual, which has a variable, self.fitness. I have a collection of these Individual instances and I'd like to sort them by their fitness. How is this done in python?
|
[
"from operator import attrgetter\nsorted(item_list, key=attrgetter('fitness'))\n\nitem_list can be any iterable. Here is an example\n>>> class C(object):\n... def __init__(self, fitness):\n... self.fitness=fitness\n... def __repr__(self):\n... return \"fitness: %s\"%self.fitness\n... \n>>> \n>>> from operator import attrgetter\n>>> L=[C(10),C(4),C(1),C(99)]\n>>> sorted(L, key=attrgetter('fitness'))\n[fitness: 1, fitness: 4, fitness: 10, fitness: 99]\n>>> S=set(L)\n>>> sorted(S, key=attrgetter('fitness'))\n[fitness: 1, fitness: 4, fitness: 10, fitness: 99]\n\n"
] |
[
6
] |
[] |
[] |
[
"python",
"sorting"
] |
stackoverflow_0002315659_python_sorting.txt
|
Q:
In Python, how do I loop through the dictionary and change the value if it equals something?
If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
for k, v in mydict.items():
if v is None:
... right?
A:
for k, v in mydict.iteritems():
if v is None:
mydict[k] = ''
In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.
In Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here.
Refer to this post.
A:
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
A:
Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:
mydict = dict((k, v if v else '') for k, v in mydict.items())
|
In Python, how do I loop through the dictionary and change the value if it equals something?
|
If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
for k, v in mydict.items():
if v is None:
... right?
|
[
"for k, v in mydict.iteritems():\n if v is None:\n mydict[k] = ''\n\nIn a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.\nIn Python3 however the code gives AttributeError: 'dict' object has no attribute 'iteritems' error. Use items() instead of iteritems() here. \nRefer to this post.\n",
"You could create a dict comprehension of just the elements whose values are None, and then update back into the original:\ntmp = dict((k,\"\") for k,v in mydict.iteritems() if v is None)\nmydict.update(tmp)\n\nUpdate - did some performance tests\nWell, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.\n",
"Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:\nmydict = dict((k, v if v else '') for k, v in mydict.items())\n\n"
] |
[
174,
16,
12
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0002315520_dictionary_python.txt
|
Q:
pyplot.ginput() causes axes to change?
I am encountering some strange behavior with using the matplotlib.pyplot ginput() function to store clicked points. On the first click, the ranges of the axes of the clicked image change to add 200 on each side. The image remains with this border of whitespace until something new is plotted.
Example code:
import matplotlib.pyplot as plt
plt.imshow(im1)
x = plt.ginput(4)
On the first click of the mouse, the axes change from (0, imageWidth) and (0, imageHeight) to (-200, imageWidth+200) and (-200, imageHeight+200).
The image itself is not affected in any way.
The same behavior occurs when ginput is called on the current figure.
Has anyone else encountered this? Any explanations? Fixes?
A:
Try
plt.imshow(im1)
plt.axis('image')
x = plt.ginput(4)
I learned this here.
|
pyplot.ginput() causes axes to change?
|
I am encountering some strange behavior with using the matplotlib.pyplot ginput() function to store clicked points. On the first click, the ranges of the axes of the clicked image change to add 200 on each side. The image remains with this border of whitespace until something new is plotted.
Example code:
import matplotlib.pyplot as plt
plt.imshow(im1)
x = plt.ginput(4)
On the first click of the mouse, the axes change from (0, imageWidth) and (0, imageHeight) to (-200, imageWidth+200) and (-200, imageHeight+200).
The image itself is not affected in any way.
The same behavior occurs when ginput is called on the current figure.
Has anyone else encountered this? Any explanations? Fixes?
|
[
"Try \nplt.imshow(im1)\nplt.axis('image')\nx = plt.ginput(4)\n\nI learned this here.\n"
] |
[
4
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0002315656_matplotlib_python.txt
|
Q:
Why does Django's ModelForm validation think that this is invalid?
I have what looks to me to be a pretty simple setup of model, modelform and a view playing with the two. The only hitch is that the model has a user property that can't be POSTed to the form, rather it should be populated by request.user so I have this:
# models.py
class Update(models.Model):
user = models.ForeignKey(User, related_name="updates")
organisation = models.ForeignKey(Organisation, related_name="updates")
publish = models.BooleanField(default=True)
class UpdateForm(ModelForm):
name = forms.CharField(
max_length=140,
required=False,
widget=forms.TextInput(attrs={"class": "blankable"})
)
class Meta(NodeForm.Meta):
model = Update
# views.py
def status(request):
from myproject.organisations.models import Organisation
from myproject.feeds.models import Update, UpdateForm
stream = 0
if request.method == "POST":
o = request.POST.get("organisation")
if not o or request.user not in Organisation.objects.get(pk=request.POST.get("organisation")).administrators.all():
return HttpResponseRedirect(reverse("ethico.core.views.index"))
f = UpdateForm(request.POST, instance=Update(user=request.user))
if f.is_valid():
stream = f.save()
else:
stream = f.errors
...
Whenever I run this, I always get the same error:
user: This field is required.
I've tried setting f with the initial attribute using {"user": 1} and it still says that it's required. I've tried passing in a modified POST by copying the request.POST into a new variable and modifying that before passing it to UpdateForm but that's ugly. What am I forgetting here?
A:
You should try excluding the user field in the form
class UpdateForm(ModelForm):
name = forms.CharField(
max_length=140,
required=False,
widget=forms.TextInput(attrs={"class": "blankable"})
)
class Meta:
model = Update
exclude = ("user",)
http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#s-using-a-subset-of-fields-on-the-form
|
Why does Django's ModelForm validation think that this is invalid?
|
I have what looks to me to be a pretty simple setup of model, modelform and a view playing with the two. The only hitch is that the model has a user property that can't be POSTed to the form, rather it should be populated by request.user so I have this:
# models.py
class Update(models.Model):
user = models.ForeignKey(User, related_name="updates")
organisation = models.ForeignKey(Organisation, related_name="updates")
publish = models.BooleanField(default=True)
class UpdateForm(ModelForm):
name = forms.CharField(
max_length=140,
required=False,
widget=forms.TextInput(attrs={"class": "blankable"})
)
class Meta(NodeForm.Meta):
model = Update
# views.py
def status(request):
from myproject.organisations.models import Organisation
from myproject.feeds.models import Update, UpdateForm
stream = 0
if request.method == "POST":
o = request.POST.get("organisation")
if not o or request.user not in Organisation.objects.get(pk=request.POST.get("organisation")).administrators.all():
return HttpResponseRedirect(reverse("ethico.core.views.index"))
f = UpdateForm(request.POST, instance=Update(user=request.user))
if f.is_valid():
stream = f.save()
else:
stream = f.errors
...
Whenever I run this, I always get the same error:
user: This field is required.
I've tried setting f with the initial attribute using {"user": 1} and it still says that it's required. I've tried passing in a modified POST by copying the request.POST into a new variable and modifying that before passing it to UpdateForm but that's ugly. What am I forgetting here?
|
[
"You should try excluding the user field in the form\nclass UpdateForm(ModelForm):\n name = forms.CharField(\n max_length=140,\n required=False,\n widget=forms.TextInput(attrs={\"class\": \"blankable\"})\n )\n\n class Meta:\n model = Update\n exclude = (\"user\",)\n\nhttp://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#s-using-a-subset-of-fields-on-the-form\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002315086_django_python.txt
|
Q:
Unescape a string inside a string
I am working with urllib2, and trying to extract the headers in a printable form from a Response object.
Presently I am printing str(response.info()), however what is printed, is itself a Python string (at least to my understanding).
(Pdb) p str(response.info())
'Date: Tue, 23 Feb 2010 03:12:26 GMT\r\nServer: Apache\r\nVary: Accept-Encoding,User-Agent\r\nContent-Encoding: gzip\r\nContent-Length: 9045\r\nConnection: close\r\nContent-Type: text/html; charset=ISO-8859-1\r\n'
I need to turn that string into an "actual" string, such as by evaluation or something similar. The best theoretical solution I've found is to use:
s = str(response.info())
print s.decode("string_escape")
But this does not work. Further adding to the confusion is how to handle the quotes within the string, calling eval(s) and str(s) do not work either.
Is there some better way to extract the raw headers in the response without quoting, or a method to decode the string s as above?
A:
str(info()) does give a normal string:
>>> import urllib2
>>> f = urllib2.urlopen('http://tejp.de')
>>> print str(f.info())
Connection: close
Vary: Accept-Encoding
Content-Type: text/html
Accept-Ranges: bytes
ETag: "-807357257"
Last-Modified: Wed, 01 Jul 2009 10:05:34 GMT
Content-Length: 285
Date: Tue, 23 Feb 2010 03:24:10 GMT
Server: lighttpd/1.4.19
It's only the debugger's p command which prints the string in escaped form.
A:
response.info() returns a httplib.HTTPMessage, which behaves like a mapping:
info = response.info()
for k, v in info.items():
print '%s: %s' % (k, v)
So in short, you're doing it wrong.
A:
From pdb, this should work:
print str(response.info())
Not sure if that answers your question, though.
|
Unescape a string inside a string
|
I am working with urllib2, and trying to extract the headers in a printable form from a Response object.
Presently I am printing str(response.info()), however what is printed, is itself a Python string (at least to my understanding).
(Pdb) p str(response.info())
'Date: Tue, 23 Feb 2010 03:12:26 GMT\r\nServer: Apache\r\nVary: Accept-Encoding,User-Agent\r\nContent-Encoding: gzip\r\nContent-Length: 9045\r\nConnection: close\r\nContent-Type: text/html; charset=ISO-8859-1\r\n'
I need to turn that string into an "actual" string, such as by evaluation or something similar. The best theoretical solution I've found is to use:
s = str(response.info())
print s.decode("string_escape")
But this does not work. Further adding to the confusion is how to handle the quotes within the string, calling eval(s) and str(s) do not work either.
Is there some better way to extract the raw headers in the response without quoting, or a method to decode the string s as above?
|
[
"str(info()) does give a normal string:\n>>> import urllib2\n>>> f = urllib2.urlopen('http://tejp.de')\n>>> print str(f.info())\nConnection: close\nVary: Accept-Encoding\nContent-Type: text/html\nAccept-Ranges: bytes\nETag: \"-807357257\"\nLast-Modified: Wed, 01 Jul 2009 10:05:34 GMT\nContent-Length: 285\nDate: Tue, 23 Feb 2010 03:24:10 GMT\nServer: lighttpd/1.4.19\n\nIt's only the debugger's p command which prints the string in escaped form.\n",
"response.info() returns a httplib.HTTPMessage, which behaves like a mapping:\ninfo = response.info()\nfor k, v in info.items():\n print '%s: %s' % (k, v)\n\nSo in short, you're doing it wrong.\n",
"From pdb, this should work:\nprint str(response.info())\n\nNot sure if that answers your question, though.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"http",
"python",
"string"
] |
stackoverflow_0002315889_http_python_string.txt
|
Q:
Get number of modified rows after sqlite3 execute in Python
When performing SQL statements such as UPDATE, and INSERT, the usual .fetch*() methods on the Cursor instance obviously don't apply to the number of rows modified.
In the event of executing one of the aforementioned statements, what is the correct way to obtain the corresponding row count in Python, and the corresponding API in the Sqlite3 C interface?
A:
After calling your Cursor.execute*() methods with your UPDATE or INSERT statements you can use Cursor.rowcount to see the # of rows affected by the execute call.
If I had to guess I would say the python lib is calling int sqlite3_changes(sqlite3*) from the C API but I have not looked at the code so I can't say for sure.
|
Get number of modified rows after sqlite3 execute in Python
|
When performing SQL statements such as UPDATE, and INSERT, the usual .fetch*() methods on the Cursor instance obviously don't apply to the number of rows modified.
In the event of executing one of the aforementioned statements, what is the correct way to obtain the corresponding row count in Python, and the corresponding API in the Sqlite3 C interface?
|
[
"After calling your Cursor.execute*() methods with your UPDATE or INSERT statements you can use Cursor.rowcount to see the # of rows affected by the execute call.\nIf I had to guess I would say the python lib is calling int sqlite3_changes(sqlite3*) from the C API but I have not looked at the code so I can't say for sure.\n"
] |
[
41
] |
[] |
[] |
[
"c",
"python",
"sqlite"
] |
stackoverflow_0002316003_c_python_sqlite.txt
|
Q:
How to create a dictionary of integer pairs from a file in python
If I have a file of pairs of integer IDs, followed by a value, I'd like to create this into a dictionary. Each separate term is separated by a newline. I want to make sure these are all held as ints. How can I do this?
edit: as requested, a sample.
9 120
10 12
11 4
12 1
13 515
14 32
A:
d={}
f=open("file")
for line in f:
a,b=map( int, line.split() )
d[a]=b
f.close()
print d
output
$ cat file
9 120
10 12
11 4
12 1
13 515
14 32
$ ./python.py
{9: 120, 10: 12, 11: 4, 12: 1, 13: 515, 14: 32}
|
How to create a dictionary of integer pairs from a file in python
|
If I have a file of pairs of integer IDs, followed by a value, I'd like to create this into a dictionary. Each separate term is separated by a newline. I want to make sure these are all held as ints. How can I do this?
edit: as requested, a sample.
9 120
10 12
11 4
12 1
13 515
14 32
|
[
"d={}\nf=open(\"file\")\nfor line in f:\n a,b=map( int, line.split() ) \n d[a]=b\nf.close()\nprint d\n\noutput\n$ cat file\n9 120\n10 12\n11 4\n12 1\n13 515\n14 32\n\n$ ./python.py\n{9: 120, 10: 12, 11: 4, 12: 1, 13: 515, 14: 32}\n\n"
] |
[
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002316150_python.txt
|
Q:
trouble writing to file in "for line in" iterator in Python script
This seems to be an embarrassingly simple question, but, after a day of reading over How-To's and manuals, it must be asked.
I'm writing many lines to a few files using a few nested loops, inserting some static strings and copying lines over from other files over and over again. The output appears to be a single copy of the static strings and all of the lines I want to copy from other files, instead of multiple copies of the strings combined with the copied lines.
I made a test script that I thought would mimic the behaviour, but it behaves perfectly:
for i in range(10):
f = open('output.txt','w')
f.write( "---------------------------\n" )
FILE1 = open('test1.txt','r')
for line in FILE1:
f.write( "... compliments of loop #1 ...\n" )
f.write( line )
FILE1.close()
f.write( "\n##########################\n" )
FILE2 = open('test2.txt','r')
for line in FILE2:
f.write( "... compliments of loop #1 ...\n" )
f.write( line )
FILE2.close()
f.write( "\n++++++++++++++++++++++++++\n" )
The output is as expected: the static strings interleaved with copied strings. My real, ugly script, however, doesn't do this. I don't want to paste the whole thing in here, but will include as much as I think is relevant (and I'll probably get that wrong, too, 'cause I don't know what's going on). It references an array of objects - I won't include the class, as it seems to behave.
for i in range(10):
print "script-%s-%i-%s%s" % (cities[i].user,i,cities[i].name,cities[i].coords)
f = open("script-%s-%i-%s%s" % (cities[i].user,i,cities[i].name,cities[i].coords),'w')
f.write( "//\n" )
f.write( "//\n// %s - %s %s\n" % (cities[i].user,cities[i].name,cities[i].coords) )
f.write( "//\n" )
f.write( "//\n" )
npc10 = open("script-%s-npc10-%i.txt" % (cities[i].user,i),'r')
for line in npc10:
f.write( "ifgosub ( m_city.AnyIdleHero(%s) == false ) wait_for_big_hero\n" % (cities[i].hero) )
f.write( "ifgosub ( m_city.IsArmyReady(a:%i,s:%i,w:%i,wo:%i) == false ) gosub check_npc10\n" % (lvl10.arch,lvl10.scout,lvl10.warr,lvl10.work) )
f.write( "ifgosub ( m_city.IsArmyReady(a:%i,s:%i,w:%i,wo:%i) == false ) farm_npc5\n" % (lvl10.arch,lvl10.scout,lvl10.warr,lvl10.work) )
f.write( "ifgosub ( m_city.AnyIdleHero(%s) == false ) wait_for_big_hero\n" % (cities[i].hero) )
f.write( line )
npc10.close()
f.write( "\n//\n" )
f.write( "label farm_npc5\n" )
npc5 = open("script-%s-npc5-%i.txt" % (cities[i].user,i),'r')
for line in npc5:
f.write( "sleep 5\n" )
f.write( line )
npc5.close()
f.write( "\n//\n" )
# ... 107 lines of static f.write's
f.close()
Sample of one of the input files ( script-%s-npc10-%i.txt" % (cities[i].user,i) ) - they are all very similar:
attack 456,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,215 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 12m 34s
Sample of one of the output files
( "script-%s-%i-%s%s" % (cities[i].user,i,cities[i].name,cities[i].coords) ):
//
// user1 - cityname1 (456,456)
//
//
ifgosub ( m_city.AnyIdleHero(Alfonso) == false ) wait_for_big_hero
ifgosub ( m_city.IsArmyReady(a:92150,s:2000,w:2000,wo:2000) == false ) gosub check_npc10
ifgosub ( m_city.IsArmyReady(a:92150,s:2000,w:2000,wo:2000) == false ) farm_npc5
ifgosub ( m_city.AnyIdleHero(Alfonso) == false ) wait_for_big_hero
attack 456,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,215 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 12m 34s
//
label farm_npc5
sleep 5
attack 354,159 Alfred b:50,t:40 //Distance: 1 Mission time: 13m 20s
attack 789,654 Alfred b:50,t:40 //Distance: 2 Mission time: 26m 40s
attack 125,456 Alfred b:50,t:40 //Distance: 2 Mission time: 29m 48s
//
[...]
What's the difference? Why don't the static strings get repeated, while the copied lines do?
ANSWER: I wrote the source files in OSX TextEdit, so their newline character was '\r', as pointed out by gnibbler. Following his lead led me to 6 PEP 278: Universal Newline Support. Using the file mode 'rU' squared everything.
Thanks folks!
A:
It appears that the for loop is only executing once.
I'm not sure why it would do that - perhaps there is a problem with the line endings so the whole file is being read in as a single line.
For example, if the lines of the input script file has \r line ending and python is expecting \n line endings.
Try using 'rU' as the mode instead of 'r'
A:
Using the sample you gave as an input file and a made up cities+lvl10 variable, the script works as expected: For each of the "attack" lines in the input, it prints multiple "ifgosub" lines first and then the "attack" line.
The most likely cause of your problem is that iteration over a file doesn't give you the lines separately, but all lines at once. In my experiments that happened if I chose to use CR (\r) as line end characters (that convention was used by MacOS up to 9.x). Maybe some stange character encodings for the input files may cause a similar problem.
To test this assumption, just try to iterate over one of your files, maybe like this:
i = 0
npc10 = open("script-%s-npc10-%i.txt" % (cities[i].user,i),'r')
lines = [line for line in npc10]
npc10.close()
after that you can check len(lines) if it is larger than 1.
BTW, since Python 2.6 (or 2.5 + from __future__ import with_statement) you can use context managers to ensure that files are closed:
with open("script-%s-npc10-%i.txt" % (cities[i].user,i),'r') as npc10:
for line in npc10:
#....
# the file gets closed automatically after the with-statement
A:
my guess is that when you iterate over the lines in the input files (in the inner loops), the whole file is read as a single line, therefore there is only a single iteration.
Not sure, but a possible cause might be mixing Windows/Linux files and python interpreters ("\r\n" vs "\n" End-Of-Line encodings), but someone could correct me here.
General tip when mixing Linux / Windows text files:
convert your files with dos2unix or unix2dos command-line tools.
A:
Maybe you mixed up tabs and spaces in your file and therefore the indentation isn't like it appears to be. Try python's -t flag to check for inconsistent usage of tabs:
python -t script.py
|
trouble writing to file in "for line in" iterator in Python script
|
This seems to be an embarrassingly simple question, but, after a day of reading over How-To's and manuals, it must be asked.
I'm writing many lines to a few files using a few nested loops, inserting some static strings and copying lines over from other files over and over again. The output appears to be a single copy of the static strings and all of the lines I want to copy from other files, instead of multiple copies of the strings combined with the copied lines.
I made a test script that I thought would mimic the behaviour, but it behaves perfectly:
for i in range(10):
f = open('output.txt','w')
f.write( "---------------------------\n" )
FILE1 = open('test1.txt','r')
for line in FILE1:
f.write( "... compliments of loop #1 ...\n" )
f.write( line )
FILE1.close()
f.write( "\n##########################\n" )
FILE2 = open('test2.txt','r')
for line in FILE2:
f.write( "... compliments of loop #1 ...\n" )
f.write( line )
FILE2.close()
f.write( "\n++++++++++++++++++++++++++\n" )
The output is as expected: the static strings interleaved with copied strings. My real, ugly script, however, doesn't do this. I don't want to paste the whole thing in here, but will include as much as I think is relevant (and I'll probably get that wrong, too, 'cause I don't know what's going on). It references an array of objects - I won't include the class, as it seems to behave.
for i in range(10):
print "script-%s-%i-%s%s" % (cities[i].user,i,cities[i].name,cities[i].coords)
f = open("script-%s-%i-%s%s" % (cities[i].user,i,cities[i].name,cities[i].coords),'w')
f.write( "//\n" )
f.write( "//\n// %s - %s %s\n" % (cities[i].user,cities[i].name,cities[i].coords) )
f.write( "//\n" )
f.write( "//\n" )
npc10 = open("script-%s-npc10-%i.txt" % (cities[i].user,i),'r')
for line in npc10:
f.write( "ifgosub ( m_city.AnyIdleHero(%s) == false ) wait_for_big_hero\n" % (cities[i].hero) )
f.write( "ifgosub ( m_city.IsArmyReady(a:%i,s:%i,w:%i,wo:%i) == false ) gosub check_npc10\n" % (lvl10.arch,lvl10.scout,lvl10.warr,lvl10.work) )
f.write( "ifgosub ( m_city.IsArmyReady(a:%i,s:%i,w:%i,wo:%i) == false ) farm_npc5\n" % (lvl10.arch,lvl10.scout,lvl10.warr,lvl10.work) )
f.write( "ifgosub ( m_city.AnyIdleHero(%s) == false ) wait_for_big_hero\n" % (cities[i].hero) )
f.write( line )
npc10.close()
f.write( "\n//\n" )
f.write( "label farm_npc5\n" )
npc5 = open("script-%s-npc5-%i.txt" % (cities[i].user,i),'r')
for line in npc5:
f.write( "sleep 5\n" )
f.write( line )
npc5.close()
f.write( "\n//\n" )
# ... 107 lines of static f.write's
f.close()
Sample of one of the input files ( script-%s-npc10-%i.txt" % (cities[i].user,i) ) - they are all very similar:
attack 456,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,215 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 12m 34s
Sample of one of the output files
( "script-%s-%i-%s%s" % (cities[i].user,i,cities[i].name,cities[i].coords) ):
//
// user1 - cityname1 (456,456)
//
//
ifgosub ( m_city.AnyIdleHero(Alfonso) == false ) wait_for_big_hero
ifgosub ( m_city.IsArmyReady(a:92150,s:2000,w:2000,wo:2000) == false ) gosub check_npc10
ifgosub ( m_city.IsArmyReady(a:92150,s:2000,w:2000,wo:2000) == false ) farm_npc5
ifgosub ( m_city.AnyIdleHero(Alfonso) == false ) wait_for_big_hero
attack 456,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,357 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 8m 52s
attack 159,215 Alfred a:9215,t:185,wo:200,w:2000,s:200 //Distance: 1 Mission time: 12m 34s
//
label farm_npc5
sleep 5
attack 354,159 Alfred b:50,t:40 //Distance: 1 Mission time: 13m 20s
attack 789,654 Alfred b:50,t:40 //Distance: 2 Mission time: 26m 40s
attack 125,456 Alfred b:50,t:40 //Distance: 2 Mission time: 29m 48s
//
[...]
What's the difference? Why don't the static strings get repeated, while the copied lines do?
ANSWER: I wrote the source files in OSX TextEdit, so their newline character was '\r', as pointed out by gnibbler. Following his lead led me to 6 PEP 278: Universal Newline Support. Using the file mode 'rU' squared everything.
Thanks folks!
|
[
"It appears that the for loop is only executing once.\nI'm not sure why it would do that - perhaps there is a problem with the line endings so the whole file is being read in as a single line.\nFor example, if the lines of the input script file has \\r line ending and python is expecting \\n line endings.\nTry using 'rU' as the mode instead of 'r'\n",
"Using the sample you gave as an input file and a made up cities+lvl10 variable, the script works as expected: For each of the \"attack\" lines in the input, it prints multiple \"ifgosub\" lines first and then the \"attack\" line.\nThe most likely cause of your problem is that iteration over a file doesn't give you the lines separately, but all lines at once. In my experiments that happened if I chose to use CR (\\r) as line end characters (that convention was used by MacOS up to 9.x). Maybe some stange character encodings for the input files may cause a similar problem.\nTo test this assumption, just try to iterate over one of your files, maybe like this:\ni = 0\nnpc10 = open(\"script-%s-npc10-%i.txt\" % (cities[i].user,i),'r')\nlines = [line for line in npc10]\nnpc10.close()\n\nafter that you can check len(lines) if it is larger than 1.\nBTW, since Python 2.6 (or 2.5 + from __future__ import with_statement) you can use context managers to ensure that files are closed:\nwith open(\"script-%s-npc10-%i.txt\" % (cities[i].user,i),'r') as npc10:\n for line in npc10:\n #....\n # the file gets closed automatically after the with-statement\n\n",
"my guess is that when you iterate over the lines in the input files (in the inner loops), the whole file is read as a single line, therefore there is only a single iteration.\nNot sure, but a possible cause might be mixing Windows/Linux files and python interpreters (\"\\r\\n\" vs \"\\n\" End-Of-Line encodings), but someone could correct me here.\nGeneral tip when mixing Linux / Windows text files:\nconvert your files with dos2unix or unix2dos command-line tools.\n",
"Maybe you mixed up tabs and spaces in your file and therefore the indentation isn't like it appears to be. Try python's -t flag to check for inconsistent usage of tabs:\npython -t script.py\n\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"file_io",
"python"
] |
stackoverflow_0002316452_file_io_python.txt
|
Q:
Numpy masked array modification
Currently I have a code that checks if given element in array is equal = 0 and if so then set the value to 'level' value (temp_board is 2D numpy array, indices_to_watch contains 2D coordinates that should be watched for zeros).
indices_to_watch = [(0,1), (1,2)]
for index in indices_to_watch:
if temp_board[index] == 0:
temp_board[index] = level
I would like to convert this to a more numpy-like approach (remove the for and use only numpy functions) to speed this up.
Here's what I tried:
masked = np.ma.array(temp_board, mask=(a!=0), hard_mask=True)
masked.put(indices_to_watch, level)
But unfortunately masked array when doing put() wants to have 1D dimensions (totally strange!), is there some other way of updating array elements that are equal to 0 and have concrete indices?
Or maybe using masked arrays is not the way to go?
A:
I'm not sure i follow all of the detail in your question. If i understood it correctly, then it seems like this is straightforward Numpy indexing. The code below checks the array (A) for zeros, and where it finds them, it replaces them with 'level'.
import numpy as NP
A = NP.random.randint(0, 10, 20).reshape(5, 4)
level = 999
ndx = A==0
A[ndx] = level
A:
Assuming that it is not very inefficient to find out where temp_board is 0, you can do what you want like this:
# First figure out where the array is zero
zindex = numpy.where(temp_board == 0)
# Make a set of tuples out of it
zindex = set(zip(*zindex))
# Make a set of tuples from indices_to_watch too
indices_to_watch = set([(0,1), (1,2)])
# Find the intersection. These are the indices that need to be set
indices_to_set = indices_to_watch & zindex
# Set the value
temp_board[zip(*indices_to_set)] = level
If you can't do the above, then here's a way, but I am not sure if it's the most Pythonic:
indices_to_watch = [(0,1), (1,2)]
First, convert to a numpy array:
indices_to_watch = numpy.array(indices_to_watch)
Then, make it indexable:
index = zip(*indices_to_watch)
Then, test the condition:
indices_to_set = numpy.where(temp_board[index] == 0)
Then, figure out the actual indices to set:
final_index = zip(*indices_to_watch[indices_to_set])
Finally, set the values:
temp_board[final_index] = level
A:
You should try something along those lines:
temp_board[temp_board[field_list] == 0] = level
|
Numpy masked array modification
|
Currently I have a code that checks if given element in array is equal = 0 and if so then set the value to 'level' value (temp_board is 2D numpy array, indices_to_watch contains 2D coordinates that should be watched for zeros).
indices_to_watch = [(0,1), (1,2)]
for index in indices_to_watch:
if temp_board[index] == 0:
temp_board[index] = level
I would like to convert this to a more numpy-like approach (remove the for and use only numpy functions) to speed this up.
Here's what I tried:
masked = np.ma.array(temp_board, mask=(a!=0), hard_mask=True)
masked.put(indices_to_watch, level)
But unfortunately masked array when doing put() wants to have 1D dimensions (totally strange!), is there some other way of updating array elements that are equal to 0 and have concrete indices?
Or maybe using masked arrays is not the way to go?
|
[
"I'm not sure i follow all of the detail in your question. If i understood it correctly, then it seems like this is straightforward Numpy indexing. The code below checks the array (A) for zeros, and where it finds them, it replaces them with 'level'.\nimport numpy as NP\nA = NP.random.randint(0, 10, 20).reshape(5, 4) \nlevel = 999\nndx = A==0\nA[ndx] = level\n\n",
"Assuming that it is not very inefficient to find out where temp_board is 0, you can do what you want like this:\n# First figure out where the array is zero\nzindex = numpy.where(temp_board == 0)\n# Make a set of tuples out of it\nzindex = set(zip(*zindex))\n# Make a set of tuples from indices_to_watch too\nindices_to_watch = set([(0,1), (1,2)])\n# Find the intersection. These are the indices that need to be set\nindices_to_set = indices_to_watch & zindex\n# Set the value\ntemp_board[zip(*indices_to_set)] = level\n\nIf you can't do the above, then here's a way, but I am not sure if it's the most Pythonic:\nindices_to_watch = [(0,1), (1,2)]\n\nFirst, convert to a numpy array:\nindices_to_watch = numpy.array(indices_to_watch)\n\nThen, make it indexable:\nindex = zip(*indices_to_watch)\n\nThen, test the condition:\nindices_to_set = numpy.where(temp_board[index] == 0)\n\nThen, figure out the actual indices to set:\nfinal_index = zip(*indices_to_watch[indices_to_set])\n\nFinally, set the values:\ntemp_board[final_index] = level\n\n",
"You should try something along those lines:\ntemp_board[temp_board[field_list] == 0] = level\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"masked_array",
"numpy",
"python"
] |
stackoverflow_0002306280_masked_array_numpy_python.txt
|
Q:
Pipe output of a command to an interactive python session?
What I'd like to do is something like
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
I suppose ipython solution would be best. If this isn't achievable, what would be your solution for the situation where I want to process output from various other commands? I've used subprocess before to do it when I was desperate, but it is not ideal.
UPDATE: So this is getting closer to the end result:
echo $PATH > /tmp/stdout.txt; ipython -i -c 'stdout = open("/tmp/stdout.txt").read()'
Now how can we go about bending this into a form
echo $PATH | pyout
where pyout is the "magic solution to all my problems". It could be a shell script that writes the piped output and then runs the ipython. Everything done fails for the same reasons bp says.
A:
In IPython you can do this
x = !echo $$$$PATH
The double escape of $ is a pain though
You could do this I guess
PATH="$PATH"
x = !echo $PATH
x[0].split(":")
A:
The --remain-interactive switch you are looking for is -i. You also can use the -c switch to specify the command to execute, such as __import__("sys").stdin.read().split(":"). So what you would try is: (do not forget about escaping strings!)
echo $PATH | python -i -c x = __import__(\"sys\").stdin.read().split(\":\")
However, this is all that will be displayed:
>>>
So why doesn't it work? Because you are piping. The python intepreter is trying to interactively read commands from the same sys.stdin you are reading arguments from. Since echo is done executing, sys.stdin is closed and no further input can happen.
For the same reason, something like:
echo $PATH > spam
python -i -c x = __import__(\"sys\").stdin.read().split(\":\") < spam
...will fail.
What I would do is:
echo $PATH > spam.bar
python -i my_app.py spam.bar
After all, open("spam.bar") is a file object just like sys.stdin is :)
A:
Due to the Python axiom of "There should be one - and preferably only one - obvious way to do it" I'm reasonably sure that there won't be a better way to interact with other processes than the subprocess module.
It might help if you could say why something like the following "is not ideal":
>>> process = subprocess.Popen(['cmd', '/c', 'echo %PATH%'], stdout=subprocess.PIPE)
>>> print process.communicate()[0].split(';')
(In your specific example you could use os.environ but I realise that's not really what you're asking.)
|
Pipe output of a command to an interactive python session?
|
What I'd like to do is something like
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
I suppose ipython solution would be best. If this isn't achievable, what would be your solution for the situation where I want to process output from various other commands? I've used subprocess before to do it when I was desperate, but it is not ideal.
UPDATE: So this is getting closer to the end result:
echo $PATH > /tmp/stdout.txt; ipython -i -c 'stdout = open("/tmp/stdout.txt").read()'
Now how can we go about bending this into a form
echo $PATH | pyout
where pyout is the "magic solution to all my problems". It could be a shell script that writes the piped output and then runs the ipython. Everything done fails for the same reasons bp says.
|
[
"In IPython you can do this\nx = !echo $$$$PATH\n\nThe double escape of $ is a pain though\nYou could do this I guess\nPATH=\"$PATH\"\nx = !echo $PATH\nx[0].split(\":\")\n\n",
"The --remain-interactive switch you are looking for is -i. You also can use the -c switch to specify the command to execute, such as __import__(\"sys\").stdin.read().split(\":\"). So what you would try is: (do not forget about escaping strings!)\necho $PATH | python -i -c x = __import__(\\\"sys\\\").stdin.read().split(\\\":\\\")\n\nHowever, this is all that will be displayed:\n>>>\n\nSo why doesn't it work? Because you are piping. The python intepreter is trying to interactively read commands from the same sys.stdin you are reading arguments from. Since echo is done executing, sys.stdin is closed and no further input can happen.\nFor the same reason, something like:\necho $PATH > spam\npython -i -c x = __import__(\\\"sys\\\").stdin.read().split(\\\":\\\") < spam\n\n...will fail.\nWhat I would do is:\necho $PATH > spam.bar\npython -i my_app.py spam.bar\n\nAfter all, open(\"spam.bar\") is a file object just like sys.stdin is :)\n",
"Due to the Python axiom of \"There should be one - and preferably only one - obvious way to do it\" I'm reasonably sure that there won't be a better way to interact with other processes than the subprocess module.\nIt might help if you could say why something like the following \"is not ideal\":\n>>> process = subprocess.Popen(['cmd', '/c', 'echo %PATH%'], stdout=subprocess.PIPE)\n>>> print process.communicate()[0].split(';')\n\n(In your specific example you could use os.environ but I realise that's not really what you're asking.)\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"interactive",
"ipython",
"pipe",
"python",
"redirect"
] |
stackoverflow_0002316730_interactive_ipython_pipe_python_redirect.txt
|
Q:
Is there a way to extract a dict in Python into the local namespace?
PHP has a function called extract() which takes an associative array as the argument and creates local variables out of the keys whose values are assigned to the key's values. Is there a way to do this in Python? A quick google search didn't immediately show me how. I suspect there's a way with exec() but it'd be nice if there were some function to do it for me.
A:
Since it is not safe to modify the dict that locals() returns
>>> d={'a':6, 'b':"hello", 'c':set()}
>>> exec '\n'.join("%s=%r"%i for i in d.items())
>>> a
6
>>> b
'hello'
>>> c
set([])
But using exec like this is ugly. You should redesign so you don't need to dynamically add to your local namespace
Edit: See Mike's reservations about using repr in the comments.
>>> d={'a':6, 'b':"hello", 'c':set()}
>>> exec '\n'.join("%s=d['%s']"%(k,k) for k in d)
>>> id(d['c'])
3079176684L
>>> id(c)
3079176684L
A:
Try:
locals().update(my_dict)
EDIT:
gnibbler has made a very valid point that locals shouldn't be modified (check: http://docs.python.org/library/functions.html#locals). Still, Python docs doesn't say it's not safe, it only says that changes to locals may not affect values of variables. Before answering the question I tried in my Python's 2.6 IDLE that updating locals actually works, both in global scope and inside a function. That's why I'm not deleting my answer, but instead I'm adding a warning that it might work under certain (platform-specific?) circumstances, but it's not guaranteed.
|
Is there a way to extract a dict in Python into the local namespace?
|
PHP has a function called extract() which takes an associative array as the argument and creates local variables out of the keys whose values are assigned to the key's values. Is there a way to do this in Python? A quick google search didn't immediately show me how. I suspect there's a way with exec() but it'd be nice if there were some function to do it for me.
|
[
"Since it is not safe to modify the dict that locals() returns \n>>> d={'a':6, 'b':\"hello\", 'c':set()}\n>>> exec '\\n'.join(\"%s=%r\"%i for i in d.items())\n>>> a\n6\n>>> b\n'hello'\n>>> c\nset([])\n\nBut using exec like this is ugly. You should redesign so you don't need to dynamically add to your local namespace\nEdit: See Mike's reservations about using repr in the comments.\n>>> d={'a':6, 'b':\"hello\", 'c':set()}\n>>> exec '\\n'.join(\"%s=d['%s']\"%(k,k) for k in d)\n>>> id(d['c'])\n3079176684L\n>>> id(c)\n3079176684L\n\n",
"Try:\n locals().update(my_dict)\n\nEDIT:\ngnibbler has made a very valid point that locals shouldn't be modified (check: http://docs.python.org/library/functions.html#locals). Still, Python docs doesn't say it's not safe, it only says that changes to locals may not affect values of variables. Before answering the question I tried in my Python's 2.6 IDLE that updating locals actually works, both in global scope and inside a function. That's why I'm not deleting my answer, but instead I'm adding a warning that it might work under certain (platform-specific?) circumstances, but it's not guaranteed.\n"
] |
[
5,
4
] |
[
"Modifying locals() dict could have been a solution but docs say, http://docs.python.org/library/functions.html#\n\nNote The contents of this dictionary\n should not be modified; changes may\n not affect the values of local and\n free variables used by the\n interpreter.\n\nso the question is why you even need it? there may be better ways to achieve that whatever you are trying to achieve.\nAlso why can't you directly access dict or assign them to variables?\n"
] |
[
-1
] |
[
"dictionary",
"php",
"python"
] |
stackoverflow_0002316764_dictionary_php_python.txt
|
Q:
Pygame and threading: locked when accessing to globals?
I am programming a game using pygame. I intend to control one of the characters using OpenSoundControl (OSC), a udp-based protocol for realtime communication. Basically I am using simpleOSC module to biund some OSC commands to functions on my pygame program.
My game structure is something like this (this is a simplification so you get the idea):
globalsomething = {}
def handler(*m):
global globalsomething
print "it works"
print globalsomething
print "not working"
if __name__ == "__main__":
osc.init()
osc.listen('', 3333)
osc.bind(handler,'/game/dosmtng')
app = Game()
while True:
app.MainLoop()
Game is a simple class that executes pygame.init() and draws and does pretty much everything related to pygame.
The problem I get when executing the code is that when I send an osc packet I get "It works" but not "not working" and then no subsequent osc packets are processed.
Since simpleOSC uses threads, my only explanation to this behavior is that pygame uses some kind of incompatible threading (?) and when trying to access to a variable located in pygame's thread it locks.
Any ideas about the cause and (if possible) a solution?
A:
I can't verify whether you are in fact having a thread/concurrency issue, although it seems likely. I can suggest a solution that may resolve it.
The python multiprocessing module demonstrates how to spawn a new process (not a thread) with a queue. If you create the new process and then init OSC in there, and have the handler simply put a message on the queue whenever something arrives, you can then poll the queue from the main pygame process to obtain any messages that have come in.
It's a bit less clean than you might like, but at least it'll get the two modules at arms length so they can't interfere with each other.
|
Pygame and threading: locked when accessing to globals?
|
I am programming a game using pygame. I intend to control one of the characters using OpenSoundControl (OSC), a udp-based protocol for realtime communication. Basically I am using simpleOSC module to biund some OSC commands to functions on my pygame program.
My game structure is something like this (this is a simplification so you get the idea):
globalsomething = {}
def handler(*m):
global globalsomething
print "it works"
print globalsomething
print "not working"
if __name__ == "__main__":
osc.init()
osc.listen('', 3333)
osc.bind(handler,'/game/dosmtng')
app = Game()
while True:
app.MainLoop()
Game is a simple class that executes pygame.init() and draws and does pretty much everything related to pygame.
The problem I get when executing the code is that when I send an osc packet I get "It works" but not "not working" and then no subsequent osc packets are processed.
Since simpleOSC uses threads, my only explanation to this behavior is that pygame uses some kind of incompatible threading (?) and when trying to access to a variable located in pygame's thread it locks.
Any ideas about the cause and (if possible) a solution?
|
[
"I can't verify whether you are in fact having a thread/concurrency issue, although it seems likely. I can suggest a solution that may resolve it.\nThe python multiprocessing module demonstrates how to spawn a new process (not a thread) with a queue. If you create the new process and then init OSC in there, and have the handler simply put a message on the queue whenever something arrives, you can then poll the queue from the main pygame process to obtain any messages that have come in.\nIt's a bit less clean than you might like, but at least it'll get the two modules at arms length so they can't interfere with each other.\n"
] |
[
3
] |
[] |
[] |
[
"multithreading",
"osc",
"pygame",
"python"
] |
stackoverflow_0002310728_multithreading_osc_pygame_python.txt
|
Q:
Python Virtualbox API
http://enomalism.com/api/pyvb/
here we have def _init_(self,**kw):
what parameter(s) should be passed when we create an instance for pyvb.vm.vbVM ???
A:
What you are seeing is "keyword arguments". You can call the constructor with a dictionary or named arguments. Here is an example of using keyword arguments:
class MyClass(object):
def __init__(self,**kwargs):
if 'val' in kwargs:
self.__value = kwargs['val'];
elif 'value' in kwargs:
self.__value = kwargs['value'];
else:
raise ValueError("Requires parameter 'val' or 'value'.");
def getValue(self):
return self.__value;
# ...
def main(argv=None):
# ...
instance1 = MyClass(val=5);
x = instance1.getValue(); # value is 5
instance2 = MyClass(value=6);
y = instance2.getValue(); # value is 6
valuedict = {'val':10};
instance3 = MyClass(**valuedict);
z = instance3.getValue(); # value is 10
Keyword arguments are nice because they can make your functions and constructors very flexible, and -- as can be seen from the last instantiation case -- it becomes possible to construct the object from a configuration dictionary. The main downside to keyword arguments is that, because it is so flexible, it may not be obvious what the options are. You can try executing "pydoc pyvb.vm" or, as has been pointed out, you can take a look at the source code, which shows the supported attributes.
A:
Looks like you want to pass in an array of configuration items. See the source code.
|
Python Virtualbox API
|
http://enomalism.com/api/pyvb/
here we have def _init_(self,**kw):
what parameter(s) should be passed when we create an instance for pyvb.vm.vbVM ???
|
[
"What you are seeing is \"keyword arguments\". You can call the constructor with a dictionary or named arguments. Here is an example of using keyword arguments:\n\nclass MyClass(object):\n def __init__(self,**kwargs):\n if 'val' in kwargs:\n self.__value = kwargs['val'];\n elif 'value' in kwargs:\n self.__value = kwargs['value'];\n else:\n raise ValueError(\"Requires parameter 'val' or 'value'.\");\n def getValue(self):\n return self.__value;\n\n# ...\n\ndef main(argv=None):\n # ...\n instance1 = MyClass(val=5);\n x = instance1.getValue(); # value is 5\n\n instance2 = MyClass(value=6);\n y = instance2.getValue(); # value is 6\n\n valuedict = {'val':10};\n instance3 = MyClass(**valuedict);\n z = instance3.getValue(); # value is 10\n\n\nKeyword arguments are nice because they can make your functions and constructors very flexible, and -- as can be seen from the last instantiation case -- it becomes possible to construct the object from a configuration dictionary. The main downside to keyword arguments is that, because it is so flexible, it may not be obvious what the options are. You can try executing \"pydoc pyvb.vm\" or, as has been pointed out, you can take a look at the source code, which shows the supported attributes.\n",
"Looks like you want to pass in an array of configuration items. See the source code.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"virtualbox"
] |
stackoverflow_0002312254_python_virtualbox.txt
|
Q:
Setting up authentication in Trac
I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.
We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a users database stored in a mysql database. I have been asked to look into the possibilities for Trac to use our existing user database in order to keep user maintenance to a minimum. Do you have any suggestions or tips for doing that?
Here is what I have come up with so far:
Install Trac on our server (currently done with mysql/apache2/mod_python), but don't grant access to anyone on the net.
Write a php wrapper script that
Handles the authentication mechanism.
Passes the request to Trac with the username included.
Trac handles the request as the specified user
The problem is; I don't know how to do step 2.
Any comments?
Best regards
Jørn
A:
First off, don't use mod_python, use mod_wsgi.
Second, you have several options for how to do authentication. One option might be to just use mod_authn_dbd with a MySQL backend, keeping your authn in the apache2 config.
Third, look into Trac's AccountManager. It's one of the most useful Trac plugins (we use it at work), and will help you get this right. http://trac-hacks.org/wiki/AccountManagerPlugin
A:
What you are looking for is called Single Sign On.
Are you running Trac on Apache? In that case, it seems to be possible to make use of what user authentication interfaces (LDAP...) Apache can interface with. Check out this conversation.
There are also some SSO plugins available at Trac Hacks, among them an LDAP one.
A:
Just a quick follow up: I ended up using Carsten Fuchs ScriptAuthPlugin (modifying it to md5-hash the password). Similar to TracCoSign, all you have to provide, is an address to which ScriptAuthPlugin can validate user credentials. Works nicely :-)
http://trac-hacks.org/wiki/ScriptAuthPlugin
~Jørn
|
Setting up authentication in Trac
|
I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.
We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a users database stored in a mysql database. I have been asked to look into the possibilities for Trac to use our existing user database in order to keep user maintenance to a minimum. Do you have any suggestions or tips for doing that?
Here is what I have come up with so far:
Install Trac on our server (currently done with mysql/apache2/mod_python), but don't grant access to anyone on the net.
Write a php wrapper script that
Handles the authentication mechanism.
Passes the request to Trac with the username included.
Trac handles the request as the specified user
The problem is; I don't know how to do step 2.
Any comments?
Best regards
Jørn
|
[
"First off, don't use mod_python, use mod_wsgi.\nSecond, you have several options for how to do authentication. One option might be to just use mod_authn_dbd with a MySQL backend, keeping your authn in the apache2 config.\nThird, look into Trac's AccountManager. It's one of the most useful Trac plugins (we use it at work), and will help you get this right. http://trac-hacks.org/wiki/AccountManagerPlugin\n",
"What you are looking for is called Single Sign On.\nAre you running Trac on Apache? In that case, it seems to be possible to make use of what user authentication interfaces (LDAP...) Apache can interface with. Check out this conversation. \nThere are also some SSO plugins available at Trac Hacks, among them an LDAP one.\n",
"Just a quick follow up: I ended up using Carsten Fuchs ScriptAuthPlugin (modifying it to md5-hash the password). Similar to TracCoSign, all you have to provide, is an address to which ScriptAuthPlugin can validate user credentials. Works nicely :-)\nhttp://trac-hacks.org/wiki/ScriptAuthPlugin\n~Jørn\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"apache",
"php",
"python",
"trac"
] |
stackoverflow_0002282123_apache_php_python_trac.txt
|
Q:
setting windows live messenger nick and status message using win32com.client
is their any way to set windows live messenger using the win32com library ?
A:
This thread at MSDN forum discusses the topic thoroughly.
In short, you can do it with this API
Another possibility is to use a python based web client to do it over http at home.live.com
|
setting windows live messenger nick and status message using win32com.client
|
is their any way to set windows live messenger using the win32com library ?
|
[
"This thread at MSDN forum discusses the topic thoroughly.\nIn short, you can do it with this API\nAnother possibility is to use a python based web client to do it over http at home.live.com\n"
] |
[
0
] |
[] |
[] |
[
"live",
"python",
"windows",
"windows_live_messenger"
] |
stackoverflow_0002317175_live_python_windows_windows_live_messenger.txt
|
Q:
Python: Asynchronous http requests sent in order with automatic handling of cookies?
I am coding a python (2.6) interface to a web service. I need to communicate via http so that :
Cookies are handled automatically,
The requests are asynchronous,
The order in which the requests are sent is respected (the order in which the responses to these requests are received does not matter).
I have tried what could be easily derived from the build-in libraries, facing different problems :
Using httplib and urllib2, the requests are synchronous unless I use thread, in which case the order is not guaranteed to be respected,
Using asyncore, there was no library to automatically deal with cookies send by the web service.
After some googling, it seems that there are many examples of python scripts or libraries that match 2 out of the 3 criteria, but not the 3 of them. I am thinking of reading through the cookielib sources and adapting what I need of it to asyncore (or only to my application in a ad hoc manner), but it seems strange that nothing like this exists yet, as I guess I am not the only one interested. If anyone knows of pointers about this problem, it would be greatly appreciated.
Thank you.
Edit to clarify :
What I am doing is a local proxy that interfaces my IRC client with a webchat. It creates a socket that listens to IRC connections, then upon receiving one, it logs in the webchat via http. I don't have access to the behaviour of the webchat, and it uses cookies for session IDs. When client sends several IRC requests to my python proxy, I have to forward them to the webchat's server via http and with cookies. I also want to do this asynchronously (I don't want to wait for the http response before I send the next request), and currently what happens is that the order in which the http requests are sent is not the order in which the IRC commands were received.
I hope this clarifies the question, and I will of course detail more if it doesn't.
A:
Using httplib and urllib2, the
requests are synchronous unless I use
thread, in which case the order is not
guaranteed to be respected
How would you know that the order has been respected unless you get your response back from the first connection before you send the response to the second connection? After all, you don't care what order the responses come in, so it's very possible that the responses come back in the order you expect but that your requests were processed in the wrong order!
The only way you can guarantee the ordering is by waiting for confirmation that the first request has successfully arrived (eg. you start receiving the response for it) before beginning the second request. You can do this by not launching the second thread until you reach the response handling part of the first thread.
|
Python: Asynchronous http requests sent in order with automatic handling of cookies?
|
I am coding a python (2.6) interface to a web service. I need to communicate via http so that :
Cookies are handled automatically,
The requests are asynchronous,
The order in which the requests are sent is respected (the order in which the responses to these requests are received does not matter).
I have tried what could be easily derived from the build-in libraries, facing different problems :
Using httplib and urllib2, the requests are synchronous unless I use thread, in which case the order is not guaranteed to be respected,
Using asyncore, there was no library to automatically deal with cookies send by the web service.
After some googling, it seems that there are many examples of python scripts or libraries that match 2 out of the 3 criteria, but not the 3 of them. I am thinking of reading through the cookielib sources and adapting what I need of it to asyncore (or only to my application in a ad hoc manner), but it seems strange that nothing like this exists yet, as I guess I am not the only one interested. If anyone knows of pointers about this problem, it would be greatly appreciated.
Thank you.
Edit to clarify :
What I am doing is a local proxy that interfaces my IRC client with a webchat. It creates a socket that listens to IRC connections, then upon receiving one, it logs in the webchat via http. I don't have access to the behaviour of the webchat, and it uses cookies for session IDs. When client sends several IRC requests to my python proxy, I have to forward them to the webchat's server via http and with cookies. I also want to do this asynchronously (I don't want to wait for the http response before I send the next request), and currently what happens is that the order in which the http requests are sent is not the order in which the IRC commands were received.
I hope this clarifies the question, and I will of course detail more if it doesn't.
|
[
"\nUsing httplib and urllib2, the\n requests are synchronous unless I use\n thread, in which case the order is not\n guaranteed to be respected\n\nHow would you know that the order has been respected unless you get your response back from the first connection before you send the response to the second connection? After all, you don't care what order the responses come in, so it's very possible that the responses come back in the order you expect but that your requests were processed in the wrong order!\nThe only way you can guarantee the ordering is by waiting for confirmation that the first request has successfully arrived (eg. you start receiving the response for it) before beginning the second request. You can do this by not launching the second thread until you reach the response handling part of the first thread.\n"
] |
[
2
] |
[] |
[] |
[
"asynchronous",
"cookies",
"http",
"python"
] |
stackoverflow_0002315151_asynchronous_cookies_http_python.txt
|
Q:
Problem with Twisted and threads
Some of you that are more experienced using Twisted will probably judge me about using it together with threads - but I did it :). And now I am in somehow of a trouble - I am having an application server that listens for client requests and each time a new client connects it spawns another thread that I probably forget to properly close, since after a while of heavy usage the server stops processing requests. Well, I have 3 different types of threads and for one of those it happens - the thing is that I am not sure what's the proper way to do it, since Thread.join() seems to not work and doing cat /proc/<pid>/status it always gives me Threads: 43 when the server stopped working.
So I am looking for a way of debugging this and see how can I properly close the threads.
And yeah, I know about this question:
Is there any way to kill a Thread in Python?
and probably many others.
A:
"Twisted way" to do anything outside reactor loop (aka spawning threads) is twisted.internet.threads.deferToThread.
For example:
from twisted.internet import threads
def sthToDoInSeparateThread():
return 3
d = threads.deferToThread(sthToDoInSeparateThread)
deferToThread will execute sthToDoInSeparateThread in separate thread and fire returned defered d as soon as thread is stopped.
A:
You probably just want to do mythread.setDaemon(True) so that your threads exit when the main process exits.
|
Problem with Twisted and threads
|
Some of you that are more experienced using Twisted will probably judge me about using it together with threads - but I did it :). And now I am in somehow of a trouble - I am having an application server that listens for client requests and each time a new client connects it spawns another thread that I probably forget to properly close, since after a while of heavy usage the server stops processing requests. Well, I have 3 different types of threads and for one of those it happens - the thing is that I am not sure what's the proper way to do it, since Thread.join() seems to not work and doing cat /proc/<pid>/status it always gives me Threads: 43 when the server stopped working.
So I am looking for a way of debugging this and see how can I properly close the threads.
And yeah, I know about this question:
Is there any way to kill a Thread in Python?
and probably many others.
|
[
"\"Twisted way\" to do anything outside reactor loop (aka spawning threads) is twisted.internet.threads.deferToThread.\nFor example:\nfrom twisted.internet import threads\n\ndef sthToDoInSeparateThread():\n return 3\n\nd = threads.deferToThread(sthToDoInSeparateThread)\n\ndeferToThread will execute sthToDoInSeparateThread in separate thread and fire returned defered d as soon as thread is stopped.\n",
"You probably just want to do mythread.setDaemon(True) so that your threads exit when the main process exits.\n"
] |
[
4,
0
] |
[] |
[] |
[
"multithreading",
"python",
"twisted"
] |
stackoverflow_0001593948_multithreading_python_twisted.txt
|
Q:
XML file using Python
I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code?
Also I need to have my output (i.e. element of each attribute come in separate lines in that particular XML file).
A:
Python comes with 2 modules for xml processing mindom which is a DOM implemetation and the more 'pythonic' Element Tree which has other information and links to examples etc I use a third party library lxml which is in effect a super set of Element Tree
A:
There is also the excellent lxml library. You can query the tree with xpath or if you are familiar with css you can select elements with cssselect.
In [1]: from lxml import etree
In [2]: from StringIO import StringIO
In [3]: f = StringIO('<foo><bar id="1">hello</bar><bar id="2">world</bar></foo>')
In [4]: tree = etree.parse(f)
In [5]: r = tree.xpath('/foo/bar')
In [6]: print len(r)
2
In [7]: for elem in r:
....: print elem.get('id'), elem.text
1 hello
2 world
|
XML file using Python
|
I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code?
Also I need to have my output (i.e. element of each attribute come in separate lines in that particular XML file).
|
[
"Python comes with 2 modules for xml processing mindom which is a DOM implemetation and the more 'pythonic' Element Tree which has other information and links to examples etc I use a third party library lxml which is in effect a super set of Element Tree\n",
"There is also the excellent lxml library. You can query the tree with xpath or if you are familiar with css you can select elements with cssselect.\nIn [1]: from lxml import etree\nIn [2]: from StringIO import StringIO\nIn [3]: f = StringIO('<foo><bar id=\"1\">hello</bar><bar id=\"2\">world</bar></foo>')\nIn [4]: tree = etree.parse(f)\nIn [5]: r = tree.xpath('/foo/bar')\nIn [6]: print len(r)\n2\nIn [7]: for elem in r:\n ....: print elem.get('id'), elem.text \n1 hello\n2 world\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002317626_python_xml.txt
|
Q:
JSON serializers not working in Django
Hay, serializers is not returning JSON object
make = Make.objects.filter(slug__exact=make)
models = Model.objects.filter(make=make).values('slug','name')
json_models = serializers.get_serializer("json")()
json_models.serialize(models)
return HttpResponse(json_models.getvalue())
I'm getting an error
'dict' object has no attribute '_meta'
Any ideas?
A:
As the other answer hints, its because .values(...) returns a list and serializers is meant for Querysets. However you can still do this without needing raw SimpleJSON quite simply:
queryset = Model.objects.filter(make__slug__exact=make)
return serializers.serialize("json", queryset, fields=('slug', 'name'))
We're basically telling the serializer to do the field-limiting instead of letting the Queryset doing it. I've used some shortcuts in there to cut the query down to one line too but that's up to you.
A:
The serializer is meant to be used on QuerySet instances. Use django.utils.simplejson.dumps() if you have a normal Python structure.
|
JSON serializers not working in Django
|
Hay, serializers is not returning JSON object
make = Make.objects.filter(slug__exact=make)
models = Model.objects.filter(make=make).values('slug','name')
json_models = serializers.get_serializer("json")()
json_models.serialize(models)
return HttpResponse(json_models.getvalue())
I'm getting an error
'dict' object has no attribute '_meta'
Any ideas?
|
[
"As the other answer hints, its because .values(...) returns a list and serializers is meant for Querysets. However you can still do this without needing raw SimpleJSON quite simply:\nqueryset = Model.objects.filter(make__slug__exact=make)\nreturn serializers.serialize(\"json\", queryset, fields=('slug', 'name'))\n\nWe're basically telling the serializer to do the field-limiting instead of letting the Queryset doing it. I've used some shortcuts in there to cut the query down to one line too but that's up to you.\n",
"The serializer is meant to be used on QuerySet instances. Use django.utils.simplejson.dumps() if you have a normal Python structure.\n"
] |
[
4,
2
] |
[] |
[] |
[
"django",
"json",
"python"
] |
stackoverflow_0002317818_django_json_python.txt
|
Q:
python: dictionary dilemma: how to properly index objects based on an attribute
first, an example:
given a bunch of Person objects with
various attributes (name, ssn, phone,
email address, credit card #, etc.)
now imagine the following simple
website:
uses a person's email address as unique login name
lets users edit their attributes (including their email address)
if this website had tons of users,
then it make sense to store Person
objects in a dictionary indexed by
email address, for quick Person
retrieval upon login.
however when a Person's email address
is edited, then the dictionary key for
that Person needs to be changed as
well. this is slightly yucky
im looking for suggestions on how to tackle the generic problem:
given a bunch of entities with a shared aspect. the aspect is used both for fast access to the entities and within each entity's functionality. where should the aspect be placed:
within each entity (not good for fast access)
index only (not good for each entity's functionality)
both within each entity and as index (duplicate data/reference)
somewhere else/somehow differently
the problem may be extended, say, if we want to use several indices to index the data (ssn, credit card number, etc.). eventually we may end up with a bunch of SQL tables.
im looking for something with the following properties (and more if you can think of them):
# create an index on the attribute of a class
magical_index = magical_index_factory(class, class.attribute)
# create an object
obj = class()
# set the object's attribute
obj.attribute= value
# retrieve object from using attribute as index
magical_index[value]
# change object attribute to new value
obj.attribute= new_value
# automagically object can be retrieved using new value of attribute
magical_index[new_value]
# become less materialistic: get rid of the objects in your life
del obj
# object is really gone
magical_index[new_value]
KeyError: new_value
i want the object, indices, all to play nicely and seamlessly with each other.
please suggest appropriate design patterns
note:
the above example is just that, an example. an example used to portray the generic problem.
so please provide generic solutions (of course, you may choose to keep using the example when explaining your generic solution)
A:
Consider this.
class Person( object ):
def __init__( self, name, addr, email, etc. ):
self.observer= []
... etc. ...
@property
def name( self ): return self._name
@name.setter
def name( self, value ):
self._name= value
for observer in self.observedBy: observer.update( self )
... etc. ...
This observer attribute implements an Observable that notifies its Observers of updates. This is the list of observers that must be notified of changes.
Each attribute is wrapped with properties. Using Descriptors us probably better because it can save repeating the observer notification.
class PersonCollection( set ):
def __init__( self, *args, **kw ):
self.byName= collections.defaultdict(list)
self.byEmail= collections.defaultdict(list)
super( PersonCollection, self ).__init__( *args, **kw )
def add( self, person ):
super( PersonCollection, self ).append( person )
person.observer.append( self )
self.byName[person.name].append( person )
self.byEmail[person.email].append( person )
def update( self, person ):
"""This person changed. Find them in old indexes and fix them."""
changed = [(k,v) for k,v in self.byName.items() if id(person) == id(v) ]
for k, v in changed:
self.byName.pop( k )
self.byName[person.name].append( person )
changed = [(k,v) for k,v in self.byEmail.items() if id(person) == id(v) ]
for k, v in changed:
self.byEmail.pop( k )
self.byEmail[person.email].append( person)
... etc. ... for all methods of a collections.Set.
Use collections.ABC for more information on what must be implemented.
http://docs.python.org/library/collections.html#abcs-abstract-base-classes
If you want "generic" indexing, then your collection can be parameterized with the names of attributes, and you can use getattr to get those named attributes from the underlying objects.
class GenericIndexedCollection( set ):
attributes_to_index = [ ] # List of attribute names
def __init__( self, *args, **kw ):
self.indexes = dict( (n, {}) for n in self.attributes_to_index ]
super( PersonCollection, self ).__init__( *args, **kw )
def add( self, person ):
super( PersonCollection, self ).append( person )
for i in self.indexes:
self.indexes[i].append( getattr( person, i )
Note. To properly emulate a database, use a set not a list. Database tables are (theoretically) sets. As a practical matter they are unordered, and an index will allow the database to reject duplicates. Some RDBMS's don't reject duplicate rows because -- without an index -- it's too expensive to check.
A:
Well, another way may be to implement the following:
Attr is an abstraction for a "value". We need this since there is no "assignment overloading" in Python (simple get / set paradigm is used as the cleanest alternative). Attr also acts as an "Observable".
AttrSet is an "Observer" for Attrs, which tracks their value changes while effectively acting as an Attr-to-whatever (person in our case) dictionary.
create_with_attrs is a factory producing what looks like a named-tuple, forwarding attribute access via supplied Attrs, so that person.name = "Ivan" effectively yields person.name_attr.set("Ivan") and makes the AttrSets observing this person's name appropriately rearrange their internals.
The code (tested):
from collections import defaultdict
class Attribute(object):
def __init__(self, value):
super(Attribute, self).__init__()
self._value = value
self._notified_set = set()
def set(self, value):
old = self._value
self._value = value
for n_ch in self._notified_set:
n_ch(old_value=old, new_value=value)
def get(self):
return self._value
def add_notify_changed(self, notify_changed):
self._notified_set.add(notify_changed)
def remove_notify_changed(self, notify_changed):
self._notified_set.remove(notify_changed)
class AttrSet(object):
def __init__(self):
super(AttrSet, self).__init__()
self._attr_value_to_obj_set = defaultdict(set)
self._obj_to_attr = {}
self._attr_to_notify_changed = {}
def add(self, attr, obj):
self._obj_to_attr[obj] = attr
self._add(attr.get(), obj)
notify_changed = (lambda old_value, new_value:
self._notify_changed(obj, old_value, new_value))
attr.add_notify_changed(notify_changed)
self._attr_to_notify_changed[attr] = notify_changed
def get(self, *attr_value_lst):
attr_value_lst = attr_value_lst or self._attr_value_to_obj_set.keys()
result = set()
for attr_value in attr_value_lst:
result.update(self._attr_value_to_obj_set[attr_value])
return result
def remove(self, obj):
attr = self._obj_to_attr.pop(obj)
self._remove(attr.get(), obj)
notify_changed = self._attr_to_notify_changed.pop(attr)
attr.remove_notify_changed(notify_changed)
def __iter__(self):
return iter(self.get())
def _add(self, attr_value, obj):
self._attr_value_to_obj_set[attr_value].add(obj)
def _remove(self, attr_value, obj):
obj_set = self._attr_value_to_obj_set[attr_value]
obj_set.remove(obj)
if not obj_set:
self._attr_value_to_obj_set.pop(attr_value)
def _notify_changed(self, obj, old_value, new_value):
self._remove(old_value, obj)
self._add(new_value, obj)
def create_with_attrs(**attr_name_to_attr):
class Result(object):
def __getattr__(self, attr_name):
if attr_name in attr_name_to_attr.keys():
return attr_name_to_attr[attr_name].get()
else:
raise AttributeError(attr_name)
def __setattr__(self, attr_name, attr_value):
if attr_name in attr_name_to_attr.keys():
attr_name_to_attr[attr_name].set(attr_value)
else:
raise AttributeError(attr_name)
def __str__(self):
result = ""
for attr_name in attr_name_to_attr:
result += (attr_name + ": "
+ str(attr_name_to_attr[attr_name].get())
+ ", ")
return result
return Result()
With the data prepared with
name_and_email_lst = [("John","email1@dot.com"),
("John","email2@dot.com"),
("Jack","email3@dot.com"),
("Hack","email4@dot.com"),
]
email = AttrSet()
name = AttrSet()
for name_str, email_str in name_and_email_lst:
email_attr = Attribute(email_str)
name_attr = Attribute(name_str)
person = create_with_attrs(email=email_attr, name=name_attr)
email.add(email_attr, person)
name.add(name_attr, person)
def print_set(person_set):
for person in person_set: print person
print
the following pseudo-SQL snippet sequence gives:
SELECT id FROM email
>>> print_set(email.get())
email: email3@dot.com, name: Jack,
email: email4@dot.com, name: Hack,
email: email2@dot.com, name: John,
email: email1@dot.com, name: John,
SELECT id FROM email WHERE email="email1@dot.com"
>>> print_set(email.get("email1@dot.com"))
email: email1@dot.com, name: John,
SELECT id FROM email WHERE email="email1@dot.com" OR email="email2@dot.com"
>>> print_set(email.get("email1@dot.com", "email2@dot.com"))
email: email1@dot.com, name: John,
email: email2@dot.com, name: John,
SELECT id FROM name WHERE name="John"
>>> print_set(name.get("John"))
email: email1@dot.com, name: John,
email: email2@dot.com, name: John,
SELECT id FROM name, email WHERE name="John" AND email="email1@dot.com"
>>> print_set(name.get("John").intersection(email.get("email1@dot.com")))
email: email1@dot.com, name: John,
UPDATE email, name SET email="jon@dot.com", name="Jon"
WHERE id IN
SELECT id FROM email WHERE email="email1@dot.com"
>>> person = email.get("email1@dot.com").pop()
>>> person.name = "Jon"; person.email = "jon@dot.com"
>>> print_set(email.get())
email: email3@dot.com, name: Jack,
email: email4@dot.com, name: Hack,
email: email2@dot.com, name: John,
email: jon@dot.com, name: Jon,
DELETE FROM email, name WHERE id=%s
SELECT id FROM email
>>> name.remove(person)
>>> email.remove(person)
>>> print_set(email.get())
email: email3@dot.com, name: Jack,
email: email4@dot.com, name: Hack,
email: email2@dot.com, name: John,
|
python: dictionary dilemma: how to properly index objects based on an attribute
|
first, an example:
given a bunch of Person objects with
various attributes (name, ssn, phone,
email address, credit card #, etc.)
now imagine the following simple
website:
uses a person's email address as unique login name
lets users edit their attributes (including their email address)
if this website had tons of users,
then it make sense to store Person
objects in a dictionary indexed by
email address, for quick Person
retrieval upon login.
however when a Person's email address
is edited, then the dictionary key for
that Person needs to be changed as
well. this is slightly yucky
im looking for suggestions on how to tackle the generic problem:
given a bunch of entities with a shared aspect. the aspect is used both for fast access to the entities and within each entity's functionality. where should the aspect be placed:
within each entity (not good for fast access)
index only (not good for each entity's functionality)
both within each entity and as index (duplicate data/reference)
somewhere else/somehow differently
the problem may be extended, say, if we want to use several indices to index the data (ssn, credit card number, etc.). eventually we may end up with a bunch of SQL tables.
im looking for something with the following properties (and more if you can think of them):
# create an index on the attribute of a class
magical_index = magical_index_factory(class, class.attribute)
# create an object
obj = class()
# set the object's attribute
obj.attribute= value
# retrieve object from using attribute as index
magical_index[value]
# change object attribute to new value
obj.attribute= new_value
# automagically object can be retrieved using new value of attribute
magical_index[new_value]
# become less materialistic: get rid of the objects in your life
del obj
# object is really gone
magical_index[new_value]
KeyError: new_value
i want the object, indices, all to play nicely and seamlessly with each other.
please suggest appropriate design patterns
note:
the above example is just that, an example. an example used to portray the generic problem.
so please provide generic solutions (of course, you may choose to keep using the example when explaining your generic solution)
|
[
"Consider this.\nclass Person( object ):\n def __init__( self, name, addr, email, etc. ):\n self.observer= []\n ... etc. ...\n @property\n def name( self ): return self._name\n @name.setter\n def name( self, value ): \n self._name= value\n for observer in self.observedBy: observer.update( self )\n ... etc. ...\n\nThis observer attribute implements an Observable that notifies its Observers of updates. This is the list of observers that must be notified of changes.\nEach attribute is wrapped with properties. Using Descriptors us probably better because it can save repeating the observer notification. \nclass PersonCollection( set ):\n def __init__( self, *args, **kw ):\n self.byName= collections.defaultdict(list)\n self.byEmail= collections.defaultdict(list)\n super( PersonCollection, self ).__init__( *args, **kw )\n def add( self, person ):\n super( PersonCollection, self ).append( person )\n person.observer.append( self )\n self.byName[person.name].append( person )\n self.byEmail[person.email].append( person )\n def update( self, person ):\n \"\"\"This person changed. Find them in old indexes and fix them.\"\"\"\n changed = [(k,v) for k,v in self.byName.items() if id(person) == id(v) ]\n for k, v in changed:\n self.byName.pop( k )\n self.byName[person.name].append( person )\n changed = [(k,v) for k,v in self.byEmail.items() if id(person) == id(v) ]\n for k, v in changed:\n self.byEmail.pop( k )\n self.byEmail[person.email].append( person)\n\n ... etc. ... for all methods of a collections.Set.\n\nUse collections.ABC for more information on what must be implemented.\nhttp://docs.python.org/library/collections.html#abcs-abstract-base-classes\nIf you want \"generic\" indexing, then your collection can be parameterized with the names of attributes, and you can use getattr to get those named attributes from the underlying objects.\nclass GenericIndexedCollection( set ):\n attributes_to_index = [ ] # List of attribute names\n def __init__( self, *args, **kw ):\n self.indexes = dict( (n, {}) for n in self.attributes_to_index ]\n super( PersonCollection, self ).__init__( *args, **kw )\n def add( self, person ):\n super( PersonCollection, self ).append( person )\n for i in self.indexes:\n self.indexes[i].append( getattr( person, i )\n\nNote. To properly emulate a database, use a set not a list. Database tables are (theoretically) sets. As a practical matter they are unordered, and an index will allow the database to reject duplicates. Some RDBMS's don't reject duplicate rows because -- without an index -- it's too expensive to check.\n",
"Well, another way may be to implement the following:\n\nAttr is an abstraction for a \"value\". We need this since there is no \"assignment overloading\" in Python (simple get / set paradigm is used as the cleanest alternative). Attr also acts as an \"Observable\".\nAttrSet is an \"Observer\" for Attrs, which tracks their value changes while effectively acting as an Attr-to-whatever (person in our case) dictionary.\ncreate_with_attrs is a factory producing what looks like a named-tuple, forwarding attribute access via supplied Attrs, so that person.name = \"Ivan\" effectively yields person.name_attr.set(\"Ivan\") and makes the AttrSets observing this person's name appropriately rearrange their internals.\n\nThe code (tested):\nfrom collections import defaultdict\n\nclass Attribute(object):\n def __init__(self, value):\n super(Attribute, self).__init__()\n self._value = value\n self._notified_set = set()\n def set(self, value):\n old = self._value\n self._value = value\n for n_ch in self._notified_set:\n n_ch(old_value=old, new_value=value)\n def get(self):\n return self._value\n def add_notify_changed(self, notify_changed):\n self._notified_set.add(notify_changed)\n def remove_notify_changed(self, notify_changed):\n self._notified_set.remove(notify_changed)\n\nclass AttrSet(object):\n def __init__(self):\n super(AttrSet, self).__init__()\n self._attr_value_to_obj_set = defaultdict(set)\n self._obj_to_attr = {}\n self._attr_to_notify_changed = {}\n def add(self, attr, obj):\n self._obj_to_attr[obj] = attr\n self._add(attr.get(), obj)\n notify_changed = (lambda old_value, new_value:\n self._notify_changed(obj, old_value, new_value))\n attr.add_notify_changed(notify_changed)\n self._attr_to_notify_changed[attr] = notify_changed\n def get(self, *attr_value_lst):\n attr_value_lst = attr_value_lst or self._attr_value_to_obj_set.keys()\n result = set()\n for attr_value in attr_value_lst:\n result.update(self._attr_value_to_obj_set[attr_value])\n return result\n def remove(self, obj):\n attr = self._obj_to_attr.pop(obj)\n self._remove(attr.get(), obj)\n notify_changed = self._attr_to_notify_changed.pop(attr)\n attr.remove_notify_changed(notify_changed)\n def __iter__(self):\n return iter(self.get())\n def _add(self, attr_value, obj):\n self._attr_value_to_obj_set[attr_value].add(obj)\n def _remove(self, attr_value, obj):\n obj_set = self._attr_value_to_obj_set[attr_value]\n obj_set.remove(obj)\n if not obj_set:\n self._attr_value_to_obj_set.pop(attr_value)\n def _notify_changed(self, obj, old_value, new_value):\n self._remove(old_value, obj)\n self._add(new_value, obj)\n\ndef create_with_attrs(**attr_name_to_attr):\n class Result(object):\n def __getattr__(self, attr_name):\n if attr_name in attr_name_to_attr.keys():\n return attr_name_to_attr[attr_name].get()\n else:\n raise AttributeError(attr_name)\n def __setattr__(self, attr_name, attr_value):\n if attr_name in attr_name_to_attr.keys():\n attr_name_to_attr[attr_name].set(attr_value)\n else:\n raise AttributeError(attr_name)\n def __str__(self):\n result = \"\"\n for attr_name in attr_name_to_attr:\n result += (attr_name + \": \"\n + str(attr_name_to_attr[attr_name].get())\n + \", \")\n return result\n return Result()\n\nWith the data prepared with\nname_and_email_lst = [(\"John\",\"email1@dot.com\"),\n (\"John\",\"email2@dot.com\"),\n (\"Jack\",\"email3@dot.com\"),\n (\"Hack\",\"email4@dot.com\"),\n ]\n\nemail = AttrSet()\nname = AttrSet()\n\nfor name_str, email_str in name_and_email_lst:\n email_attr = Attribute(email_str)\n name_attr = Attribute(name_str)\n person = create_with_attrs(email=email_attr, name=name_attr)\n email.add(email_attr, person)\n name.add(name_attr, person)\n\ndef print_set(person_set):\n for person in person_set: print person\n print\n\nthe following pseudo-SQL snippet sequence gives:\nSELECT id FROM email\n>>> print_set(email.get())\nemail: email3@dot.com, name: Jack,\nemail: email4@dot.com, name: Hack,\nemail: email2@dot.com, name: John,\nemail: email1@dot.com, name: John,\n\nSELECT id FROM email WHERE email=\"email1@dot.com\"\n>>> print_set(email.get(\"email1@dot.com\"))\nemail: email1@dot.com, name: John,\n\nSELECT id FROM email WHERE email=\"email1@dot.com\" OR email=\"email2@dot.com\"\n>>> print_set(email.get(\"email1@dot.com\", \"email2@dot.com\"))\nemail: email1@dot.com, name: John,\nemail: email2@dot.com, name: John,\n\nSELECT id FROM name WHERE name=\"John\"\n>>> print_set(name.get(\"John\"))\nemail: email1@dot.com, name: John,\nemail: email2@dot.com, name: John,\n\nSELECT id FROM name, email WHERE name=\"John\" AND email=\"email1@dot.com\"\n>>> print_set(name.get(\"John\").intersection(email.get(\"email1@dot.com\")))\nemail: email1@dot.com, name: John,\n\nUPDATE email, name SET email=\"jon@dot.com\", name=\"Jon\"\nWHERE id IN\nSELECT id FROM email WHERE email=\"email1@dot.com\"\n>>> person = email.get(\"email1@dot.com\").pop()\n>>> person.name = \"Jon\"; person.email = \"jon@dot.com\"\n>>> print_set(email.get())\nemail: email3@dot.com, name: Jack,\nemail: email4@dot.com, name: Hack,\nemail: email2@dot.com, name: John,\nemail: jon@dot.com, name: Jon,\n\nDELETE FROM email, name WHERE id=%s\nSELECT id FROM email\n>>> name.remove(person)\n>>> email.remove(person)\n>>> print_set(email.get())\nemail: email3@dot.com, name: Jack,\nemail: email4@dot.com, name: Hack,\nemail: email2@dot.com, name: John,\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"data_structures",
"design_patterns",
"dictionary",
"indexing",
"python"
] |
stackoverflow_0002305798_data_structures_design_patterns_dictionary_indexing_python.txt
|
Q:
Django group / aggregation
I have following structure with example data:
id season_id title
1 1 Intro
2 1 Second part
3 1 Third part
4 4 Other intro
5 4 Other second part
(don't ask why), where season_id is always point to id of first episode of season...
What i want, to get following:
1 1 Intro
4 4 Other intro
which are first episoded for season, technically speaking - all entries with lowest season_eid
for and i am using following query to get ids of them:
Movie.objects.filter(category_type = 2).values('season_eid').annotate(models.Min('season_eid'))
and having id i can get all data for objects using django orm __in construction.
Can I make grouping / annotate and take all fields/values using only one query? values + annotate gives me only list of dictionaries, but instead of this i would like to get proper objects (lowest value/min of season_eid) with rest of fields.
A:
Movie.objects.annotate(category_min_season = models.Min('category__season_id')).filter(season_id=category_min_season)
assuming that your catgory has FK to the Movies model.
Update:
Actually you don't even need annotation; thanks to the denormalised data you have stored in the table.
You can just do:
Model.objects.filter(id=Q(season_id))
|
Django group / aggregation
|
I have following structure with example data:
id season_id title
1 1 Intro
2 1 Second part
3 1 Third part
4 4 Other intro
5 4 Other second part
(don't ask why), where season_id is always point to id of first episode of season...
What i want, to get following:
1 1 Intro
4 4 Other intro
which are first episoded for season, technically speaking - all entries with lowest season_eid
for and i am using following query to get ids of them:
Movie.objects.filter(category_type = 2).values('season_eid').annotate(models.Min('season_eid'))
and having id i can get all data for objects using django orm __in construction.
Can I make grouping / annotate and take all fields/values using only one query? values + annotate gives me only list of dictionaries, but instead of this i would like to get proper objects (lowest value/min of season_eid) with rest of fields.
|
[
"Movie.objects.annotate(category_min_season = models.Min('category__season_id')).filter(season_id=category_min_season)\n\nassuming that your catgory has FK to the Movies model.\nUpdate:\nActually you don't even need annotation; thanks to the denormalised data you have stored in the table.\nYou can just do:\nModel.objects.filter(id=Q(season_id))\n\n"
] |
[
1
] |
[] |
[] |
[
"annotate",
"django",
"group_by",
"orm",
"python"
] |
stackoverflow_0002317374_annotate_django_group_by_orm_python.txt
|
Q:
Python equivalent for Ruby's ObjectSpace?
I've a name of a class stored in var, which I need to create an object from.
However I do not know in which module it is defined (if I did, I would just call getattr(module,var), but I do know it's imported.
Should I go over every module and test if the class is defined there ? How do I do it in python ?
What if I have the module + class in the same var, how can I create an object from it ? (ie var = 'module.class')
Cheers,
Ze
A:
globals()[classname] should do it.
More code: http://code.activestate.com/recipes/285262/
A:
Classes are not added to a global registry in Python by default. You'll need to iterate over all imported modules and look for it.
A:
Rather than storing the classname as a string, why don't you store the class object in the var, so you can instantiate it directly.
>>> class A(object):
... def __init__(self):
... print 'A new object created'
...
>>> class_object = A
>>> object = class_object()
A new object created
>>>
|
Python equivalent for Ruby's ObjectSpace?
|
I've a name of a class stored in var, which I need to create an object from.
However I do not know in which module it is defined (if I did, I would just call getattr(module,var), but I do know it's imported.
Should I go over every module and test if the class is defined there ? How do I do it in python ?
What if I have the module + class in the same var, how can I create an object from it ? (ie var = 'module.class')
Cheers,
Ze
|
[
"globals()[classname] should do it.\nMore code: http://code.activestate.com/recipes/285262/\n",
"Classes are not added to a global registry in Python by default. You'll need to iterate over all imported modules and look for it.\n",
"Rather than storing the classname as a string, why don't you store the class object in the var, so you can instantiate it directly.\n>>> class A(object):\n... def __init__(self):\n... print 'A new object created'\n... \n>>> class_object = A\n>>> object = class_object()\nA new object created\n>>> \n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"metaprogramming",
"module",
"python",
"ruby"
] |
stackoverflow_0002318044_metaprogramming_module_python_ruby.txt
|
Q:
Controlling VirtualBox
Documentation for pyVB is given in http://enomalism.com/api/pyvb/
we are trying to make a commandline interface to virtualbox using pyvb module in python.
>>> import pyvb
>>> n=pyvb.vm.vbVM()
>>> n.setUUID("64e1b2e5-739e-45a6-b8d7-3ab7519c5215}")
>>> m=pyvb.vb.VB()
>>> m.startVM(n)
this is how we tried doing it, but vm doesn't get started.
A:
Why reinvent the wheel; VirtualBox already comes with a command line interface?
|
Controlling VirtualBox
|
Documentation for pyVB is given in http://enomalism.com/api/pyvb/
we are trying to make a commandline interface to virtualbox using pyvb module in python.
>>> import pyvb
>>> n=pyvb.vm.vbVM()
>>> n.setUUID("64e1b2e5-739e-45a6-b8d7-3ab7519c5215}")
>>> m=pyvb.vb.VB()
>>> m.startVM(n)
this is how we tried doing it, but vm doesn't get started.
|
[
"Why reinvent the wheel; VirtualBox already comes with a command line interface?\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002318127_python.txt
|
Q:
groovy map coercion in python
I'm a relative newcomer to python and I'm just wondering if there is some equivalent to the map coercion feature available in groovy.
For context, I am writing a unit test and want to mock a class with a simple two method interface, in groovy I would do the following:
mock = [apply:{value -> return value*2 }, isValid:{return true}]
testObject.applyMock(mock)
i.e, mock can be treated as an object with a class like:
class mock:
def apply(self, value):
return value *2
def isValid(self):
return true
Is there a nice pythonic way to achieve this?
Cheers
Alex
A:
Use the 3-parameter form of type():
mock = type('mock', (object,), {'apply': (lambda self, value: value * 2),
'isValid': lambda self: True})
|
groovy map coercion in python
|
I'm a relative newcomer to python and I'm just wondering if there is some equivalent to the map coercion feature available in groovy.
For context, I am writing a unit test and want to mock a class with a simple two method interface, in groovy I would do the following:
mock = [apply:{value -> return value*2 }, isValid:{return true}]
testObject.applyMock(mock)
i.e, mock can be treated as an object with a class like:
class mock:
def apply(self, value):
return value *2
def isValid(self):
return true
Is there a nice pythonic way to achieve this?
Cheers
Alex
|
[
"Use the 3-parameter form of type():\nmock = type('mock', (object,), {'apply': (lambda self, value: value * 2),\n 'isValid': lambda self: True})\n\n"
] |
[
2
] |
[] |
[] |
[
"closures",
"mocking",
"python"
] |
stackoverflow_0002318494_closures_mocking_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.