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:
Fitting a line in 3D
Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line from 2D data sets, but none in 3D.
Thanks.
A:
If you are trying to predict one value from the other two, then you should use lstsq with the a argument as your independent variables (plus a column of 1's to estimate an intercept) and b as your dependent variable.
If, on the other hand, you just want to get the best fitting line to the data, i.e. the line which, if you projected the data onto it, would minimize the squared distance between the real point and its projection, then what you want is the first principal component.
One way to define it is the line whose direction vector is the eigenvector of the covariance matrix corresponding to the largest eigenvalue, that passes through the mean of your data. That said, eig(cov(data)) is a really bad way to calculate it, since it does a lot of needless computation and copying and is potentially less accurate than using svd. See below:
import numpy as np
# Generate some data that lies along a line
x = np.mgrid[-2:5:120j]
y = np.mgrid[1:9:120j]
z = np.mgrid[-5:3:120j]
data = np.concatenate((x[:, np.newaxis],
y[:, np.newaxis],
z[:, np.newaxis]),
axis=1)
# Perturb with some Gaussian noise
data += np.random.normal(size=data.shape) * 0.4
# Calculate the mean of the points, i.e. the 'center' of the cloud
datamean = data.mean(axis=0)
# Do an SVD on the mean-centered data.
uu, dd, vv = np.linalg.svd(data - datamean)
# Now vv[0] contains the first principal component, i.e. the direction
# vector of the 'best fit' line in the least squares sense.
# Now generate some points along this best fit line, for plotting.
# I use -7, 7 since the spread of the data is roughly 14
# and we want it to have mean 0 (like the points we did
# the svd on). Also, it's a straight line, so we only need 2 points.
linepts = vv[0] * np.mgrid[-7:7:2j][:, np.newaxis]
# shift by the mean to get the line in the right place
linepts += datamean
# Verify that everything looks right.
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d as m3d
ax = m3d.Axes3D(plt.figure())
ax.scatter3D(*data.T)
ax.plot3D(*linepts.T)
plt.show()
Here's what it looks like:
A:
If your data is fairly well behaved then it should be sufficient to find the least squares sum of the component distances. Then you can find the linear regression with z independent of x and then again independent of y.
Following the documentation example:
import numpy as np
pts = np.add.accumulate(np.random.random((10,3)))
x,y,z = pts.T
# this will find the slope and x-intercept of a plane
# parallel to the y-axis that best fits the data
A_xz = np.vstack((x, np.ones(len(x)))).T
m_xz, c_xz = np.linalg.lstsq(A_xz, z)[0]
# again for a plane parallel to the x-axis
A_yz = np.vstack((y, np.ones(len(y)))).T
m_yz, c_yz = np.linalg.lstsq(A_yz, z)[0]
# the intersection of those two planes and
# the function for the line would be:
# z = m_yz * y + c_yz
# z = m_xz * x + c_xz
# or:
def lin(z):
x = (z - c_xz)/m_xz
y = (z - c_yz)/m_yz
return x,y
#verifying:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
zz = np.linspace(0,5)
xx,yy = lin(zz)
ax.scatter(x, y, z)
ax.plot(xx,yy,zz)
plt.savefig('test.png')
plt.show()
If you want to minimize the actual orthogonal distances from the line (orthogonal to the line) to the points in 3-space (which I'm not sure is even referred to as linear regression). Then I would build a function that computes the RSS and use a scipy.optimize minimization function to solve it.
|
Fitting a line in 3D
|
Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line from 2D data sets, but none in 3D.
Thanks.
|
[
"If you are trying to predict one value from the other two, then you should use lstsq with the a argument as your independent variables (plus a column of 1's to estimate an intercept) and b as your dependent variable. \nIf, on the other hand, you just want to get the best fitting line to the data, i.e. the line which, if you projected the data onto it, would minimize the squared distance between the real point and its projection, then what you want is the first principal component. \nOne way to define it is the line whose direction vector is the eigenvector of the covariance matrix corresponding to the largest eigenvalue, that passes through the mean of your data. That said, eig(cov(data)) is a really bad way to calculate it, since it does a lot of needless computation and copying and is potentially less accurate than using svd. See below:\nimport numpy as np\n\n# Generate some data that lies along a line\n\nx = np.mgrid[-2:5:120j]\ny = np.mgrid[1:9:120j]\nz = np.mgrid[-5:3:120j]\n\ndata = np.concatenate((x[:, np.newaxis], \n y[:, np.newaxis], \n z[:, np.newaxis]), \n axis=1)\n\n# Perturb with some Gaussian noise\ndata += np.random.normal(size=data.shape) * 0.4\n\n# Calculate the mean of the points, i.e. the 'center' of the cloud\ndatamean = data.mean(axis=0)\n\n# Do an SVD on the mean-centered data.\nuu, dd, vv = np.linalg.svd(data - datamean)\n\n# Now vv[0] contains the first principal component, i.e. the direction\n# vector of the 'best fit' line in the least squares sense.\n\n# Now generate some points along this best fit line, for plotting.\n\n# I use -7, 7 since the spread of the data is roughly 14\n# and we want it to have mean 0 (like the points we did\n# the svd on). Also, it's a straight line, so we only need 2 points.\nlinepts = vv[0] * np.mgrid[-7:7:2j][:, np.newaxis]\n\n# shift by the mean to get the line in the right place\nlinepts += datamean\n\n# Verify that everything looks right.\n\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d as m3d\n\nax = m3d.Axes3D(plt.figure())\nax.scatter3D(*data.T)\nax.plot3D(*linepts.T)\nplt.show()\n\nHere's what it looks like: \n",
"If your data is fairly well behaved then it should be sufficient to find the least squares sum of the component distances. Then you can find the linear regression with z independent of x and then again independent of y.\nFollowing the documentation example:\nimport numpy as np\n\npts = np.add.accumulate(np.random.random((10,3)))\nx,y,z = pts.T\n\n# this will find the slope and x-intercept of a plane\n# parallel to the y-axis that best fits the data\nA_xz = np.vstack((x, np.ones(len(x)))).T\nm_xz, c_xz = np.linalg.lstsq(A_xz, z)[0]\n\n# again for a plane parallel to the x-axis\nA_yz = np.vstack((y, np.ones(len(y)))).T\nm_yz, c_yz = np.linalg.lstsq(A_yz, z)[0]\n\n# the intersection of those two planes and\n# the function for the line would be:\n# z = m_yz * y + c_yz\n# z = m_xz * x + c_xz\n# or:\ndef lin(z):\n x = (z - c_xz)/m_xz\n y = (z - c_yz)/m_yz\n return x,y\n\n#verifying:\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = Axes3D(fig)\nzz = np.linspace(0,5)\nxx,yy = lin(zz)\nax.scatter(x, y, z)\nax.plot(xx,yy,zz)\nplt.savefig('test.png')\nplt.show()\n\nIf you want to minimize the actual orthogonal distances from the line (orthogonal to the line) to the points in 3-space (which I'm not sure is even referred to as linear regression). Then I would build a function that computes the RSS and use a scipy.optimize minimization function to solve it.\n"
] |
[
59,
5
] |
[] |
[] |
[
"curve_fitting",
"linear_algebra",
"numpy",
"python"
] |
stackoverflow_0002298390_curve_fitting_linear_algebra_numpy_python.txt
|
Q:
Using Property Builtin with GAE Datastore's Model
I want to make attributes of GAE Model properties. The reason is for cases like to turn the value into uppercase before storing it. For a plain Python class, I would do something like:
Foo(db.Model):
def get_attr(self):
return self.something
def set_attr(self, value):
self.something = value.upper() if value != None else None
attr = property(get_attr, set_attr)
However, GAE Datastore have their own concept of Property class, I looked into the documentation and it seems that I could override get_value_for_datastore(model_instance) to achieve my goal. Nevertheless, I don't know what model_instance is and how to extract the corresponding field from it.
Is overriding GAE Property classes the right way to provides getter/setter-like functionality? If so, how to do it?
Added:
One potential issue of overriding get_value_for_datastore that I think of is it might not get called before the object was put into datastore. Hence getting the attribute before storing the object would yield an incorrect value.
A:
Subclassing GAE's Property class is especially helpful if you want more than one "field" with similar behavior, in one or more models. Don't worry, get_value_for_datastore and make_value_from_datastore are going to get called, on any store and fetch respectively -- so if you need to do anything fancy (including but not limited to uppercasing a string, which isn't actually all that fancy;-), overriding these methods in your subclass is just fine.
Edit: let's see some example code (net of imports and main):
class MyStringProperty(db.StringProperty):
def get_value_for_datastore(self, model_instance):
vv = db.StringProperty.get_value_for_datastore(self, model_instance)
return vv.upper()
class MyModel(db.Model):
foo = MyStringProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
my = MyModel(foo='Hello World')
k = my.put()
mm = MyModel.get(k)
s = mm.foo
self.response.out.write('The secret word is: %r' % s)
This shows you the string's been uppercased in the datastore -- but if you change the get call to a simple mm = my you'll see the in-memory instance wasn't affected.
But, a db.Property instance itself is a descriptor -- wrapping it into a built-in property (a completely different descriptor) will not work well with the datastore (for example, you can't write GQL queries based on field names that aren't really instances of db.Property but instances of property -- those fields are not in the datastore!).
So if you want to work with both the datastore and for instances of Model that have never actually been to the datastore and back, you'll have to choose two names for what's logically "the same" field -- one is the name of the attribute you'll use on in-memory model instances, and that one can be a built-in property; the other one is the name of the attribute that ends up in the datastore, and that one needs to be an instance of a db.Property subclass and it's this second name that you'll need to use in queries. Of course the methods underlying the first name need to read and write the second name, but you can't just "hide" the latter because that's the name that's going to be in the datastore, and so that's the name that will make sense to queries!
A:
What you want is a DerivedProperty. The procedure for writing one is outlined in that post - it's similar to what Alex describes, but by overriding get instead of get_value_for_datastore, you avoid issues with needing to write to the datastore to update it. My aetycoon library has it and other useful properties included.
|
Using Property Builtin with GAE Datastore's Model
|
I want to make attributes of GAE Model properties. The reason is for cases like to turn the value into uppercase before storing it. For a plain Python class, I would do something like:
Foo(db.Model):
def get_attr(self):
return self.something
def set_attr(self, value):
self.something = value.upper() if value != None else None
attr = property(get_attr, set_attr)
However, GAE Datastore have their own concept of Property class, I looked into the documentation and it seems that I could override get_value_for_datastore(model_instance) to achieve my goal. Nevertheless, I don't know what model_instance is and how to extract the corresponding field from it.
Is overriding GAE Property classes the right way to provides getter/setter-like functionality? If so, how to do it?
Added:
One potential issue of overriding get_value_for_datastore that I think of is it might not get called before the object was put into datastore. Hence getting the attribute before storing the object would yield an incorrect value.
|
[
"Subclassing GAE's Property class is especially helpful if you want more than one \"field\" with similar behavior, in one or more models. Don't worry, get_value_for_datastore and make_value_from_datastore are going to get called, on any store and fetch respectively -- so if you need to do anything fancy (including but not limited to uppercasing a string, which isn't actually all that fancy;-), overriding these methods in your subclass is just fine.\nEdit: let's see some example code (net of imports and main):\nclass MyStringProperty(db.StringProperty):\n def get_value_for_datastore(self, model_instance):\n vv = db.StringProperty.get_value_for_datastore(self, model_instance)\n return vv.upper()\n\nclass MyModel(db.Model):\n foo = MyStringProperty()\n\nclass MainHandler(webapp.RequestHandler):\n\n def get(self):\n my = MyModel(foo='Hello World')\n k = my.put()\n mm = MyModel.get(k)\n s = mm.foo\n self.response.out.write('The secret word is: %r' % s)\n\nThis shows you the string's been uppercased in the datastore -- but if you change the get call to a simple mm = my you'll see the in-memory instance wasn't affected.\nBut, a db.Property instance itself is a descriptor -- wrapping it into a built-in property (a completely different descriptor) will not work well with the datastore (for example, you can't write GQL queries based on field names that aren't really instances of db.Property but instances of property -- those fields are not in the datastore!).\nSo if you want to work with both the datastore and for instances of Model that have never actually been to the datastore and back, you'll have to choose two names for what's logically \"the same\" field -- one is the name of the attribute you'll use on in-memory model instances, and that one can be a built-in property; the other one is the name of the attribute that ends up in the datastore, and that one needs to be an instance of a db.Property subclass and it's this second name that you'll need to use in queries. Of course the methods underlying the first name need to read and write the second name, but you can't just \"hide\" the latter because that's the name that's going to be in the datastore, and so that's the name that will make sense to queries!\n",
"What you want is a DerivedProperty. The procedure for writing one is outlined in that post - it's similar to what Alex describes, but by overriding get instead of get_value_for_datastore, you avoid issues with needing to write to the datastore to update it. My aetycoon library has it and other useful properties included.\n"
] |
[
3,
1
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002303090_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Python equivalents of the common Perl modules?
I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability):
DBI + DBD::mysql
LWP::UserAgent
WWW::Mechanize
XML::LibXML
HTML::TreeBuilder
CGI::FormBuilder
Template::Toolkit
What are the Python equivalents to these?
A:
DBI + DBD::mysql
MySQLdb
LWP::UserAgent
urllib (Python STL)
urllib2 (Python STL)
WWW::Mechanize
Mechanize
XML::LibXML
libxml2
lxml
HTML::TreeBuilder
xml.etree.ElementTree (Python STL)
CGI::FormBuilder
cgi and cgitb (Python STL)
Template::Toolkit
Template-Python
Note: Items marked above as Python STL are included as part of the Python Standard Library as listed in the Python v2.6.4 documentation.
A:
All Python database modules use the same API, so either MySQLdb or oursql will work.
urllib2
mechanize
etree or lxml
No direct equivalent, but BeautifulSoup and lxml can parse, and etree and lxml can generate.
FormEncode
Genshi, Jinja2, mako, cheetah, and too many others
urllib2 and etree are in the standard library; the rest are easy enough to get.
|
Python equivalents of the common Perl modules?
|
I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability):
DBI + DBD::mysql
LWP::UserAgent
WWW::Mechanize
XML::LibXML
HTML::TreeBuilder
CGI::FormBuilder
Template::Toolkit
What are the Python equivalents to these?
|
[
"DBI + DBD::mysql\n\nMySQLdb\n\nLWP::UserAgent\n\nurllib (Python STL)\nurllib2 (Python STL)\n\nWWW::Mechanize\n\nMechanize\n\nXML::LibXML\n\nlibxml2\nlxml\n\nHTML::TreeBuilder\n\nxml.etree.ElementTree (Python STL)\n\nCGI::FormBuilder\n\ncgi and cgitb (Python STL)\n\nTemplate::Toolkit\n\nTemplate-Python\n\nNote: Items marked above as Python STL are included as part of the Python Standard Library as listed in the Python v2.6.4 documentation.\n",
"\nAll Python database modules use the same API, so either MySQLdb or oursql will work.\nurllib2\nmechanize\netree or lxml\nNo direct equivalent, but BeautifulSoup and lxml can parse, and etree and lxml can generate.\nFormEncode\nGenshi, Jinja2, mako, cheetah, and too many others\n\nurllib2 and etree are in the standard library; the rest are easy enough to get.\n"
] |
[
15,
14
] |
[] |
[] |
[
"migration",
"perl",
"python"
] |
stackoverflow_0002333851_migration_perl_python.txt
|
Q:
How do I get my python object back from a QVariant in PyQt4?
I am creating a subclass of QAbstractItemModel to be displayed in an QTreeView.
My index() and parent() function creates the QModelIndex using the QAbstractItemModel inherited function createIndex and providing it the row, column, and data needed. Here, for testing purposes, data is a Python string.
class TestModel(QAbstractItemModel):
def __init__(self):
QAbstractItemModel.__init__(self)
def index(self, row, column, parent):
if parent.isValid():
return self.createIndex(row, column, "bar")
return self.createIndex(row, column, "foo")
def parent(self, index):
if index.isValid():
if index.data().data() == "bar": <--- NEVER TRUE
return self.createIndex(0, 0, "foo")
return QModelIndex()
def rowCount(self, index):
if index.isValid():
if index.data().data() == "bar": <--- NEVER TRUE
return 0
return 1
def columnCount(self, index):
return 1
def data(self, index, role):
if index.isValid():
return index.data().data() <--- CANNOT DO ANYTHING WITH IT
return "<None>"
Within the index(), parent(), and data() functions I need to get my data back. It comes as a QVariant. How do I get my Python object back from the QVariant?
A:
Have you tried this?
my_python_object = my_qvariant.toPyObject()
http://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toPyObject (just for completeness, but there isn't much to see there...)
A:
The key thing is to use internalPointer() directly on the QModelIndex, not dealing with the QVariant at all.
class TestModel(QAbstractItemModel):
def __init__(self, plan):
QAbstractItemModel.__init__(self)
def index(self, row, column, parent):
if not parent.isValid():
return self.createIndex(row, column, "foo")
return self.createIndex(row, column, "bar")
def parent(self, index):
if index.internalPointer() == "bar":
return self.createIndex(0, 0, "foo")
return QModelIndex()
def rowCount(self, index):
if index.internalPointer() == "bar":
return 0
return 1
def columnCount(self, index):
return 1
def data(self, index, role):
if role == 0: # Qt.DisplayRole
return index.internalPointer()
else:
return None
|
How do I get my python object back from a QVariant in PyQt4?
|
I am creating a subclass of QAbstractItemModel to be displayed in an QTreeView.
My index() and parent() function creates the QModelIndex using the QAbstractItemModel inherited function createIndex and providing it the row, column, and data needed. Here, for testing purposes, data is a Python string.
class TestModel(QAbstractItemModel):
def __init__(self):
QAbstractItemModel.__init__(self)
def index(self, row, column, parent):
if parent.isValid():
return self.createIndex(row, column, "bar")
return self.createIndex(row, column, "foo")
def parent(self, index):
if index.isValid():
if index.data().data() == "bar": <--- NEVER TRUE
return self.createIndex(0, 0, "foo")
return QModelIndex()
def rowCount(self, index):
if index.isValid():
if index.data().data() == "bar": <--- NEVER TRUE
return 0
return 1
def columnCount(self, index):
return 1
def data(self, index, role):
if index.isValid():
return index.data().data() <--- CANNOT DO ANYTHING WITH IT
return "<None>"
Within the index(), parent(), and data() functions I need to get my data back. It comes as a QVariant. How do I get my Python object back from the QVariant?
|
[
"Have you tried this?\nmy_python_object = my_qvariant.toPyObject()\n\nhttp://pyqt.sourceforge.net/Docs/PyQt4/qvariant.html#toPyObject (just for completeness, but there isn't much to see there...)\n",
"The key thing is to use internalPointer() directly on the QModelIndex, not dealing with the QVariant at all.\nclass TestModel(QAbstractItemModel):\n def __init__(self, plan):\n QAbstractItemModel.__init__(self)\n\n def index(self, row, column, parent):\n if not parent.isValid():\n return self.createIndex(row, column, \"foo\")\n return self.createIndex(row, column, \"bar\")\n\n def parent(self, index):\n if index.internalPointer() == \"bar\":\n return self.createIndex(0, 0, \"foo\")\n return QModelIndex()\n\n def rowCount(self, index):\n if index.internalPointer() == \"bar\":\n return 0\n return 1\n\n def columnCount(self, index):\n return 1\n\n def data(self, index, role):\n if role == 0: # Qt.DisplayRole\n return index.internalPointer()\n else:\n return None\n\n"
] |
[
13,
5
] |
[] |
[] |
[
"pyqt4",
"python",
"qabstractitemmodel",
"qvariant"
] |
stackoverflow_0002333420_pyqt4_python_qabstractitemmodel_qvariant.txt
|
Q:
Transforming nested Python loops into list comprehensions
I've started working on some Project Euler problems, and have solved number 4 with a simple brute force solution:
def mprods(a,b):
c = range(a,b)
f = []
for d in c:
for e in c:
f.append(d*e)
return f
max([z for z in mprods(100,1000) if str(z)==(''.join([str(z)[-i] for i in range(1,len(str(z))+1)]))])
After solving, I tried to make it as compact as possible, and came up with that horrible bottom line!
Not to leave something half-done, I am trying to condense the mprods function into a list comprehension. So far, I've come up with these attempts:
[d*e for d,e in (range(a,b), range(a,b))]
Obviously completely on the wrong track. :-)
[d*e for x in [e for e in range(1,5)] for d in range(1,5)]
This gives me [4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16], where I expect
[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16] or similar.
Any Pythonistas out there that can help? :)
A:
c = range(a, b)
print [d * e for d in c for e in c]
A:
from itertools import product
def palindrome(i):
return str(i) == str(i)[::-1]
x = xrange(900,1000)
max(a*b for (a,b) in (product(x,x)) if palindrome(a*b))
xrange(900,1000) is like range(900,1000) but instead of returning a list it returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.
product(xrange(900,1000),xrange(900,1000)) gives the Cartesian product of the input iterables. It is equivalent to nested for-loops. For example, product(A, B) returns the same as: ((x,y) for x in A for y in B). The leftmost iterators are in the outermost for-loop, so the output tuples cycle in a manner similar to an odometer (with the rightmost element changing on every iteration).
product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)
product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...
str(i)[::-1] is list slicing shorthand to reverse a list.
Note how everything is wrapped in a generator expression, a high performance, memory efficient generalization of list comprehensions and generators.
Also note that the largest palindrome made from the product of two 2-digit numbers is made from the numbers 91 99, two numbers in the range(90,100). Extrapolating to 3-digit numbers you can use range(900,1000).
A:
I think you'll like this one-liner (formatted for readability):
max(z for z in (d*e
for d in xrange(100, 1000)
for e in xrange(100, 1000))
if str(z) == str(z)[::-1])
Or slightly changed:
c = range(100, 1000)
max(z for z in (d*e for d in c for e in c) if str(z) == str(z)[::-1])
Wonder how many parens that would be in Lisp...
|
Transforming nested Python loops into list comprehensions
|
I've started working on some Project Euler problems, and have solved number 4 with a simple brute force solution:
def mprods(a,b):
c = range(a,b)
f = []
for d in c:
for e in c:
f.append(d*e)
return f
max([z for z in mprods(100,1000) if str(z)==(''.join([str(z)[-i] for i in range(1,len(str(z))+1)]))])
After solving, I tried to make it as compact as possible, and came up with that horrible bottom line!
Not to leave something half-done, I am trying to condense the mprods function into a list comprehension. So far, I've come up with these attempts:
[d*e for d,e in (range(a,b), range(a,b))]
Obviously completely on the wrong track. :-)
[d*e for x in [e for e in range(1,5)] for d in range(1,5)]
This gives me [4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16], where I expect
[1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16] or similar.
Any Pythonistas out there that can help? :)
|
[
"c = range(a, b)\nprint [d * e for d in c for e in c]\n\n",
"from itertools import product\n\ndef palindrome(i):\n return str(i) == str(i)[::-1]\n\nx = xrange(900,1000)\n\nmax(a*b for (a,b) in (product(x,x)) if palindrome(a*b))\n\n\nxrange(900,1000) is like range(900,1000) but instead of returning a list it returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.\nproduct(xrange(900,1000),xrange(900,1000)) gives the Cartesian product of the input iterables. It is equivalent to nested for-loops. For example, product(A, B) returns the same as: ((x,y) for x in A for y in B). The leftmost iterators are in the outermost for-loop, so the output tuples cycle in a manner similar to an odometer (with the rightmost element changing on every iteration). \nproduct('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\nproduct((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...\nstr(i)[::-1] is list slicing shorthand to reverse a list.\nNote how everything is wrapped in a generator expression, a high performance, memory efficient generalization of list comprehensions and generators.\nAlso note that the largest palindrome made from the product of two 2-digit numbers is made from the numbers 91 99, two numbers in the range(90,100). Extrapolating to 3-digit numbers you can use range(900,1000).\n\n",
"I think you'll like this one-liner (formatted for readability):\nmax(z for z in (d*e\n for d in xrange(100, 1000)\n for e in xrange(100, 1000))\n if str(z) == str(z)[::-1])\n\nOr slightly changed:\nc = range(100, 1000)\nmax(z for z in (d*e for d in c for e in c) if str(z) == str(z)[::-1])\n\nWonder how many parens that would be in Lisp...\n"
] |
[
7,
3,
2
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0002329165_list_comprehension_python.txt
|
Q:
Jython 2.2.1, howto move a file? shutils.move is non-existant!
'''use Jython'''
import shutil
print dir(shutil)
There is no, shutil.move, how does one move a file with Jython?
and while we at it, how does one delete a file with Jython?
A:
os.rename() to move, and os.unlink() to delete -- just like Python pre-shutil.
A:
If you need support for moving across filesystems, consider just copying CPython's shutil.py into your project. The Python License is flexible enough to allow this (even for commercial projects), as long as licensing and attribution information are retained.
A:
f1 = File(filename_old)
f1.nameTo(File(filename_new))
|
Jython 2.2.1, howto move a file? shutils.move is non-existant!
|
'''use Jython'''
import shutil
print dir(shutil)
There is no, shutil.move, how does one move a file with Jython?
and while we at it, how does one delete a file with Jython?
|
[
"os.rename() to move, and os.unlink() to delete -- just like Python pre-shutil.\n",
"If you need support for moving across filesystems, consider just copying CPython's shutil.py into your project. The Python License is flexible enough to allow this (even for commercial projects), as long as licensing and attribution information are retained.\n",
"f1 = File(filename_old)\nf1.nameTo(File(filename_new))\n\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"file_handling",
"java",
"jython",
"python",
"shutil"
] |
stackoverflow_0000249262_file_handling_java_jython_python_shutil.txt
|
Q:
Django queries: how to make contains OR not_contains queries
I have to make a query that will get records containing "wd2" substring or not containing "wd" string at all. Is there any way to do it nicely?
Seems something like:
Record.objects.filter( Q(parameter__icontains="wd2") | Q( ## what should be here? ## ) )
A:
From the django q object documentation:
You can compose statements of arbitrary complexity by combining Q objects with the & and | operators and use parenthetical grouping. Also, Q objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) query:
Q(question__startswith='Who') | ~Q(pub_date__year=2005)
So I would recommend
Record.objects.filter( Q(parameter__icontains="wd2") | ~Q(parameter__icontains="wd") )
|
Django queries: how to make contains OR not_contains queries
|
I have to make a query that will get records containing "wd2" substring or not containing "wd" string at all. Is there any way to do it nicely?
Seems something like:
Record.objects.filter( Q(parameter__icontains="wd2") | Q( ## what should be here? ## ) )
|
[
"From the django q object documentation:\n\nYou can compose statements of arbitrary complexity by combining Q objects with the & and | operators and use parenthetical grouping. Also, Q objects can be negated using the ~ operator, allowing for combined lookups that combine both a normal query and a negated (NOT) query:\n\nQ(question__startswith='Who') | ~Q(pub_date__year=2005)\n\nSo I would recommend\nRecord.objects.filter( Q(parameter__icontains=\"wd2\") | ~Q(parameter__icontains=\"wd\") )\n\n"
] |
[
15
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002334698_django_python.txt
|
Q:
Can distutils use a custom .def to expose extra symbols when it compiles a Windows .dll?
I'm abusing distutils to compile an extension module for Python, but rather than using the Python C API I'm using ctypes to talk to the resulting shared library.
This works fine in Linux because it automatically exports all symbols in a shared library, but in Windows distutils provides a .def to export only the Python module init function.
How do I extend distutils to provide my own .def on Windows so it will export the symbols I need?
A:
You can pass ['-Wl,--export-all-symbols'] as extra_link_args if you're using Mingw's GCC. There's probably a similar setting for Visual, somewhere in the IDE.
This works only if distutils chooses to use "gcc -mdll" as a linker instead of "dllwrap". It does so if your ld version is later than 2.10.90, which should be the case if you're using a recent Mingw. At first it didn't work for me because I used Python 2.2 which has a small bug related to version parsing: it expects 3 dot-separated numbers so it falls back to dllwrap if the ld version is 2.20...
|
Can distutils use a custom .def to expose extra symbols when it compiles a Windows .dll?
|
I'm abusing distutils to compile an extension module for Python, but rather than using the Python C API I'm using ctypes to talk to the resulting shared library.
This works fine in Linux because it automatically exports all symbols in a shared library, but in Windows distutils provides a .def to export only the Python module init function.
How do I extend distutils to provide my own .def on Windows so it will export the symbols I need?
|
[
"You can pass ['-Wl,--export-all-symbols'] as extra_link_args if you're using Mingw's GCC. There's probably a similar setting for Visual, somewhere in the IDE.\nThis works only if distutils chooses to use \"gcc -mdll\" as a linker instead of \"dllwrap\". It does so if your ld version is later than 2.10.90, which should be the case if you're using a recent Mingw. At first it didn't work for me because I used Python 2.2 which has a small bug related to version parsing: it expects 3 dot-separated numbers so it falls back to dllwrap if the ld version is 2.20...\n"
] |
[
1
] |
[] |
[] |
[
"distutils",
"dll",
"dllexport",
"python",
"windows"
] |
stackoverflow_0002334754_distutils_dll_dllexport_python_windows.txt
|
Q:
How to quickly (easy to script) preview 3D vectors / lines?
I am busy reading 3D building models from a tool and thus generating a bunch of Line(p1, p2) objects, each consisting of two Point(x, y, z) objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D).
The reading is done in Python, specifically IronPython. I could use either a .NET viewer library or write out a text/xml/whatnot file with the data to be displayed by manually opening the result in the appropriate program.
What format / tool would you use to view the data?
(At the moment, this is only for debugging purposes, so it doesn't have to be top-notch. Just a wire-frame will do!)
I did check the mathplot library, but that seems to only plot functions...
EDIT: I eventually did go the X3D route and wrote a little blog post on how to do it. Here is a sample X3D wireframe file for a 1x1x1 cube:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
"http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
<Scene>
<Transform>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 0
1 1 0
0 1 0
0 0 0
1 0 0"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 1
1 1 1
0 1 1
0 0 1
1 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 0 1
1 0 1
1 0 0
0 0 0
0 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 1 1
1 1 1
1 1 0
0 1 0
0 1 1"
/>
</LineSet>
</Shape>
</Transform>
</Scene>
</X3D>
A:
I'm not a 3D-programming expert but there is a simple trick you can do.
If you imagine that the z axis is vertical to your screen then you can project a 3D point (x, y, z) like this: (zoom_factor*(x/z), zoom_factor*(y/z))
A:
You might try the PyQwt3D package. If that doesn't work, here's a list of other python packages that might be useful.
A:
For using the writing to file approach you could investigate X3D, which is the successor to VRML. Also see this list of vector graphics markup languages
A:
You could look at POV-Ray. It's a ray tracer that has its own text based scene description language. IIRC, there is a python module which will generate the scene files, if not, it wouldn't be difficult to do by hand. Displaying line segments at low resolution should render fairly quickly.
Check here: http://code.activestate.com/recipes/205451/
Also, python is the scripting language for Blender.
|
How to quickly (easy to script) preview 3D vectors / lines?
|
I am busy reading 3D building models from a tool and thus generating a bunch of Line(p1, p2) objects, each consisting of two Point(x, y, z) objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D).
The reading is done in Python, specifically IronPython. I could use either a .NET viewer library or write out a text/xml/whatnot file with the data to be displayed by manually opening the result in the appropriate program.
What format / tool would you use to view the data?
(At the moment, this is only for debugging purposes, so it doesn't have to be top-notch. Just a wire-frame will do!)
I did check the mathplot library, but that seems to only plot functions...
EDIT: I eventually did go the X3D route and wrote a little blog post on how to do it. Here is a sample X3D wireframe file for a 1x1x1 cube:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
"http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
<Scene>
<Transform>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 0
1 1 0
0 1 0
0 0 0
1 0 0"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 1
1 1 1
0 1 1
0 0 1
1 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 0 1
1 0 1
1 0 0
0 0 0
0 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 1 1
1 1 1
1 1 0
0 1 0
0 1 1"
/>
</LineSet>
</Shape>
</Transform>
</Scene>
</X3D>
|
[
"I'm not a 3D-programming expert but there is a simple trick you can do.\nIf you imagine that the z axis is vertical to your screen then you can project a 3D point (x, y, z) like this: (zoom_factor*(x/z), zoom_factor*(y/z))\n",
"You might try the PyQwt3D package. If that doesn't work, here's a list of other python packages that might be useful.\n",
"For using the writing to file approach you could investigate X3D, which is the successor to VRML. Also see this list of vector graphics markup languages \n",
"You could look at POV-Ray. It's a ray tracer that has its own text based scene description language. IIRC, there is a python module which will generate the scene files, if not, it wouldn't be difficult to do by hand. Displaying line segments at low resolution should render fairly quickly.\nCheck here: http://code.activestate.com/recipes/205451/\nAlso, python is the scripting language for Blender.\n"
] |
[
1,
1,
1,
1
] |
[] |
[] |
[
".net",
"3d",
"ironpython",
"python"
] |
stackoverflow_0001345485_.net_3d_ironpython_python.txt
|
Q:
A decent SSL library for Python 2.5
I am tasked with migrating a server's networking from plain sockets to SSL in python 2.5, and I've run into a snag. It seems that just about no SSL library out there fully implements the socket interface, so the code we currently have can't be straight migrated.
Specifically, I can't seem to find a library that supports the 'setblocking' method (most of these are wrappers, so would it be terrible to just address the wrapped socket directly?) and most don't seem to treat the wrapped socket as a file-like device, so the crucial 'select' method won't work (again, could I run select on the wrapped socket?).
(read, write, error) = select([socket], [socket], [], 0.2)
I have tried tlslite and M2Crypto so far, but neither seem to work transparently as sockets.
Any ideas would be appreciated.
A:
How about this backport of Python 2.6's ssl module to Python 2.3+? It provides the same functionality described here, which appears to mean that it takes a normal socket.socket and wraps it in an SSL context.
A:
pyOpenSSL seems to support setblocking().
|
A decent SSL library for Python 2.5
|
I am tasked with migrating a server's networking from plain sockets to SSL in python 2.5, and I've run into a snag. It seems that just about no SSL library out there fully implements the socket interface, so the code we currently have can't be straight migrated.
Specifically, I can't seem to find a library that supports the 'setblocking' method (most of these are wrappers, so would it be terrible to just address the wrapped socket directly?) and most don't seem to treat the wrapped socket as a file-like device, so the crucial 'select' method won't work (again, could I run select on the wrapped socket?).
(read, write, error) = select([socket], [socket], [], 0.2)
I have tried tlslite and M2Crypto so far, but neither seem to work transparently as sockets.
Any ideas would be appreciated.
|
[
"How about this backport of Python 2.6's ssl module to Python 2.3+? It provides the same functionality described here, which appears to mean that it takes a normal socket.socket and wraps it in an SSL context.\n",
"pyOpenSSL seems to support setblocking().\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"ssl"
] |
stackoverflow_0002334354_python_ssl.txt
|
Q:
Post processing attendance data with Django
I have a web app which tries to determine when people are attending events.
class Attendee(models.Model):
location = models.ForeignKey(Location)
user = models.ForeignKey(User)
checked_in = models.DateTimeField()
checked_out = models.DateTimeField()
last_active = models.DateTimeField()
An Attendee is checked in whenever they sign in to a particular location, and an attendee is checked out whenever they sign out.
The problem is that determining when somebody is actually "checked out", because they may not actively sign out of the Django user system, I have to find a way to register them as being checked out after 24 hours.
At the moment I am using a horribly simplistic ORM query in a manager to list "active" and "inactive" users on the site.
expires = datetime.datetime.today() - datetime.timedelta(seconds=settings.AUTO_CHECKOUT_AFTER)
# Get people who were last active more than 24 hours ago OR who have checked out
inactive_users = User.objects.all().filter(Q(attendee__last_active__lt = expires) \
| Q(attendee__checked_out__lte = datetime.datetime.now()), \
attendee__location=location).exclude(attendee__checked_out = None, attendee__checked_in__gte = expires).distinct()
What is the better way to do this? I'm guessing need a Django equivalent to a CRON job to automatically check-out users that are inactive.
A:
You don't need a 'Django equivalent to a cron job', you just need a cron job.
The cron should run a standalone Django script - you can do this in several different ways, but the easiest way is to create a standalone ./manage.pycommand.
|
Post processing attendance data with Django
|
I have a web app which tries to determine when people are attending events.
class Attendee(models.Model):
location = models.ForeignKey(Location)
user = models.ForeignKey(User)
checked_in = models.DateTimeField()
checked_out = models.DateTimeField()
last_active = models.DateTimeField()
An Attendee is checked in whenever they sign in to a particular location, and an attendee is checked out whenever they sign out.
The problem is that determining when somebody is actually "checked out", because they may not actively sign out of the Django user system, I have to find a way to register them as being checked out after 24 hours.
At the moment I am using a horribly simplistic ORM query in a manager to list "active" and "inactive" users on the site.
expires = datetime.datetime.today() - datetime.timedelta(seconds=settings.AUTO_CHECKOUT_AFTER)
# Get people who were last active more than 24 hours ago OR who have checked out
inactive_users = User.objects.all().filter(Q(attendee__last_active__lt = expires) \
| Q(attendee__checked_out__lte = datetime.datetime.now()), \
attendee__location=location).exclude(attendee__checked_out = None, attendee__checked_in__gte = expires).distinct()
What is the better way to do this? I'm guessing need a Django equivalent to a CRON job to automatically check-out users that are inactive.
|
[
"You don't need a 'Django equivalent to a cron job', you just need a cron job. \nThe cron should run a standalone Django script - you can do this in several different ways, but the easiest way is to create a standalone ./manage.pycommand.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002335239_django_python.txt
|
Q:
What is the scope of a defaulted parameter in Python?
When you define a function in Python with an array parameter, what is the scope of that parameter?
This example is taken from the Python tutorial:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
Prints:
[1]
[1, 2]
[1, 2, 3]
I'm not quite sure if I understand what's happening here. Does this mean that the scope of the array is outside of the function? Why does the array remember its values from call to call? Coming from other languages, I would expect this behavior only if the variable was static. Otherwise it seems it should be reset each time. And actually, when I tried the following:
def f(a):
L = []
L.append(a)
return L
I got the behavior I expected (the array was reset on each call).
So it seems to me that I just need the line def f(a, L=[]): explained - what is the scope of the L variable?
A:
The scope is as you would expect.
The perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].
The list is stored in f.__defaults__ (or f.func_defaults in Python 2.)
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
print f.__defaults__
f.__defaults__ = (['foo'],) # Don't do this!
print f(4)
Result:
[1]
[1, 2]
[1, 2, 3]
([1, 2, 3],)
['foo', 4]
A:
The scope of the L variable is behaving as you expect.
The "problem" is with the list you're creating with []. Python does not create a new list each time you call the function. L gets assigned the same list each time you call which is why the function "remembers" previous calls.
So in effect this is what you have:
mylist = []
def f(a, L=mylist):
L.append(a)
return L
The Python Tutorial puts it this way:
The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.
and suggests the following way to code the expected behaviour:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
A:
There's even less "magic" than you might suspect. This is equivalent to
m = []
def f(a, L=m):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
m is only created once.
A:
Say you have the following code:
def func(a=[]):
a.append(1)
print("A:", a)
func()
func()
func()
You can use python's indentation to help you understand what's going on. Everything that is flush to the left margin is executed when the file gets executed. Everything that's indented is compiled into a code object which gets executed when func() is called. So the function is defined and its default arguments set once, when the program gets executed (because the def statement is flush left).
What it does with the default arguments is an interesting issue. In python 3, it puts most of the information about a function in two places: func.__code__ and func.__defaults__. In python 2, func.__code__ was func.func_code func.__defaults__ was func.func_defaults. Later versions of python 2, including 2.6 have both sets of names, to aid the transition from python 2 to python 3. I will use the more modern __code__ and __defaults__. If you're stuck on an older python, the concepts are the same; just the names differ.
The default values are stored in func.__defaults__, and retrieved each time the function is called.
Thus when you define the function above, the body of the function gets compiled and stored in variables under __code__, to be executed later, and the default arguments get stored in __defaults__. When you call the function, it uses the values in __defaults__. If those values get modified for any reason, it only has the modified version available to use.
Play around defining different functions in the interactive interpreter, and see what you can figure out about how python creates and uses functions.
A:
The explaination is given in answers to this question. To sum it up here:
Functions in Python are a kind of object. Because they are a kind of object, they act like objects when instantiated. A function, if defined with a mutable attribute as a default argument, is exactly the same as a class with a static attribute that is a mutable list.
Lennart Regebro has a good explanation and the answer to the question by Roberto Liffredo is excellent.
To adapt Lennart's answer ... if I have a BananaBunch class:
class BananaBunch:
bananas = []
def addBanana(self, banana):
self.bananas.append(banana)
bunch = BananaBunch()
>>> bunch
<__main__.BananaBunch instance at 0x011A7FA8>
>>> bunch.addBanana(1)
>>> bunch.bananas
[1]
>>> for i in range(6):
bunch.addBanana("Banana #" + i)
>>> for i in range(6):
bunch.addBanana("Banana #" + str(i))
>>> bunch.bananas
[1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5']
// And for review ...
//If I then add something to the BananaBunch class ...
>>> BananaBunch.bananas.append("A mutated banana")
//My own bunch is suddenly corrupted. :-)
>>> bunch.bananas
[1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5', 'A mutated banana']
How does this apply to functions? Functions in Python are objects. This bears repeating. Functions in Python are objects.
So when you create a function, you are creating an object. When you give a function a mutable default value, you are populating that object's attribute with a mutable value, and every time you call that function you are operating on the same attribute. So if you are using a mutable call (like append), then you are modifying the same object, just as if you were adding bananas to the bunch object.
A:
The "problem" here is that L=[] is only evaluated once, that is, when the file is compiled. Python steps through each line of the file and compiles it. By the time it reaches the def with the default parameter, it creates that list instance once.
If you put L = [] inside the function code, the instance is not created at "compile time" (actually compile time can also be called part of the run time) because Python compiles the function's code but does not call it. So you will get a new list instance because the creation is done every time you call the function (instead of once during compilation).
A solution for that problem is not to use mutable objects as default parameters, or only fixed instances like None:
def f(a, L = None):
if l == None:
l = []
L.append(a)
return L
Note that in both cases you described, the scope of L is the function scope.
|
What is the scope of a defaulted parameter in Python?
|
When you define a function in Python with an array parameter, what is the scope of that parameter?
This example is taken from the Python tutorial:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
Prints:
[1]
[1, 2]
[1, 2, 3]
I'm not quite sure if I understand what's happening here. Does this mean that the scope of the array is outside of the function? Why does the array remember its values from call to call? Coming from other languages, I would expect this behavior only if the variable was static. Otherwise it seems it should be reset each time. And actually, when I tried the following:
def f(a):
L = []
L.append(a)
return L
I got the behavior I expected (the array was reset on each call).
So it seems to me that I just need the line def f(a, L=[]): explained - what is the scope of the L variable?
|
[
"The scope is as you would expect.\nThe perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].\nThe list is stored in f.__defaults__ (or f.func_defaults in Python 2.)\ndef f(a, L=[]):\n L.append(a)\n return L\n\nprint f(1)\nprint f(2)\nprint f(3)\nprint f.__defaults__\nf.__defaults__ = (['foo'],) # Don't do this!\nprint f(4)\n\nResult:\n[1]\n[1, 2]\n[1, 2, 3]\n([1, 2, 3],)\n['foo', 4]\n\n",
"The scope of the L variable is behaving as you expect. \nThe \"problem\" is with the list you're creating with []. Python does not create a new list each time you call the function. L gets assigned the same list each time you call which is why the function \"remembers\" previous calls. \nSo in effect this is what you have:\nmylist = []\ndef f(a, L=mylist):\n L.append(a)\n return L\n\nThe Python Tutorial puts it this way:\n\nThe default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. \n\nand suggests the following way to code the expected behaviour:\ndef f(a, L=None):\n if L is None:\n L = []\n L.append(a)\n return L\n\n",
"There's even less \"magic\" than you might suspect. This is equivalent to \nm = []\n\ndef f(a, L=m):\n L.append(a)\n return L\n\nprint f(1)\nprint f(2)\nprint f(3)\n\nm is only created once.\n",
"Say you have the following code:\ndef func(a=[]):\n a.append(1)\n print(\"A:\", a)\n\nfunc()\nfunc()\nfunc()\n\nYou can use python's indentation to help you understand what's going on. Everything that is flush to the left margin is executed when the file gets executed. Everything that's indented is compiled into a code object which gets executed when func() is called. So the function is defined and its default arguments set once, when the program gets executed (because the def statement is flush left). \nWhat it does with the default arguments is an interesting issue. In python 3, it puts most of the information about a function in two places: func.__code__ and func.__defaults__. In python 2, func.__code__ was func.func_code func.__defaults__ was func.func_defaults. Later versions of python 2, including 2.6 have both sets of names, to aid the transition from python 2 to python 3. I will use the more modern __code__ and __defaults__. If you're stuck on an older python, the concepts are the same; just the names differ. \nThe default values are stored in func.__defaults__, and retrieved each time the function is called. \nThus when you define the function above, the body of the function gets compiled and stored in variables under __code__, to be executed later, and the default arguments get stored in __defaults__. When you call the function, it uses the values in __defaults__. If those values get modified for any reason, it only has the modified version available to use. \nPlay around defining different functions in the interactive interpreter, and see what you can figure out about how python creates and uses functions.\n",
"The explaination is given in answers to this question. To sum it up here:\nFunctions in Python are a kind of object. Because they are a kind of object, they act like objects when instantiated. A function, if defined with a mutable attribute as a default argument, is exactly the same as a class with a static attribute that is a mutable list.\nLennart Regebro has a good explanation and the answer to the question by Roberto Liffredo is excellent.\nTo adapt Lennart's answer ... if I have a BananaBunch class:\nclass BananaBunch:\n bananas = []\n\n def addBanana(self, banana):\n self.bananas.append(banana)\n\n\nbunch = BananaBunch()\n>>> bunch\n<__main__.BananaBunch instance at 0x011A7FA8>\n>>> bunch.addBanana(1)\n>>> bunch.bananas\n[1]\n>>> for i in range(6):\n bunch.addBanana(\"Banana #\" + i)\n>>> for i in range(6):\n bunch.addBanana(\"Banana #\" + str(i))\n\n>>> bunch.bananas\n[1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5']\n\n// And for review ... \n//If I then add something to the BananaBunch class ...\n>>> BananaBunch.bananas.append(\"A mutated banana\")\n\n//My own bunch is suddenly corrupted. :-)\n>>> bunch.bananas\n[1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5', 'A mutated banana']\n\nHow does this apply to functions? Functions in Python are objects. This bears repeating. Functions in Python are objects. \nSo when you create a function, you are creating an object. When you give a function a mutable default value, you are populating that object's attribute with a mutable value, and every time you call that function you are operating on the same attribute. So if you are using a mutable call (like append), then you are modifying the same object, just as if you were adding bananas to the bunch object.\n",
"The \"problem\" here is that L=[] is only evaluated once, that is, when the file is compiled. Python steps through each line of the file and compiles it. By the time it reaches the def with the default parameter, it creates that list instance once.\nIf you put L = [] inside the function code, the instance is not created at \"compile time\" (actually compile time can also be called part of the run time) because Python compiles the function's code but does not call it. So you will get a new list instance because the creation is done every time you call the function (instead of once during compilation).\nA solution for that problem is not to use mutable objects as default parameters, or only fixed instances like None:\ndef f(a, L = None):\n if l == None:\n l = []\n L.append(a)\n return L\n\nNote that in both cases you described, the scope of L is the function scope.\n"
] |
[
25,
7,
3,
2,
1,
0
] |
[
"You have to keep in mind that python is an interpreted language. What is happening here is when the function \"f\" is defined, it creates the list and assigns it to the default parameter \"L\" of function \"f\". Later, when you call this function, the same list is used as the default parameter. In short, the code on the \"def\" line, only gets executed once when the function is defined. This is a common python pitfall, of which I have fallen in myself.\ndef f(a, L=[]):\n L.append(a)\n return L\n\nprint f(1)\nprint f(2)\nprint f(3)\n\nThere have been suggestions for idioms in other answers here to fix this issue. The one I would suggest is as follows:\ndef f(a, L=None):\n L = L or []\n L.append(a)\n return L\n\nThis uses the or short circuit to either take the \"L\" that was passed, or create a new list.\nThe answer to your scope question is the \"L\" only has a scope within the function \"f\", but because the default parameters are only assigned once to a single list instead of every time you call the function it behaves as if the default parameter \"L\" has a global scope.\n"
] |
[
-1
] |
[
"default_value",
"function_calls",
"parameters",
"python",
"scope"
] |
stackoverflow_0002335160_default_value_function_calls_parameters_python_scope.txt
|
Q:
How can I get the window focused on Windows and re-size it?
I want to get the focused window so I can resize it... how can I do it?
A:
Use the GetForegroundWindow Win32 API to get the window handle.
Then use the MoveWindow (or SetWindowPos if you prefer) win32 API to resize the window.
Working with the Win32 API can be done directly with ctypes and working with the dlls or by using the pywin32 project.
Edit: Sure here is an example (Make sure you have pywin32 installed):
import win32gui
hwnd = win32gui.GetForegroundWindow()
win32gui.MoveWindow(hwnd, 0, 0, 500, 500, True)
|
How can I get the window focused on Windows and re-size it?
|
I want to get the focused window so I can resize it... how can I do it?
|
[
"Use the GetForegroundWindow Win32 API to get the window handle.\nThen use the MoveWindow (or SetWindowPos if you prefer) win32 API to resize the window.\nWorking with the Win32 API can be done directly with ctypes and working with the dlls or by using the pywin32 project.\nEdit: Sure here is an example (Make sure you have pywin32 installed):\nimport win32gui\nhwnd = win32gui.GetForegroundWindow()\nwin32gui.MoveWindow(hwnd, 0, 0, 500, 500, True)\n\n"
] |
[
17
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0002335721_python_windows.txt
|
Q:
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted?
Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.
Corrupted, to me, is the image is loaded into Firefox and it says
The image “such and such image” cannot be displayed, because it contains errors.
Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.
Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?
I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.
A:
An easy way would be to try loading and verifying the files with PIL (Python Imaging Library).
from PIL import Image
v_image = Image.open(file)
v_image.verify()
Catch the exceptions...
From the documentation:
im.verify()
Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file.
A:
i suggest you check out imagemagick for this: http://www.imagemagick.org/
there you have a tool called identify which you can either use in combination with a script/stdout or you can use the programming interface provided
A:
In PHP, with exif_imagetype():
if (exif_imagetype($filename) === false)
{
unlink($filename); // image is corrupted
}
EDIT: Or you can try to fully load the image with ImageCreateFromString():
if (ImageCreateFromString(file_get_contents($filename)) === false)
{
unlink($filename); // image is corrupted
}
An image resource will be returned on
success. FALSE is returned if the
image type is unsupported, the data is
not in a recognized format, or the
image is corrupt and cannot be loaded.
A:
If your exact requirements are that it show correctly in FireFox you may have a difficult time - the only way to be sure would be to link to the exact same image loading source code as FireFox.
Basic image corruption (file is incomplete) can be detected simply by trying to open the file using any number of image libraries.
However many images can fail to display simply because they stretch a part of the file format that the particular viewer you are using can't handle (GIF in particular has a lot of these edge cases, but you can find JPEG and the rare PNG file that can only be displayed in specific viewers). There are also some ugly JPEG edge cases where the file appears to be uncorrupted in viewer X, but in reality the file has been cut short and is only displaying correctly because very little information has been lost (FireFox can show some cut off JPEGs correctly [you get a grey bottom], but others result in FireFox seeming the load them half way and then display the error message instead of the partial image)
A:
You could use imagemagick if it is available:
if you want to do a whole folder
identify "./myfolder/*" >log.txt 2>&1
if you want to just check a file:
identify myfile.jpg
|
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted?
|
Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.
Corrupted, to me, is the image is loaded into Firefox and it says
The image “such and such image” cannot be displayed, because it contains errors.
Now, I could select all of my 250,000 images (~150gb) and drag-n-drop them into Firefox. That would be bad though, because I don't think Mozilla designed Firefox to open 250,000 tabs. No, I need a way to programmatically check whether an image is corrupted.
Does anyone know a PHP or Python library which can do something along these lines? Or an existing piece of software for Windows?
I have already removed obviously corrupted images (such as ones that are 0 bytes) but I'm about 99.9% sure that there are more diseased images floating around in my throng of a collection.
|
[
"An easy way would be to try loading and verifying the files with PIL (Python Imaging Library).\nfrom PIL import Image\n\nv_image = Image.open(file)\nv_image.verify()\n\nCatch the exceptions...\nFrom the documentation:\nim.verify()\nAttempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file.\n",
"i suggest you check out imagemagick for this: http://www.imagemagick.org/\nthere you have a tool called identify which you can either use in combination with a script/stdout or you can use the programming interface provided\n",
"In PHP, with exif_imagetype():\nif (exif_imagetype($filename) === false)\n{\n unlink($filename); // image is corrupted\n}\n\nEDIT: Or you can try to fully load the image with ImageCreateFromString():\nif (ImageCreateFromString(file_get_contents($filename)) === false)\n{\n unlink($filename); // image is corrupted\n}\n\n\nAn image resource will be returned on\n success. FALSE is returned if the\n image type is unsupported, the data is\n not in a recognized format, or the\n image is corrupt and cannot be loaded.\n\n",
"If your exact requirements are that it show correctly in FireFox you may have a difficult time - the only way to be sure would be to link to the exact same image loading source code as FireFox.\nBasic image corruption (file is incomplete) can be detected simply by trying to open the file using any number of image libraries.\nHowever many images can fail to display simply because they stretch a part of the file format that the particular viewer you are using can't handle (GIF in particular has a lot of these edge cases, but you can find JPEG and the rare PNG file that can only be displayed in specific viewers). There are also some ugly JPEG edge cases where the file appears to be uncorrupted in viewer X, but in reality the file has been cut short and is only displaying correctly because very little information has been lost (FireFox can show some cut off JPEGs correctly [you get a grey bottom], but others result in FireFox seeming the load them half way and then display the error message instead of the partial image)\n",
"You could use imagemagick if it is available:\nif you want to do a whole folder\nidentify \"./myfolder/*\" >log.txt 2>&1\n\nif you want to just check a file:\nidentify myfile.jpg\n\n"
] |
[
27,
7,
5,
3,
0
] |
[] |
[] |
[
"image",
"php",
"python"
] |
stackoverflow_0001401527_image_php_python.txt
|
Q:
Convert dbus.String to normal string
I am using dbus to get the current playing song from Songbird Media Player & Metadata is also taken from dbus object.
The line where error comes is:-
audio_file = MP3(current_playing_track['location'], ID3=ID3)
The error is:-
Traceback (most recent call last):
File "./last.py", line 42, in <module>
audio_file = MP3(current_playing_track['location'], ID3=ID3)
File "/usr/lib/python2.6/dist-packages/mutagen/__init__.py", line 73, in __init__
self.load(filename, *args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/id3.py", line 1949, in load
try: self.tags = ID3(filename, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/id3.py", line 74, in __init__
super(ID3, self).__init__(*args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/_util.py", line 103, in __init__
super(DictProxy, self).__init__(*args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/__init__.py", line 37, in __init__
self.load(*args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/id3.py", line 109, in load
self.__fileobj = file(filename, 'rb')
IOError: [Errno 2] No such file or directory: dbus.String(u'file:///media/Misc/Songbird%20Library/Puddle%20Of%20Mudd/Puddle%20Of%20Mudd%20-%20Unknown%20Album%20-%20Spin%20You%20Around.mp3', variant_level=1)
How do I convert file location to a normal string?
A:
Just do str( your_dbus_string )
|
Convert dbus.String to normal string
|
I am using dbus to get the current playing song from Songbird Media Player & Metadata is also taken from dbus object.
The line where error comes is:-
audio_file = MP3(current_playing_track['location'], ID3=ID3)
The error is:-
Traceback (most recent call last):
File "./last.py", line 42, in <module>
audio_file = MP3(current_playing_track['location'], ID3=ID3)
File "/usr/lib/python2.6/dist-packages/mutagen/__init__.py", line 73, in __init__
self.load(filename, *args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/id3.py", line 1949, in load
try: self.tags = ID3(filename, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/id3.py", line 74, in __init__
super(ID3, self).__init__(*args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/_util.py", line 103, in __init__
super(DictProxy, self).__init__(*args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/__init__.py", line 37, in __init__
self.load(*args, **kwargs)
File "/usr/lib/python2.6/dist-packages/mutagen/id3.py", line 109, in load
self.__fileobj = file(filename, 'rb')
IOError: [Errno 2] No such file or directory: dbus.String(u'file:///media/Misc/Songbird%20Library/Puddle%20Of%20Mudd/Puddle%20Of%20Mudd%20-%20Unknown%20Album%20-%20Spin%20You%20Around.mp3', variant_level=1)
How do I convert file location to a normal string?
|
[
"Just do str( your_dbus_string )\n"
] |
[
7
] |
[] |
[] |
[
"dbus",
"python",
"string"
] |
stackoverflow_0002336127_dbus_python_string.txt
|
Q:
pylint seems to not handle "from . import foo" style imports
If I do:
from . import foo
In a script and run pylint over it, I get:
F: 1: Unable to import %r
Is there a way a work around for getting pylint to understand this syntax?
A:
Update to at least pylint 0.18.1 / logilab-astng 0.19.1?
A:
Note that the "from . import smthg" is only allowed in a Python package.
I've tested this with
pylint --version
No config file found, using default configuration
pylint 0.19.0,
astng 0.19.1, common 0.46.0
Python 2.5.5 (r255:77872, Feb 1 2010, 19:53:42)
[GCC 4.4.3]
and was not able to reproduce your problem:
alf@lacapelle:/tmp$ ls package/
foo.py __init__.py relative.py
alf@lacapelle:/tmp$ cat package/relative.py
from . import foo
alf@lacapelle:/tmp$ pylint -r n package/
No config file found, using default configuration
************* Module package
C: 1: Missing docstring
************* Module package.foo
C: 1: Black listed name "foo"
C: 1: Missing docstring
************* Module package.relative
C: 1: Missing docstring
W: 1: Unused import foo
|
pylint seems to not handle "from . import foo" style imports
|
If I do:
from . import foo
In a script and run pylint over it, I get:
F: 1: Unable to import %r
Is there a way a work around for getting pylint to understand this syntax?
|
[
"Update to at least pylint 0.18.1 / logilab-astng 0.19.1?\n",
"Note that the \"from . import smthg\" is only allowed in a Python package. \nI've tested this with \npylint --version\nNo config file found, using default configuration\npylint 0.19.0, \nastng 0.19.1, common 0.46.0\nPython 2.5.5 (r255:77872, Feb 1 2010, 19:53:42) \n[GCC 4.4.3]\n\nand was not able to reproduce your problem:\nalf@lacapelle:/tmp$ ls package/\nfoo.py __init__.py relative.py\nalf@lacapelle:/tmp$ cat package/relative.py \nfrom . import foo\n\nalf@lacapelle:/tmp$ pylint -r n package/\nNo config file found, using default configuration\n************* Module package\nC: 1: Missing docstring\n************* Module package.foo\nC: 1: Black listed name \"foo\"\nC: 1: Missing docstring\n************* Module package.relative\nC: 1: Missing docstring\nW: 1: Unused import foo\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"import",
"pylint",
"python"
] |
stackoverflow_0002142810_import_pylint_python.txt
|
Q:
How does pylint quit the Windows command box it is running in?
Pylint is doing something odd on my Windows box - something that shouldn't be possible. This isn't a question about fixing pylint, so much as fixing my understanding.
I have a typical install of the latest version of pylint, Python 2.6 and Windows Vista.
If I open a Command Prompt, and run pylint from the command line, it executes successfully, then when it gets to the end of the program, it doesn't merely exit to the command line again, but closes the entire Command Prompt window.
I had a brief look at the code online (which I assume is the code that is actually being run) and they are calling sys.exit() with various error levels, but my reading and testing suggests that should still just return to the command line with the appropriate error-level set.
Pylint is also run as part of my project's testing regime, and it works there, suggesting to me that if it is called as a Python method rather from the command-line, it doesn't have the same problem (probably no call to sys.exit() in this code path.)
By what mechanism could pylint close the "shell" that contained it?
If this a bug in Pylint? I don't see how. A bug in Python? A bug in Windows?
A:
I just tried this on XP:
t.bat:
exit
Running this closes the window!
Maybe the command line for pylint uses a batch file which contains an exit?
A:
This is a very easy fix. Go into your python scripts folder and locate pylint.bat and open it in notepad.
It will read the following
@echo off
rem = """-*-Python-*- script
rem -------------------- DOS section --------------------
rem You could set PYTHONPATH or TK environment variables here
python -x "%~f0" %*
goto exit
"""
# -------------------- Python section --------------------
import sys
from pylint import lint
lint.Run(sys.argv[1:])
DosExitLabel = """
:exit
exit(ERRORLEVEL)
rem """
To fix the issue at hand of the prompt closing change it to the following
@echo off
rem = """-*-Python-*- script
rem -------------------- DOS section --------------------
rem You could set PYTHONPATH or TK environment variables here
python -x "%~f0" %*
goto exit
"""
# -------------------- Python section --------------------
import sys
from pylint import lint
lint.Run(sys.argv[1:])
DosExitLabel = """
:exit
ECHO.
rem exit(ERRORLEVEL)
rem """
Basically all I did was comment out the exit(ERRORLEVEL) with "rem" keyword then before it goes back to the prompt I added in a blank line print with "ECHO." so that the prompt does not get skewed in with the output.
A:
This is http://www.logilab.org/ticket/19498 scheduled for 0.20.0 (currently under development).
|
How does pylint quit the Windows command box it is running in?
|
Pylint is doing something odd on my Windows box - something that shouldn't be possible. This isn't a question about fixing pylint, so much as fixing my understanding.
I have a typical install of the latest version of pylint, Python 2.6 and Windows Vista.
If I open a Command Prompt, and run pylint from the command line, it executes successfully, then when it gets to the end of the program, it doesn't merely exit to the command line again, but closes the entire Command Prompt window.
I had a brief look at the code online (which I assume is the code that is actually being run) and they are calling sys.exit() with various error levels, but my reading and testing suggests that should still just return to the command line with the appropriate error-level set.
Pylint is also run as part of my project's testing regime, and it works there, suggesting to me that if it is called as a Python method rather from the command-line, it doesn't have the same problem (probably no call to sys.exit() in this code path.)
By what mechanism could pylint close the "shell" that contained it?
If this a bug in Pylint? I don't see how. A bug in Python? A bug in Windows?
|
[
"I just tried this on XP:\nt.bat:\n\nexit\n\nRunning this closes the window!\nMaybe the command line for pylint uses a batch file which contains an exit?\n",
"This is a very easy fix. Go into your python scripts folder and locate pylint.bat and open it in notepad.\nIt will read the following\n@echo off\nrem = \"\"\"-*-Python-*- script\nrem -------------------- DOS section --------------------\nrem You could set PYTHONPATH or TK environment variables here\npython -x \"%~f0\" %*\ngoto exit\n\n\"\"\"\n# -------------------- Python section --------------------\nimport sys\nfrom pylint import lint\nlint.Run(sys.argv[1:])\n\n\nDosExitLabel = \"\"\"\n:exit\nexit(ERRORLEVEL)\nrem \"\"\"\nTo fix the issue at hand of the prompt closing change it to the following\n@echo off\nrem = \"\"\"-*-Python-*- script\nrem -------------------- DOS section --------------------\nrem You could set PYTHONPATH or TK environment variables here\npython -x \"%~f0\" %*\ngoto exit\n\n\"\"\"\n# -------------------- Python section --------------------\nimport sys\nfrom pylint import lint\nlint.Run(sys.argv[1:])\n\n\nDosExitLabel = \"\"\"\n:exit\nECHO.\nrem exit(ERRORLEVEL)\nrem \"\"\"\nBasically all I did was comment out the exit(ERRORLEVEL) with \"rem\" keyword then before it goes back to the prompt I added in a blank line print with \"ECHO.\" so that the prompt does not get skewed in with the output.\n",
"This is http://www.logilab.org/ticket/19498 scheduled for 0.20.0 (currently under development). \n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"command_line",
"errorlevel",
"pylint",
"python",
"windows_vista"
] |
stackoverflow_0001719898_command_line_errorlevel_pylint_python_windows_vista.txt
|
Q:
Parse timezone abbreviation to UTC
How can I convert a date time string of the form Feb 25 2010, 16:19:20 CET to the unix epoch?
Currently my best approach is to use time.strptime() is this:
def to_unixepoch(s):
# ignore the time zone in strptime
a = s.split()
b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z")
# this puts the time_tuple(UTC+TZ) to unixepoch(UTC+TZ+LOCALTIME)
c = int(time.mktime(b))
# UTC+TZ
c -= time.timezone
# UTC
c -= {"CET": 3600, "CEST": 2 * 3600}[a[-1]]
return c
I see from other questions that it might be possible to use calendar.timegm(), and pytz among others to simplify this, but these don't handle the abbreviated time zones.
I'd like a solution that requires minimal excess libraries, I like to keep to the standard library as much as possible.
A:
The Python standard library does not really implement time zones. You should use python-dateutil. It provides useful extensions to the standard datetime module including a time zones implementation and a parser.
You can convert time zone aware datetime objects to UTC with .astimezone(dateutil.tz.tzutc()). For the current time as a timezone aware datetime object, you can use datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()).
import dateutil.tz
cet = dateutil.tz.gettz('CET')
cesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet)
cesttime.isoformat()
'2010-04-01T12:57:00+02:00'
cettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet)
cettime.isoformat()
'2010-01-01T12:57:00+01:00'
# does not automatically parse the time zone portion
dateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\
.replace(tzinfo=dateutil.tz.gettz('CET'))
Unfortunately this technique will be wrong during the repeated daylight savings time hour.
|
Parse timezone abbreviation to UTC
|
How can I convert a date time string of the form Feb 25 2010, 16:19:20 CET to the unix epoch?
Currently my best approach is to use time.strptime() is this:
def to_unixepoch(s):
# ignore the time zone in strptime
a = s.split()
b = time.strptime(" ".join(a[:-1]) + " UTC", "%b %d %Y, %H:%M:%S %Z")
# this puts the time_tuple(UTC+TZ) to unixepoch(UTC+TZ+LOCALTIME)
c = int(time.mktime(b))
# UTC+TZ
c -= time.timezone
# UTC
c -= {"CET": 3600, "CEST": 2 * 3600}[a[-1]]
return c
I see from other questions that it might be possible to use calendar.timegm(), and pytz among others to simplify this, but these don't handle the abbreviated time zones.
I'd like a solution that requires minimal excess libraries, I like to keep to the standard library as much as possible.
|
[
"The Python standard library does not really implement time zones. You should use python-dateutil. It provides useful extensions to the standard datetime module including a time zones implementation and a parser.\nYou can convert time zone aware datetime objects to UTC with .astimezone(dateutil.tz.tzutc()). For the current time as a timezone aware datetime object, you can use datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()).\nimport dateutil.tz\n\ncet = dateutil.tz.gettz('CET')\n\ncesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet)\ncesttime.isoformat()\n'2010-04-01T12:57:00+02:00'\n\ncettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet)\ncettime.isoformat() \n'2010-01-01T12:57:00+01:00'\n\n# does not automatically parse the time zone portion\ndateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\\\n .replace(tzinfo=dateutil.tz.gettz('CET'))\n\nUnfortunately this technique will be wrong during the repeated daylight savings time hour.\n"
] |
[
7
] |
[] |
[] |
[
"datetime",
"python",
"pytz",
"time",
"timezone"
] |
stackoverflow_0002335405_datetime_python_pytz_time_timezone.txt
|
Q:
Tcl/Tk Tkinter version 8.4 and 8.5 conflict on Mac Os X 10.4.11 with python 2.6.4
I am having trouble getting Tkinter up and runnning in order to install matplot lib.
I am running Mac OS X 10.4.11, and just installed Python 2.6.4 .
After several other fights, one remaining battle for me to get matlotlib installed is to have a working version of Tkinter, although there are several in my Mac from Xcode and also Python, I guess they just aren't installed in useful places? After I installed Python 2.6.4, import _tkinter failed. So I installed Tcl 8.5 from active state.
Now, I make it to the Tkinter test:
Tkinter._test()
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 3746, in _test
root = Tk()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1645, in init
self._loadtk()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1659, in _loadtk
% (_tkinter.TK_VERSION, tk_version)
RuntimeError: tk.h version (8.4) doesn't match libtk.a version (8.5)
I realize you have discussed the exact error I am describing here:
http://bugs.python.org/issue4017
but those errors arose from a problem with an earlier version of python, where setup.py reversed the order of where to look. The advice in your previous post is to fix this order in setup.py and rebuild python, but my setup.py is already looking good - it includes these lines:
def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
# The _tkinter module, using frameworks. Since frameworks are quite
# different the UNIX search logic is not sharable.
from os.path import join, exists
framework_dirs = [
'/Library/Frameworks',
'/System/Library/Frameworks/',
join(os.getenv('HOME'), '/Library/Frameworks')
I would really appreciate any insight on how to handle this!( I am a biologist...)
While I'm at it, I'll include what is going on when I try to install m matplotlib in case it is useful...matplotlib thinks I have Tkinter 8.4 (ironically, only afeter I installed 8.5, before that it always said it could not find Tkinter):
Tkinter: Tkinter: 65971, Tk: 8.4, Tcl: 8.4
also, here is the error I run into when trying to build matplotlib:
powerpc-apple-darwin8-g++-4.0.1: unrecognized option '-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk'
i686-apple-darwin8-g++-4.0.1: unrecognized option '-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk'
/usr/bin/ld: -syslibroot: multiply specified
collect2: ld returned 1 exit status
/usr/bin/ld: -syslibroot: multiply specified
collect2: ld returned 1 exit status
lipo: can't open input file: /var/tmp//ccrblCgU.out (No such file or directory)
error: command 'g++' failed with exit status 1
make: *** [mpl_build] Error 1
thank you!!
Katrine
A:
I think the important point from previous solutions proposed was that Python, upon install, detects the correct version and location of Tk. I assume you installed Tk after installing Python. This problem was solved on my machine when I reinstalled Python2.6 using the .dmg installer. I didn't need to rebuild or anything. I hope this helps. :)
|
Tcl/Tk Tkinter version 8.4 and 8.5 conflict on Mac Os X 10.4.11 with python 2.6.4
|
I am having trouble getting Tkinter up and runnning in order to install matplot lib.
I am running Mac OS X 10.4.11, and just installed Python 2.6.4 .
After several other fights, one remaining battle for me to get matlotlib installed is to have a working version of Tkinter, although there are several in my Mac from Xcode and also Python, I guess they just aren't installed in useful places? After I installed Python 2.6.4, import _tkinter failed. So I installed Tcl 8.5 from active state.
Now, I make it to the Tkinter test:
Tkinter._test()
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 3746, in _test
root = Tk()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1645, in init
self._loadtk()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 1659, in _loadtk
% (_tkinter.TK_VERSION, tk_version)
RuntimeError: tk.h version (8.4) doesn't match libtk.a version (8.5)
I realize you have discussed the exact error I am describing here:
http://bugs.python.org/issue4017
but those errors arose from a problem with an earlier version of python, where setup.py reversed the order of where to look. The advice in your previous post is to fix this order in setup.py and rebuild python, but my setup.py is already looking good - it includes these lines:
def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
# The _tkinter module, using frameworks. Since frameworks are quite
# different the UNIX search logic is not sharable.
from os.path import join, exists
framework_dirs = [
'/Library/Frameworks',
'/System/Library/Frameworks/',
join(os.getenv('HOME'), '/Library/Frameworks')
I would really appreciate any insight on how to handle this!( I am a biologist...)
While I'm at it, I'll include what is going on when I try to install m matplotlib in case it is useful...matplotlib thinks I have Tkinter 8.4 (ironically, only afeter I installed 8.5, before that it always said it could not find Tkinter):
Tkinter: Tkinter: 65971, Tk: 8.4, Tcl: 8.4
also, here is the error I run into when trying to build matplotlib:
powerpc-apple-darwin8-g++-4.0.1: unrecognized option '-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk'
i686-apple-darwin8-g++-4.0.1: unrecognized option '-syslibroot,/Developer/SDKs/MacOSX10.4u.sdk'
/usr/bin/ld: -syslibroot: multiply specified
collect2: ld returned 1 exit status
/usr/bin/ld: -syslibroot: multiply specified
collect2: ld returned 1 exit status
lipo: can't open input file: /var/tmp//ccrblCgU.out (No such file or directory)
error: command 'g++' failed with exit status 1
make: *** [mpl_build] Error 1
thank you!!
Katrine
|
[
"I think the important point from previous solutions proposed was that Python, upon install, detects the correct version and location of Tk. I assume you installed Tk after installing Python. This problem was solved on my machine when I reinstalled Python2.6 using the .dmg installer. I didn't need to rebuild or anything. I hope this helps. :)\n"
] |
[
2
] |
[] |
[] |
[
"macos",
"python",
"tk_toolkit",
"tkinter"
] |
stackoverflow_0002247971_macos_python_tk_toolkit_tkinter.txt
|
Q:
How do I make a command line program that takes arguments?
How can I make a command line, so I can execute my program on Windows with some parameters...
For example:
C:/Program/App.exe -safemode
A:
have a look at the getopt and optparse modules from the standard lib, many good things could be also said about more advanced argparse module.
Generally you just need to access sys.argv.
A:
I sense that you also want to generate an 'executable' that you can run standalone.... For that you use py2exe
Here is a complete example.py:
import optparse
parser = optparse.OptionParser()
parser.add_option("-s", "--safemode",
default = False,
action = "store_true",
help = "Should program run in safe mode?")
parser.add_option("-w", "--width",
type = "int",
default = 1024,
help = "Desired screen width in pixels")
options, arguments = parser.parse_args()
if options.safemode:
print "Proceeding safely"
else:
print "Proceeding dangerously"
if options.width == 1024:
print "running in 1024-pixel mode"
elif options.width == 1920:
print "running in 1920-pixel mode"
And here is a complete setup.py that will turn the above example.py into example.exe (in the dist subdirectory):
from distutils.core import setup
import py2exe
import sys
sys.argv.append('py2exe')
setup(
options = {'py2exe': dict(bundle_files=1, optimize=2)},
console = ["example.py"],
zipfile = None,
)
A:
Are you speaking about parameter passed to a python script?
'couse you can access them by
import sys
print sys.argv
Or can use a more sophisticated getopt module.
A:
Not a python guy (yet anyway) but my Google-fu found this assuming you meant "handling command line arguments":
http://www.faqs.org/docs/diveintopython/kgp_commandline.html
A:
Use optparse.OptionParser.
from optparse import OptionParser
import sys
def make_cli_parser():
"""Makes the parser for the command line interface."""
usage = "python %prog [OPTIONS]"
cli_parser = OptionParser(usage)
cli_parser.add_option('-s', '--safemode', action='store_true',
help="Run in safe mode")
return cli_parser
def main(argv):
cli_parser = make_cli_parser()
opts, args = cli_parser.parse_args(argv)
if opts.safemode:
print "Running in safe mode."
else:
print "Running with the devil."
if __name__ == '__main__':
main(sys.argv[1:])
In use:
$ python opt.py
Running with the devil.
$ python opt.py -s
Running in safe mode.
$ python opt.py -h
Usage: python opt.py [OPTIONS]
Options:
-h, --help show this help message and exit
-s, --safemode Run in safe mode
A:
Or are you just asking how to open a command line?
go to the start menu, click "run" (or just type, in Windows 7), type "cmd"
This will open up a command shell.
Given that your question is tagged python, I'm not sure it's going to be compiled into an exe, you might have to type "python (your source here).py -safemode".
A:
The other comments addressed how to handle parameters. If you want to make your python program an exe you might want to look at py2exe.
This is not required but you mentioned App.exe and not App.py
A:
You are asking a question that has several levels of answers.
First, command line is passed into the array sys.argv. argv is a historic name from C and Unix languages. So:
~/p$ cat > args.py
import sys
print "You have ", len(sys.argv), "arguments."
for i in range(len(sys.argv)):
print "argv[", i, "] = ", sys.argv[i]
~/p$ python args.py 34 2 2 2
You have 5 arguments.
argv[ 0 ] = args.py
argv[ 1 ] = 34
argv[ 2 ] = 2
argv[ 3 ] = 2
argv[ 4 ] = 2
This works both in MS Windows and Unix.
Second, you might be asking "How do I get nice arguments? Have it handle /help in
MS Windows or --help in Linux?"
Well, there are three choices which try to do what you want. Two, optparse and getopt are already in the standard library, while argparse is on its way. All three of these are libraries that start with the sys.argv array of strings, a description of you command line arguments, and return some sort of data structure or class from which
you can get the options you mean.
getopt does the minimal job. It does not provide "/help" or "--help".
optparse does a more detailed job. It provides "/help" and both short and long
versions of options, e.g., "-v" and "--verbose".
argparse handles the kitchen sink, including "/help", short and long commands,
and also subcommand structures, as you see in source control "git add ....", and
positional arguments.
As you move to the richer parsing, you need to give the parser more details about what you want the command line arguments to be. For example, you need to pass a long written
description of the argument if you want the --help argument to print it.
Third, you might be asking for a tool that just deals with the options from the command
line, environment variables and configuration files. Python currently has separate tools
for each of these. Perhaps I'll write a unified one, You will need:
- Command line arguments parsed by argparse, or getopt, etc.
- Environment variables, from os.environ[]
- Configuration files from ConfigFile or plistlib, etc.
and build your own answer to "what are the settings"?
Hope this fully answers your questions
A:
One of the many ways:
import sys
print sys.argv
>>>python arg.py arg1 arg2
['arg.py', 'arg1', 'arg2']
sys.argv is a list containing all the arguments (also the name of script/program) as string.
|
How do I make a command line program that takes arguments?
|
How can I make a command line, so I can execute my program on Windows with some parameters...
For example:
C:/Program/App.exe -safemode
|
[
"have a look at the getopt and optparse modules from the standard lib, many good things could be also said about more advanced argparse module.\nGenerally you just need to access sys.argv.\n",
"I sense that you also want to generate an 'executable' that you can run standalone.... For that you use py2exe\nHere is a complete example.py:\nimport optparse\n\nparser = optparse.OptionParser()\n\nparser.add_option(\"-s\", \"--safemode\",\n default = False,\n action = \"store_true\",\n help = \"Should program run in safe mode?\")\n\nparser.add_option(\"-w\", \"--width\",\n type = \"int\",\n default = 1024,\n help = \"Desired screen width in pixels\")\n\noptions, arguments = parser.parse_args()\n\nif options.safemode:\n print \"Proceeding safely\"\nelse:\n print \"Proceeding dangerously\"\n\nif options.width == 1024:\n print \"running in 1024-pixel mode\"\nelif options.width == 1920:\n print \"running in 1920-pixel mode\"\n\nAnd here is a complete setup.py that will turn the above example.py into example.exe (in the dist subdirectory):\nfrom distutils.core import setup\nimport py2exe\nimport sys\n\nsys.argv.append('py2exe')\n\nsetup(\n options = {'py2exe': dict(bundle_files=1, optimize=2)},\n console = [\"example.py\"],\n zipfile = None,\n )\n\n",
"Are you speaking about parameter passed to a python script?\n'couse you can access them by\nimport sys\nprint sys.argv\n\nOr can use a more sophisticated getopt module.\n",
"Not a python guy (yet anyway) but my Google-fu found this assuming you meant \"handling command line arguments\":\nhttp://www.faqs.org/docs/diveintopython/kgp_commandline.html\n",
"Use optparse.OptionParser.\nfrom optparse import OptionParser\nimport sys\n\ndef make_cli_parser():\n \"\"\"Makes the parser for the command line interface.\"\"\"\n usage = \"python %prog [OPTIONS]\"\n cli_parser = OptionParser(usage)\n cli_parser.add_option('-s', '--safemode', action='store_true',\n help=\"Run in safe mode\")\n return cli_parser\n\ndef main(argv):\n cli_parser = make_cli_parser()\n opts, args = cli_parser.parse_args(argv)\n if opts.safemode:\n print \"Running in safe mode.\"\n else:\n print \"Running with the devil.\"\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\nIn use:\n$ python opt.py\nRunning with the devil.\n$ python opt.py -s\nRunning in safe mode.\n$ python opt.py -h\n\nUsage: python opt.py [OPTIONS]\nOptions:\n -h, --help show this help message and exit\n -s, --safemode Run in safe mode\n\n",
"Or are you just asking how to open a command line?\ngo to the start menu, click \"run\" (or just type, in Windows 7), type \"cmd\"\nThis will open up a command shell.\nGiven that your question is tagged python, I'm not sure it's going to be compiled into an exe, you might have to type \"python (your source here).py -safemode\".\n",
"The other comments addressed how to handle parameters. If you want to make your python program an exe you might want to look at py2exe. \nThis is not required but you mentioned App.exe and not App.py\n",
"You are asking a question that has several levels of answers.\nFirst, command line is passed into the array sys.argv. argv is a historic name from C and Unix languages. So:\n~/p$ cat > args.py\nimport sys\nprint \"You have \", len(sys.argv), \"arguments.\"\nfor i in range(len(sys.argv)):\nprint \"argv[\", i, \"] = \", sys.argv[i]\n\n~/p$ python args.py 34 2 2 2\nYou have 5 arguments.\nargv[ 0 ] = args.py\nargv[ 1 ] = 34\nargv[ 2 ] = 2\nargv[ 3 ] = 2\nargv[ 4 ] = 2\n\nThis works both in MS Windows and Unix.\nSecond, you might be asking \"How do I get nice arguments? Have it handle /help in \nMS Windows or --help in Linux?\"\nWell, there are three choices which try to do what you want. Two, optparse and getopt are already in the standard library, while argparse is on its way. All three of these are libraries that start with the sys.argv array of strings, a description of you command line arguments, and return some sort of data structure or class from which\nyou can get the options you mean. \n\ngetopt does the minimal job. It does not provide \"/help\" or \"--help\".\noptparse does a more detailed job. It provides \"/help\" and both short and long\nversions of options, e.g., \"-v\" and \"--verbose\".\nargparse handles the kitchen sink, including \"/help\", short and long commands,\nand also subcommand structures, as you see in source control \"git add ....\", and\npositional arguments.\n\nAs you move to the richer parsing, you need to give the parser more details about what you want the command line arguments to be. For example, you need to pass a long written\ndescription of the argument if you want the --help argument to print it.\nThird, you might be asking for a tool that just deals with the options from the command \nline, environment variables and configuration files. Python currently has separate tools\nfor each of these. Perhaps I'll write a unified one, You will need:\n - Command line arguments parsed by argparse, or getopt, etc.\n - Environment variables, from os.environ[]\n - Configuration files from ConfigFile or plistlib, etc.\nand build your own answer to \"what are the settings\"?\nHope this fully answers your questions\n",
"One of the many ways:\nimport sys\nprint sys.argv\n\n\n>>>python arg.py arg1 arg2\n['arg.py', 'arg1', 'arg2']\n\n\n\nsys.argv is a list containing all the arguments (also the name of script/program) as string.\n"
] |
[
9,
7,
3,
2,
2,
0,
0,
0,
0
] |
[] |
[] |
[
"command_line",
"python",
"windows"
] |
stackoverflow_0002335989_command_line_python_windows.txt
|
Q:
Customizing the language-guessing algorithm in Django
I'm developing a multilingual Django website. It has two languages, English and Hebrew. I want the default language for every first-time visitor to be Hebrew, regardless of what his browser's Accept-Language is.
Of course, if he changes language to English (and thus gets the language cookie or the key in the session), it should remain at English.
I think I can program this algorithm myself, but where do I "plug it in"? How do I make my project use it?
A:
Start by reading this: http://docs.djangoproject.com/en/1.1/topics/i18n/#topics-i18n
Then read this: http://docs.djangoproject.com/en/1.1/topics/i18n/internationalization/#topics-i18n-internationalization
Each RequestContext has access to
three translation-specific variables:
LANGUAGES is a list of tuples in which
the first element is the language code
and the second is the language name
(translated into the currently active
locale).
LANGUAGE_CODE is the current
user's preferred language, as a
string. Example: en-us. (See How
Django discovers language preference.)
LANGUAGE_BIDI is the current locale's
direction. If True, it's a
right-to-left language, e.g.: Hebrew,
Arabic. If False it's a left-to-right
language, e.g.: English, French,
German etc.
If you don't use the
RequestContext extension, you can get
those values with three tags:
Is this what you're asking about?
A:
Maybe you don't have to override anything. You can just check on the first page, (or maybe every page) if the user already has a language cookie and otherwise redirect him to the set_language redirect view. In that way you could force the language to Hebrew.
If the user decides to change back to English, he can do it very easily.
|
Customizing the language-guessing algorithm in Django
|
I'm developing a multilingual Django website. It has two languages, English and Hebrew. I want the default language for every first-time visitor to be Hebrew, regardless of what his browser's Accept-Language is.
Of course, if he changes language to English (and thus gets the language cookie or the key in the session), it should remain at English.
I think I can program this algorithm myself, but where do I "plug it in"? How do I make my project use it?
|
[
"Start by reading this: http://docs.djangoproject.com/en/1.1/topics/i18n/#topics-i18n\nThen read this: http://docs.djangoproject.com/en/1.1/topics/i18n/internationalization/#topics-i18n-internationalization\n\nEach RequestContext has access to\n three translation-specific variables:\nLANGUAGES is a list of tuples in which\n the first element is the language code\n and the second is the language name\n (translated into the currently active\n locale). \nLANGUAGE_CODE is the current\n user's preferred language, as a\n string. Example: en-us. (See How\n Django discovers language preference.)\nLANGUAGE_BIDI is the current locale's\n direction. If True, it's a\n right-to-left language, e.g.: Hebrew,\n Arabic. If False it's a left-to-right\n language, e.g.: English, French,\n German etc. \nIf you don't use the\n RequestContext extension, you can get\n those values with three tags:\n\nIs this what you're asking about?\n",
"Maybe you don't have to override anything. You can just check on the first page, (or maybe every page) if the user already has a language cookie and otherwise redirect him to the set_language redirect view. In that way you could force the language to Hebrew. \nIf the user decides to change back to English, he can do it very easily.\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"django_multilingual",
"python"
] |
stackoverflow_0002334402_django_django_multilingual_python.txt
|
Q:
How to parse a single line csv string without the csv.reader iterator in python?
I have a CSV file that i need to rearrange and renecode. I'd like to run
line = line.decode('windows-1250').encode('utf-8')
on each line before it's parsed and split by the CSV reader. Or I'd like iterate over lines myself run the re-encoding and use just single line parsing form CSV library but with the same reader instance.
Is there a way to do that nicely?
A:
Loop over lines on file can be done this way:
with open('path/to/my/file.csv', 'r') as f:
for line in f:
puts line # here You can convert encoding and save lines
But if You want to convert encoding of a whole file You can also call:
$ iconv -f Windows-1250 -t UTF8 < file.csv > file.csv
Edit: So where the problem is?
with open('path/to/my/file.csv', 'r') as f:
for line in f:
line = line.decode('windows-1250').encode('utf-8')
elements = line.split(",")
A:
Thx, for the answers. The wrapping one gave me an idea:
def reencode(file):
for line in file:
yield line.decode('windows-1250').encode('utf-8')
csv_writer = csv.writer(open(outfilepath,'w'), delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
csv_reader = csv.reader(reencode(open(filepath)), delimiter=";",quotechar='"')
for c in csv_reader:
l = # rearange columns here
csv_writer.writerow(l)
That's exactly what i was going for re-encoding a line just before it's get parsed by the csv_reader.
A:
At the very bottom of the csv documentation is a set of classes (UnicodeReader and UnicodeWriter) that implements Unicode support for csv:
rfile = open('input.csv')
wfile = open('output.csv','w')
csv_reader = UnicodeReader(rfile,encoding='windows-1250')
csv_writer = UnicodeWriter(wfile,encoding='utf-8')
for c in csv_reader:
# process Unicode lines
csv_writer.writerow(c)
rfile.close()
wfile.close()
|
How to parse a single line csv string without the csv.reader iterator in python?
|
I have a CSV file that i need to rearrange and renecode. I'd like to run
line = line.decode('windows-1250').encode('utf-8')
on each line before it's parsed and split by the CSV reader. Or I'd like iterate over lines myself run the re-encoding and use just single line parsing form CSV library but with the same reader instance.
Is there a way to do that nicely?
|
[
"Loop over lines on file can be done this way:\nwith open('path/to/my/file.csv', 'r') as f:\n for line in f:\n puts line # here You can convert encoding and save lines\n\nBut if You want to convert encoding of a whole file You can also call:\n$ iconv -f Windows-1250 -t UTF8 < file.csv > file.csv\n\nEdit: So where the problem is?\nwith open('path/to/my/file.csv', 'r') as f:\n for line in f:\n line = line.decode('windows-1250').encode('utf-8')\n elements = line.split(\",\")\n\n",
"Thx, for the answers. The wrapping one gave me an idea:\ndef reencode(file):\n for line in file:\n yield line.decode('windows-1250').encode('utf-8')\n\ncsv_writer = csv.writer(open(outfilepath,'w'), delimiter=',',quotechar='\"', quoting=csv.QUOTE_MINIMAL)\ncsv_reader = csv.reader(reencode(open(filepath)), delimiter=\";\",quotechar='\"')\nfor c in csv_reader:\n l = # rearange columns here\n csv_writer.writerow(l)\n\nThat's exactly what i was going for re-encoding a line just before it's get parsed by the csv_reader. \n",
"At the very bottom of the csv documentation is a set of classes (UnicodeReader and UnicodeWriter) that implements Unicode support for csv:\nrfile = open('input.csv')\nwfile = open('output.csv','w')\ncsv_reader = UnicodeReader(rfile,encoding='windows-1250')\ncsv_writer = UnicodeWriter(wfile,encoding='utf-8')\nfor c in csv_reader:\n # process Unicode lines\n csv_writer.writerow(c)\nrfile.close()\nwfile.close()\n\n"
] |
[
2,
2,
2
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0002334436_csv_python.txt
|
Q:
What's the best module to access SimpleDB in python?
I'm writing a python script to select, insert, update, and delete data in SimpleDB.
I've been using the simpledb module written by sixapart so far, and it's working pretty well.
I've found one potential bug/feature that is problematic for me when running select queries with "limit", and I'm thinking of trying it with the boto module to see if it works better.
Has anyone used these two modules? Care to offer an opinion on which is better?
Thanks!
A:
I've found boto to be effective and straight forward and I've never had any trouble with queries with limits. Although I've never used the sixapart module.
|
What's the best module to access SimpleDB in python?
|
I'm writing a python script to select, insert, update, and delete data in SimpleDB.
I've been using the simpledb module written by sixapart so far, and it's working pretty well.
I've found one potential bug/feature that is problematic for me when running select queries with "limit", and I'm thinking of trying it with the boto module to see if it works better.
Has anyone used these two modules? Care to offer an opinion on which is better?
Thanks!
|
[
"I've found boto to be effective and straight forward and I've never had any trouble with queries with limits. Although I've never used the sixapart module. \n"
] |
[
3
] |
[] |
[] |
[
"amazon_simpledb",
"python"
] |
stackoverflow_0002336822_amazon_simpledb_python.txt
|
Q:
Is it possible to read Fortran formatted data in Python?
I get output files from very old Fortran programs, which look like:
0.81667E+00 -0.12650E+01 -0.69389E-03
0.94381E+00 -0.11985E+01 -0.11502E+00
0.96064E+00 -0.11333E+01 -0.17616E+00
0.10202E+01 -0.12435E+01 -0.93917E-01
0.10026E+01 -0.10904E+01 -0.15108E+00
0.90516E+00 -0.11030E+01 -0.19139E+00
0.98624E+00 -0.11598E+01 -0.22970E+00
Is it possible to read this in Python and convert the numbers to "normal" floats?
A:
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> float('-0.69389E-03')
-0.00069388999999999996
A:
>>> line="0.81667E+00 -0.12650E+01 -0.69389E-03"
>>> map(float,line.split())
[0.81667000000000001, -1.2649999999999999, -0.00069388999999999996]
|
Is it possible to read Fortran formatted data in Python?
|
I get output files from very old Fortran programs, which look like:
0.81667E+00 -0.12650E+01 -0.69389E-03
0.94381E+00 -0.11985E+01 -0.11502E+00
0.96064E+00 -0.11333E+01 -0.17616E+00
0.10202E+01 -0.12435E+01 -0.93917E-01
0.10026E+01 -0.10904E+01 -0.15108E+00
0.90516E+00 -0.11030E+01 -0.19139E+00
0.98624E+00 -0.11598E+01 -0.22970E+00
Is it possible to read this in Python and convert the numbers to "normal" floats?
|
[
"Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> float('-0.69389E-03')\n-0.00069388999999999996\n\n",
">>> line=\"0.81667E+00 -0.12650E+01 -0.69389E-03\"\n>>> map(float,line.split())\n[0.81667000000000001, -1.2649999999999999, -0.00069388999999999996]\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"floating_point",
"format",
"fortran",
"python"
] |
stackoverflow_0002336301_floating_point_format_fortran_python.txt
|
Q:
Python code optimization (20x slower than C)
I've written this very badly optimized C code that does a simple math calculation:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
unsigned long long int p(int);
float fullCheck(int);
int main(int argc, char **argv){
int i, g, maxNumber;
unsigned long long int diff = 1000;
if(argc < 2){
fprintf(stderr, "Usage: %s maxNumber\n", argv[0]);
return 0;
}
maxNumber = atoi(argv[1]);
for(i = 1; i < maxNumber; i++){
for(g = 1; g < maxNumber; g++){
if(i == g)
continue;
if(p(MAX(i,g)) - p(MIN(i,g)) < diff && fullCheck(p(MAX(i,g)) - p(MIN(i,g))) && fullCheck(p(i) + p(g))){
diff = p(MAX(i,g)) - p(MIN(i,g));
printf("We have a couple %llu %llu with diff %llu\n", p(i), p(g), diff);
}
}
}
return 0;
}
float fullCheck(int number){
float check = (-1 + sqrt(1 + 24 * number))/-6;
float check2 = (-1 - sqrt(1 + 24 * number))/-6;
if(check/1.00 == (int)check)
return check;
if(check2/1.00 == (int)check2)
return check2;
return 0;
}
unsigned long long int p(int n){
return n * (3 * n - 1 ) / 2;
}
And then I've tried (just for fun) to port it under Python to see how it would react. My first version was almost a 1:1 conversion that run terribly slow (120+secs in Python vs <1sec in C).
I've done a bit of optimization, and this is what I obtained:
#!/usr/bin/env/python
from cmath import sqrt
import cProfile
from pstats import Stats
def quickCheck(n):
partial_c = (sqrt(1 + 24 * (n)))/-6
c = 1/6 + partial_c
if int(c.real) == c.real:
return True
c = c - 2*partial_c
if int(c.real) == c.real:
return True
return False
def main():
maxNumber = 5000
diff = 1000
for i in range(1, maxNumber):
p_i = i * (3 * i - 1 ) / 2
for g in range(i, maxNumber):
if i == g:
continue
p_g = g * (3 * g - 1 ) / 2
if p_i > p_g:
ma = p_i
mi = p_g
else:
ma = p_g
mi = p_i
if ma - mi < diff and quickCheck(ma - mi):
if quickCheck(ma + mi):
print ('New couple ', ma, mi)
diff = ma - mi
cProfile.run('main()','script_perf')
perf = Stats('script_perf').sort_stats('time', 'calls').print_stats(10)
This runs in about 16secs which is better but also almost 20 times slower than C.
Now, I know C is better than Python for this kind of calculations, but what I would like to know is if there something that I've missed (Python-wise, like an horribly slow function or such) that could have made this function faster.
Please note that I'm using Python 3.1.1, if this makes a difference
A:
Since quickCheck is being called close to 25,000,000 times, you might want to use memoization to cache the answers.
You can do memoization in C as well as Python. Things will be much faster in C, also.
You're computing 1/6 in each iteration of quickCheck. I'm not sure if this will be optimized out by Python, but if you can avoid recomputing constant values, you'll find things are faster. C compilers do this for you.
Doing things like if condition: return True; else: return False is silly -- and time consuming. Simply do return condition.
In Python 3.x, /2 must create floating-point values. You appear to need integers for this. You should be using //2 division. It will be closer to the C version in terms of what it does, but I don't think it's significantly faster.
Finally, Python is generally interpreted. The interpreter will always be significantly slower than C.
A:
I made it go from ~7 seconds to ~3 seconds on my machine:
Precomputed i * (3 * i - 1 ) / 2 for each value, in yours it was computed twice quite a lot
Cached calls to quickCheck
Removed if i == g by adding +1 to the range
Removed if p_i > p_g since p_i is always smaller than p_g
Also put the quickCheck-function inside main, to make all variables local (which have faster lookup than global).
I'm sure there are more micro-optimizations available.
def main():
maxNumber = 5000
diff = 1000
p = {}
quickCache = {}
for i in range(maxNumber):
p[i] = i * (3 * i - 1 ) / 2
def quickCheck(n):
if n in quickCache: return quickCache[n]
partial_c = (sqrt(1 + 24 * (n)))/-6
c = 1/6 + partial_c
if int(c.real) == c.real:
quickCache[n] = True
return True
c = c - 2*partial_c
if int(c.real) == c.real:
quickCache[n] = True
return True
quickCache[n] = False
return False
for i in range(1, maxNumber):
mi = p[i]
for g in range(i+1, maxNumber):
ma = p[g]
if ma - mi < diff and quickCheck(ma - mi) and quickCheck(ma + mi):
print('New couple ', ma, mi)
diff = ma - mi
A:
Because the function p() monotonically increasing you can avoid comparing the values as g > i implies p(g) > p(i). Also, the inner loop can be broken early because p(g) - p(i) >= diff implies p(g+1) - p(i) >= diff.
Also for correctness, I changed the equality comparison in quickCheck to compare difference against an epsilon because exact comparison with floating point is pretty fragile.
On my machine this reduced the runtime to 7.8ms using Python 2.6. Using PyPy with JIT reduced this to 0.77ms.
This shows that before turning to micro-optimization it pays to look for algorithmic optimizations. Micro-optimizations make spotting algorithmic changes much harder for relatively tiny gains.
EPS = 0.00000001
def quickCheck(n):
partial_c = sqrt(1 + 24*n) / -6
c = 1/6 + partial_c
if abs(int(c) - c) < EPS:
return True
c = 1/6 - partial_c
if abs(int(c) - c) < EPS:
return True
return False
def p(i):
return i * (3 * i - 1 ) / 2
def main(maxNumber):
diff = 1000
for i in range(1, maxNumber):
for g in range(i+1, maxNumber):
if p(g) - p(i) >= diff:
break
if quickCheck(p(g) - p(i)) and quickCheck(p(g) + p(i)):
print('New couple ', p(g), p(i), p(g) - p(i))
diff = p(g) - p(i)
A:
There are some python compilers that might actually do a good bit for you. Have a look at Psyco.
Another way of dealing with math intensive programs is to rewrite the majority of the work into a math kernel, such as NumPy, so that heavily optimized code is doing the work, and your python code only guides the calculation. To get the most out of this strategy, avoid doing calculations in loops, and instead let the math kernel do all of that.
A:
The other respondents have already mentioned several optimizations that will help. However, ultimately, you're not going to be able to match the performance of C in Python. Python is a nice tool, but since it's interpreted, it isn't really suited for heavy number crunching or other apps where performance is key.
Also, even in your C version, your inner loop could use quite a bit of help. Updated version:
for(i = 1; i < maxNumber; i++){
for(g = 1; g < maxNumber; g++){
if(i == g)
continue;
max=i;
min=g;
if (max<min) {
// xor swap - could use swap(p_max,p_min) instead.
max=max^min;
min=max^min;
max=max^min;
}
p_max=P(max);
p_min=P(min);
p_i=P(i);
p_g=P(g);
if(p_max - p_min < diff && fullCheck(p_max-p_min) && fullCheck(p_i + p_g)){
diff = p_max - p_min;
printf("We have a couple %llu %llu with diff %llu\n", p_i, p_g, diff);
}
}
}
///////////////////////////
float fullCheck(int number){
float den=sqrt(1+24*number)/6.0;
float check = 1/6.0 - den;
float check2 = 1/6.0 + den;
if(check == (int)check)
return check;
if(check2 == (int)check2)
return check2;
return 0.0;
}
Division, function calls, etc are costly. Also, calculating them once and storing in vars such as I've done can make things a lot more readable.
You might consider declaring P() as inline or rewrite as a preprocessor macro. Depending on how good your optimizer is, you might want to perform some of the arithmetic yourself and simplify its implementation.
Your implementation of fullCheck() would return what appear to be invalid results, since 1/6==0, where 1/6.0 would return 0.166... as you would expect.
This is a very brief take on what you can do to your C code to improve performance. This will, no doubt, widen the gap between C and Python performance.
A:
20x difference between Python and C for a number crunching task seems quite good to me.
Check the usual performance differences for some CPU intensive tasks (keep in mind that the scale is logarithmic).
But look on the bright side, what's 1 minute of CPU time compared with the brain and typing time you saved writing Python instead of C? :-)
|
Python code optimization (20x slower than C)
|
I've written this very badly optimized C code that does a simple math calculation:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
unsigned long long int p(int);
float fullCheck(int);
int main(int argc, char **argv){
int i, g, maxNumber;
unsigned long long int diff = 1000;
if(argc < 2){
fprintf(stderr, "Usage: %s maxNumber\n", argv[0]);
return 0;
}
maxNumber = atoi(argv[1]);
for(i = 1; i < maxNumber; i++){
for(g = 1; g < maxNumber; g++){
if(i == g)
continue;
if(p(MAX(i,g)) - p(MIN(i,g)) < diff && fullCheck(p(MAX(i,g)) - p(MIN(i,g))) && fullCheck(p(i) + p(g))){
diff = p(MAX(i,g)) - p(MIN(i,g));
printf("We have a couple %llu %llu with diff %llu\n", p(i), p(g), diff);
}
}
}
return 0;
}
float fullCheck(int number){
float check = (-1 + sqrt(1 + 24 * number))/-6;
float check2 = (-1 - sqrt(1 + 24 * number))/-6;
if(check/1.00 == (int)check)
return check;
if(check2/1.00 == (int)check2)
return check2;
return 0;
}
unsigned long long int p(int n){
return n * (3 * n - 1 ) / 2;
}
And then I've tried (just for fun) to port it under Python to see how it would react. My first version was almost a 1:1 conversion that run terribly slow (120+secs in Python vs <1sec in C).
I've done a bit of optimization, and this is what I obtained:
#!/usr/bin/env/python
from cmath import sqrt
import cProfile
from pstats import Stats
def quickCheck(n):
partial_c = (sqrt(1 + 24 * (n)))/-6
c = 1/6 + partial_c
if int(c.real) == c.real:
return True
c = c - 2*partial_c
if int(c.real) == c.real:
return True
return False
def main():
maxNumber = 5000
diff = 1000
for i in range(1, maxNumber):
p_i = i * (3 * i - 1 ) / 2
for g in range(i, maxNumber):
if i == g:
continue
p_g = g * (3 * g - 1 ) / 2
if p_i > p_g:
ma = p_i
mi = p_g
else:
ma = p_g
mi = p_i
if ma - mi < diff and quickCheck(ma - mi):
if quickCheck(ma + mi):
print ('New couple ', ma, mi)
diff = ma - mi
cProfile.run('main()','script_perf')
perf = Stats('script_perf').sort_stats('time', 'calls').print_stats(10)
This runs in about 16secs which is better but also almost 20 times slower than C.
Now, I know C is better than Python for this kind of calculations, but what I would like to know is if there something that I've missed (Python-wise, like an horribly slow function or such) that could have made this function faster.
Please note that I'm using Python 3.1.1, if this makes a difference
|
[
"Since quickCheck is being called close to 25,000,000 times, you might want to use memoization to cache the answers.\nYou can do memoization in C as well as Python. Things will be much faster in C, also.\nYou're computing 1/6 in each iteration of quickCheck. I'm not sure if this will be optimized out by Python, but if you can avoid recomputing constant values, you'll find things are faster. C compilers do this for you.\nDoing things like if condition: return True; else: return False is silly -- and time consuming. Simply do return condition.\nIn Python 3.x, /2 must create floating-point values. You appear to need integers for this. You should be using //2 division. It will be closer to the C version in terms of what it does, but I don't think it's significantly faster. \nFinally, Python is generally interpreted. The interpreter will always be significantly slower than C.\n",
"I made it go from ~7 seconds to ~3 seconds on my machine:\n\nPrecomputed i * (3 * i - 1 ) / 2 for each value, in yours it was computed twice quite a lot\nCached calls to quickCheck\nRemoved if i == g by adding +1 to the range\nRemoved if p_i > p_g since p_i is always smaller than p_g\n\nAlso put the quickCheck-function inside main, to make all variables local (which have faster lookup than global).\nI'm sure there are more micro-optimizations available.\ndef main():\n maxNumber = 5000\n diff = 1000\n\n p = {}\n quickCache = {}\n\n for i in range(maxNumber):\n p[i] = i * (3 * i - 1 ) / 2\n\n def quickCheck(n):\n if n in quickCache: return quickCache[n]\n partial_c = (sqrt(1 + 24 * (n)))/-6 \n c = 1/6 + partial_c\n if int(c.real) == c.real:\n quickCache[n] = True\n return True\n c = c - 2*partial_c\n if int(c.real) == c.real:\n quickCache[n] = True\n return True\n quickCache[n] = False\n return False\n\n for i in range(1, maxNumber):\n mi = p[i]\n for g in range(i+1, maxNumber):\n ma = p[g]\n if ma - mi < diff and quickCheck(ma - mi) and quickCheck(ma + mi):\n print('New couple ', ma, mi)\n diff = ma - mi\n\n",
"Because the function p() monotonically increasing you can avoid comparing the values as g > i implies p(g) > p(i). Also, the inner loop can be broken early because p(g) - p(i) >= diff implies p(g+1) - p(i) >= diff.\nAlso for correctness, I changed the equality comparison in quickCheck to compare difference against an epsilon because exact comparison with floating point is pretty fragile.\nOn my machine this reduced the runtime to 7.8ms using Python 2.6. Using PyPy with JIT reduced this to 0.77ms.\nThis shows that before turning to micro-optimization it pays to look for algorithmic optimizations. Micro-optimizations make spotting algorithmic changes much harder for relatively tiny gains.\nEPS = 0.00000001\ndef quickCheck(n):\n partial_c = sqrt(1 + 24*n) / -6\n c = 1/6 + partial_c\n if abs(int(c) - c) < EPS:\n return True\n c = 1/6 - partial_c\n if abs(int(c) - c) < EPS:\n return True\n return False\n\ndef p(i):\n return i * (3 * i - 1 ) / 2\n\ndef main(maxNumber):\n diff = 1000\n\n for i in range(1, maxNumber):\n for g in range(i+1, maxNumber):\n if p(g) - p(i) >= diff:\n break \n if quickCheck(p(g) - p(i)) and quickCheck(p(g) + p(i)):\n print('New couple ', p(g), p(i), p(g) - p(i))\n diff = p(g) - p(i)\n\n",
"There are some python compilers that might actually do a good bit for you. Have a look at Psyco.\nAnother way of dealing with math intensive programs is to rewrite the majority of the work into a math kernel, such as NumPy, so that heavily optimized code is doing the work, and your python code only guides the calculation. To get the most out of this strategy, avoid doing calculations in loops, and instead let the math kernel do all of that.\n",
"The other respondents have already mentioned several optimizations that will help. However, ultimately, you're not going to be able to match the performance of C in Python. Python is a nice tool, but since it's interpreted, it isn't really suited for heavy number crunching or other apps where performance is key.\nAlso, even in your C version, your inner loop could use quite a bit of help. Updated version:\n for(i = 1; i < maxNumber; i++){\n for(g = 1; g < maxNumber; g++){\n if(i == g)\n continue;\n max=i;\n min=g;\n\n if (max<min) { \n // xor swap - could use swap(p_max,p_min) instead. \n max=max^min;\n min=max^min;\n max=max^min;\n }\n\n p_max=P(max);\n p_min=P(min);\n p_i=P(i);\n p_g=P(g);\n\n if(p_max - p_min < diff && fullCheck(p_max-p_min) && fullCheck(p_i + p_g)){\n diff = p_max - p_min;\n printf(\"We have a couple %llu %llu with diff %llu\\n\", p_i, p_g, diff);\n }\n }\n }\n\n\n///////////////////////////\nfloat fullCheck(int number){\n float den=sqrt(1+24*number)/6.0;\n float check = 1/6.0 - den;\n float check2 = 1/6.0 + den;\n\n\n if(check == (int)check)\n return check;\n if(check2 == (int)check2)\n return check2;\n\n return 0.0;\n}\n\nDivision, function calls, etc are costly. Also, calculating them once and storing in vars such as I've done can make things a lot more readable. \nYou might consider declaring P() as inline or rewrite as a preprocessor macro. Depending on how good your optimizer is, you might want to perform some of the arithmetic yourself and simplify its implementation.\nYour implementation of fullCheck() would return what appear to be invalid results, since 1/6==0, where 1/6.0 would return 0.166... as you would expect.\nThis is a very brief take on what you can do to your C code to improve performance. This will, no doubt, widen the gap between C and Python performance.\n",
"20x difference between Python and C for a number crunching task seems quite good to me.\nCheck the usual performance differences for some CPU intensive tasks (keep in mind that the scale is logarithmic).\nBut look on the bright side, what's 1 minute of CPU time compared with the brain and typing time you saved writing Python instead of C? :-)\n"
] |
[
17,
10,
5,
4,
2,
1
] |
[] |
[] |
[
"math",
"optimization",
"performance",
"python"
] |
stackoverflow_0002328495_math_optimization_performance_python.txt
|
Q:
How can I figure out in my module if the main program uses a specific variable?
I know this does not sound Pythonic, but bear with me for a second.
I am writing a module that depends on some external closed-source module. That module needs to get instantiated to be used (using module.create()).
My module attempts to figure out if my user already loaded that module (easy to do), but then needs to figure out if the module was instantiated. I understand that checking out the type() of each variable can tell me this, but I am not sure how I can get the names of variables defined by the main program. The reason for this is that when one instantiates the model, they also set a bunch of parameters that I do not want to overwrite for any reason.
My attempts so far involved using sys._getframe().f_globals and iterating through the elements, but in my testing it doesn't work. If I instantiate the module as modInst and then call the function in my module, it fails to show the modInst variable. Is there another solution to this? Sample code provided below.
import sys
if moduleName not in sys.modules:
import moduleName
modInst = moduleName.create()
else:
globalVars = sys._getframe().f_globals
for key, value in globalVars:
if value == "Module Name Instance":
return key
return moduleName.create()
EDIT: Sample code included.
A:
Looks like your code assumes that the .create() function was called, if at all, by the immediate/direct caller of your function (which you show only partially, making it pretty hard to be sure about what's going on) and the results placed in a global variable (of the module where the caller of your function resides). It all seems pretty fragile. Doesn't that third-party module have some global variables of its own that are affected by whether the module's create has been called or not? I imagine it would -- where else is it keeping the state-changes resulting from executing the create -- and I would explore that.
To address a specific issue you raise,
I am not sure how I can get the names
of variables defined by the main
program
that's easy -- the main program is found, as a module, in sys.modules['__main__'], so just use vars(sys.modules['__main__']) to get the global dictionary of the main program (the variable names are the keys in that dictionary, along of course with names of functions, classes, etc -- the module, like any other module, has exactly one top-level/global namespace, not one for variables, a separate one for functions, etc).
A:
Suppose the external closed-sourced module is called extmod.
Create my_extmod.py:
import extmod
INSTANTIATED=False
def create(*args,**kw):
global INSTANTIATED
INSTANTIATED=True
return extmod.create(*args,**kw)
Then require your users to import my_extmod instead of extmod directly.
To test if the create function has been called, just check the value of extmod.INSTANTIATED.
Edit: If you open up an IPython session and type import extmod, then type
extmod.[TAB], then you'll see all the top-level variables in the extmod namespace. This might help you find some parameter that changes when extmod.create is called.
Barring that, and barring the possibility of training users to import my_extmod, then perhaps you could use something like the function below. find_extmod_instance searches through all modules in sys.modules.
def find_instance(cls):
for modname in sys.modules:
module=sys.modules[modname]
for value in vars(module).values():
if isinstance(value,cls):
return value
x=find_instance(extmod.ExtmodClass) or extmod.create()
|
How can I figure out in my module if the main program uses a specific variable?
|
I know this does not sound Pythonic, but bear with me for a second.
I am writing a module that depends on some external closed-source module. That module needs to get instantiated to be used (using module.create()).
My module attempts to figure out if my user already loaded that module (easy to do), but then needs to figure out if the module was instantiated. I understand that checking out the type() of each variable can tell me this, but I am not sure how I can get the names of variables defined by the main program. The reason for this is that when one instantiates the model, they also set a bunch of parameters that I do not want to overwrite for any reason.
My attempts so far involved using sys._getframe().f_globals and iterating through the elements, but in my testing it doesn't work. If I instantiate the module as modInst and then call the function in my module, it fails to show the modInst variable. Is there another solution to this? Sample code provided below.
import sys
if moduleName not in sys.modules:
import moduleName
modInst = moduleName.create()
else:
globalVars = sys._getframe().f_globals
for key, value in globalVars:
if value == "Module Name Instance":
return key
return moduleName.create()
EDIT: Sample code included.
|
[
"Looks like your code assumes that the .create() function was called, if at all, by the immediate/direct caller of your function (which you show only partially, making it pretty hard to be sure about what's going on) and the results placed in a global variable (of the module where the caller of your function resides). It all seems pretty fragile. Doesn't that third-party module have some global variables of its own that are affected by whether the module's create has been called or not? I imagine it would -- where else is it keeping the state-changes resulting from executing the create -- and I would explore that.\nTo address a specific issue you raise,\n\nI am not sure how I can get the names\n of variables defined by the main\n program\n\nthat's easy -- the main program is found, as a module, in sys.modules['__main__'], so just use vars(sys.modules['__main__']) to get the global dictionary of the main program (the variable names are the keys in that dictionary, along of course with names of functions, classes, etc -- the module, like any other module, has exactly one top-level/global namespace, not one for variables, a separate one for functions, etc).\n",
"Suppose the external closed-sourced module is called extmod.\nCreate my_extmod.py:\nimport extmod\nINSTANTIATED=False\ndef create(*args,**kw):\n global INSTANTIATED\n INSTANTIATED=True\n return extmod.create(*args,**kw)\n\nThen require your users to import my_extmod instead of extmod directly.\nTo test if the create function has been called, just check the value of extmod.INSTANTIATED.\nEdit: If you open up an IPython session and type import extmod, then type\nextmod.[TAB], then you'll see all the top-level variables in the extmod namespace. This might help you find some parameter that changes when extmod.create is called. \nBarring that, and barring the possibility of training users to import my_extmod, then perhaps you could use something like the function below. find_extmod_instance searches through all modules in sys.modules.\ndef find_instance(cls):\n for modname in sys.modules:\n module=sys.modules[modname]\n for value in vars(module).values():\n if isinstance(value,cls):\n return value\n\nx=find_instance(extmod.ExtmodClass) or extmod.create()\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"global_variables",
"python",
"python_module"
] |
stackoverflow_0002336868_global_variables_python_python_module.txt
|
Q:
Convert SQL query to Django friendly format for application
I have an SQL query thats runs on the Postgres database of my Django based webapp. The query runs against the data stored by Django-Notifications (a reusable app) and returns a list of email addresses that have not opted out of a specific notice type.
What I would really like to be able to do is to build an application that does this on demand, so I'm looking for an example of how to convert the SQL so it can run inside a Django view that will pass out a formatted email list. The SQL is currently thus:
gr_webapp=# select email from emailconfirmation_emailaddress where verified and user_id not in
(select user_id from notification_noticesetting s join notification_noticetype t on s.notice_type_id = t.id
where t.label = 'announcement' and not s.send);
A:
You might have to make appropriate adjustments as far as model names go, since you didn't show them in your question:
users_to_exclude = Noticesetting.objects.filter(send=False, notice_type__label='announcement').values('user')
emails = Emailaddress.objects.exclude(user__in=users_to_exclude)
|
Convert SQL query to Django friendly format for application
|
I have an SQL query thats runs on the Postgres database of my Django based webapp. The query runs against the data stored by Django-Notifications (a reusable app) and returns a list of email addresses that have not opted out of a specific notice type.
What I would really like to be able to do is to build an application that does this on demand, so I'm looking for an example of how to convert the SQL so it can run inside a Django view that will pass out a formatted email list. The SQL is currently thus:
gr_webapp=# select email from emailconfirmation_emailaddress where verified and user_id not in
(select user_id from notification_noticesetting s join notification_noticetype t on s.notice_type_id = t.id
where t.label = 'announcement' and not s.send);
|
[
"You might have to make appropriate adjustments as far as model names go, since you didn't show them in your question:\nusers_to_exclude = Noticesetting.objects.filter(send=False, notice_type__label='announcement').values('user')\nemails = Emailaddress.objects.exclude(user__in=users_to_exclude)\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_models",
"python",
"sql"
] |
stackoverflow_0002337333_django_django_models_python_sql.txt
|
Q:
django-tinymce: Using different options for different instances
I have a model with an HTMLField which can be edited with a TinyMCE control in the admin. However, I would like to be able to give different options to TinyMCE depending on which instance of the model is being edited. How can I do this?
(For example, if the user is editing the SimplePage instance whose slug is technologies, I want TinyMCE to use the default CSS file, but if its editing the SimplePage whose slug is ticker, I want to use a different CSS file.)
A:
I guess you have a Media class in your ModelAdmin with additional JavaScript and CSS for the admin (like here). Your JavaScript doesn't know the slug of the current object, let's change that.
First create one of the following directory structures in your templates directory: "admin/your-app" for an app or "admin/your-app/your-model" for a specific model only (see the Django documentation).
Then create a file "change_form.html" in that directory and put something similar to this in there:
{% extends "admin/change_form.html" %}
{% block extrahead %}
<script type="text/javascript" charset="utf-8">
var MYAPP_objectSlug = "{{ original.slug|escapejs }}";
</script>
{{ block.super }}
{% endblock %}
This will extend the usual "change_form.html" of the admin and extend the extrahead block to set a JavaScript variable with your object slug (original is your object).
Now adapt the JavaScript file that does the tinyMCE.init to use a different CSS file based
on the JavaScript variable MYAPP_objectSlug.
if (MYAPP_objectSlug == "ticker"){
var MYAPP_cssFile = "../css/special.css"; // change to your path
} else {
var MYAPP_cssFile = "../css/default.css"; // change to your path
}
tinyMCE.init({
...
content_css : MYAPP_cssFile,
...
});
|
django-tinymce: Using different options for different instances
|
I have a model with an HTMLField which can be edited with a TinyMCE control in the admin. However, I would like to be able to give different options to TinyMCE depending on which instance of the model is being edited. How can I do this?
(For example, if the user is editing the SimplePage instance whose slug is technologies, I want TinyMCE to use the default CSS file, but if its editing the SimplePage whose slug is ticker, I want to use a different CSS file.)
|
[
"I guess you have a Media class in your ModelAdmin with additional JavaScript and CSS for the admin (like here). Your JavaScript doesn't know the slug of the current object, let's change that.\nFirst create one of the following directory structures in your templates directory: \"admin/your-app\" for an app or \"admin/your-app/your-model\" for a specific model only (see the Django documentation).\nThen create a file \"change_form.html\" in that directory and put something similar to this in there:\n{% extends \"admin/change_form.html\" %}\n{% block extrahead %}\n<script type=\"text/javascript\" charset=\"utf-8\">\n var MYAPP_objectSlug = \"{{ original.slug|escapejs }}\";\n</script>\n{{ block.super }}\n{% endblock %}\n\nThis will extend the usual \"change_form.html\" of the admin and extend the extrahead block to set a JavaScript variable with your object slug (original is your object).\nNow adapt the JavaScript file that does the tinyMCE.init to use a different CSS file based \n on the JavaScript variable MYAPP_objectSlug.\nif (MYAPP_objectSlug == \"ticker\"){\n var MYAPP_cssFile = \"../css/special.css\"; // change to your path\n} else {\n var MYAPP_cssFile = \"../css/default.css\"; // change to your path\n}\n\ntinyMCE.init({\n ...\n content_css : MYAPP_cssFile,\n ...\n});\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_tinymce",
"python",
"tinymce"
] |
stackoverflow_0002310835_django_django_tinymce_python_tinymce.txt
|
Q:
Output of python scripts displayed only at termination when using SSH?
I'm running a script to manage processes on a remote (SSH) machine. Let's call it five.py
#!/usr/bin/python
import time, subprocess
subprocess.call('echo 0',shell=True)
for i in range(1,5):
time.sleep(1)
print(i)
If i now run
ssh user@host five.py
I would like to see the output
0
1
2
3
4
appear on my standard out second by second (as it does if execute locally).. What happens is: I get the 0 from "echo" right away and the rest only appears at once after the entire program finishes. (Doesn't help to nest 'five.py' into a bash script; to call it by 'python five.py'; or to use 'print >> sys.stdout, i').
This must be related to the way python writes to stdout, since other programs behave quite normal.. A functional workaround is
import time, subprocess
import sys
subprocess.call('echo 0',shell=True)
for i in range(1,5):
time.sleep(1)
sys.stdout.write(str(i)+'\n')
sys.stdout.flush()
But there must be a better solution than changing all my print statements!
A:
You can add the -u on the shebang line as interjay hinted
#!/usr/bin/python -u
You could also reopen stdout with buffering turned off or set to line buffering
import os,sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # no buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # line buffering
Usually line buffering is a good choice
A:
You can replace the sys.stdout object so that it automatically flushes after each write. This will also affect the print statement. An example, taken from this answer:
class flushfile(object):
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
import sys
sys.stdout = flushfile(sys.stdout)
Edit: Another option is to start Python with the -u option, which will force input and output to be unbuffered.
A:
One thing you might look at using since you are already using Python is Paramiko, much nicer way to do remote SSH work. Here is an article about how I am using it in its most basic form.
|
Output of python scripts displayed only at termination when using SSH?
|
I'm running a script to manage processes on a remote (SSH) machine. Let's call it five.py
#!/usr/bin/python
import time, subprocess
subprocess.call('echo 0',shell=True)
for i in range(1,5):
time.sleep(1)
print(i)
If i now run
ssh user@host five.py
I would like to see the output
0
1
2
3
4
appear on my standard out second by second (as it does if execute locally).. What happens is: I get the 0 from "echo" right away and the rest only appears at once after the entire program finishes. (Doesn't help to nest 'five.py' into a bash script; to call it by 'python five.py'; or to use 'print >> sys.stdout, i').
This must be related to the way python writes to stdout, since other programs behave quite normal.. A functional workaround is
import time, subprocess
import sys
subprocess.call('echo 0',shell=True)
for i in range(1,5):
time.sleep(1)
sys.stdout.write(str(i)+'\n')
sys.stdout.flush()
But there must be a better solution than changing all my print statements!
|
[
"You can add the -u on the shebang line as interjay hinted\n#!/usr/bin/python -u\n\nYou could also reopen stdout with buffering turned off or set to line buffering\nimport os,sys\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # no buffering\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # line buffering\n\nUsually line buffering is a good choice\n",
"You can replace the sys.stdout object so that it automatically flushes after each write. This will also affect the print statement. An example, taken from this answer:\nclass flushfile(object):\n def __init__(self, f):\n self.f = f\n def write(self, x):\n self.f.write(x)\n self.f.flush()\n\nimport sys\nsys.stdout = flushfile(sys.stdout)\n\n\nEdit: Another option is to start Python with the -u option, which will force input and output to be unbuffered.\n",
"One thing you might look at using since you are already using Python is Paramiko, much nicer way to do remote SSH work. Here is an article about how I am using it in its most basic form.\n"
] |
[
7,
0,
0
] |
[] |
[] |
[
"python",
"ssh",
"stdout"
] |
stackoverflow_0002336270_python_ssh_stdout.txt
|
Q:
Is it a bad idea to change the app_label assignment on existing Django models?
I have the hair-brained idea of grouping models from different existing apps into one big new shiny app. There's not a super important reason I need to do this, but it would be nice to consolidate all of the code in one subdirectory and it would improve the site to group all the models together in the admin_index under the same module header.
My first thought was to hardcode the existing table names into the db_table setting in Meta on all the models, and then give each an identical app_label setting.
But my concern is that this might screw up the ContentType and auth Permission settings for everything. Has anyone tried this before? I've googled around a bit and haven't seen anything that directly the addresses the question, though it seems like a few people have come up with slick ways of reorginizing the admin_index with some custom configuration settings.
A:
You're correct that moving models around would render existing ContentType entries useless. Without knowing the specifics of your project it's hard to say what might be a "good idea". You might just try branching your code, making the changes, and updating the content types and permissions tables to reflect. Alternatively you could use South to write a data migration although it could be tricky to find a balance of making it work depending on when the migration is created or run vs. when you move the models. You might also check out natural keys if you're able to run trunk: http://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys. This could lead to an easier path of exporting your data out into fixtures in a more generic manner so that once you make your changes you be able to load them in without too much difficulty.
If you're planning on using Django for a while and/or working on large projects you'll want to start to develop the skills to deal with these types of changes. Evolving code and refactoring are facts of life. Learning about the pitfalls of making these changes in a casual setting will set you up better for the future to tackle the kinds of issues that do occur in team settings and on larger projects.
|
Is it a bad idea to change the app_label assignment on existing Django models?
|
I have the hair-brained idea of grouping models from different existing apps into one big new shiny app. There's not a super important reason I need to do this, but it would be nice to consolidate all of the code in one subdirectory and it would improve the site to group all the models together in the admin_index under the same module header.
My first thought was to hardcode the existing table names into the db_table setting in Meta on all the models, and then give each an identical app_label setting.
But my concern is that this might screw up the ContentType and auth Permission settings for everything. Has anyone tried this before? I've googled around a bit and haven't seen anything that directly the addresses the question, though it seems like a few people have come up with slick ways of reorginizing the admin_index with some custom configuration settings.
|
[
"You're correct that moving models around would render existing ContentType entries useless. Without knowing the specifics of your project it's hard to say what might be a \"good idea\". You might just try branching your code, making the changes, and updating the content types and permissions tables to reflect. Alternatively you could use South to write a data migration although it could be tricky to find a balance of making it work depending on when the migration is created or run vs. when you move the models. You might also check out natural keys if you're able to run trunk: http://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys. This could lead to an easier path of exporting your data out into fixtures in a more generic manner so that once you make your changes you be able to load them in without too much difficulty.\nIf you're planning on using Django for a while and/or working on large projects you'll want to start to develop the skills to deal with these types of changes. Evolving code and refactoring are facts of life. Learning about the pitfalls of making these changes in a casual setting will set you up better for the future to tackle the kinds of issues that do occur in team settings and on larger projects.\n"
] |
[
0
] |
[] |
[] |
[
"admin",
"django",
"models",
"python",
"templates"
] |
stackoverflow_0002337259_admin_django_models_python_templates.txt
|
Q:
Exceeding the size of lists in python
I'm trying to implement the sieve of eratosthenes in python, however when trying to find all primes up to the sqare root of for instance 779695003923747564589111193840021 I get an error saying result of range() has too many items. My question is, how do I avoid this problem, if I instantiate the list with a while loop I will get an error saying I'm using too much memory (before it even starts to use the pagefile), the two are listed below:
Using range()
maxnum = 39312312323123123
primes = []
seq = []
i = 0
seq = range(2,maxnum)
for i in seq:
mul = i * seq
for j in mul:
try:
seq.remove(j)
except:
pass
primes.append(i)
print primes
Using while:
maxnum = 39312312323123123
primes = []
seq = []
i = 0
while i < maxnum:
seq.append(i)
i+=1
for i in seq:
mul = i * seq
for j in mul:
try:
seq.remove(j)
except:
pass
primes.append(i)
print primes
A:
I would say, "use xrange() instead", but you are actually using the list of ints as the sieve result..... So an integer generator is not a correct solution.
I think it will be difficult to materialize a list with 39312312323123123 elements in it, no matter what function you use to do so.... That is, after all, 279 petabytes of 64-bit integers.
Try this.
class FoundComposite(Exception): pass
primes = [2]
seq = itertools.takewhile( # Take integers from a list
lambda x: x<MAXNUM, # until we reach MAXNUM
itertools.count(2) # the list of integers starting from 2
)
#seq = xrange(2, MAXNUM) # alternatively
for i in seq:
try:
for divisor in primes:
if not (i % divisor):
# no remainder - thus an even divisor
# continue to next i in seq
raise FoundComposite
# if this is reached, we have tried all divisors.
primes.append(i)
except FoundComposite:
pass
A:
Your algorithm is broken. Get it to work for maxnum=100 first.
Once you get it working you will find maxnum=100000000 will take a long long time to run.
Plot the time it takes to run for maxnum in (10,100,1000,10000,100000,1000000...) and you may be able to extrapolate how long 39312312323123123 will take :)
A:
It's a more complex algorithm, perhaps technically not counting as the sieve, but one approach is to not remove all multiples of a given prime at once, but queue the next multiple (along with the prime). This could be used in a generator implementation. The queue will still end up containing a lot of (multiples of) primes, but not as many as by building then filtering a list.
First few steps done manually, to show the principle...
2 is prime - yield and queue (4, 2)
3 is prime - yield and queue (6, 3)
4 is composite - replace (4, 2) with (6, 2) in the queue
5 is prime - yield and queue (10, 5)
6 is composite - replace (6, 2) with (8, 2) and (6, 3) with (9, 3)
Note - the queue isn't a FIFO. You will always be extracting the tuples with the lowest first item, but new/replacement tuples don't (usually) have the highest first item and (as with 6 above) there will be duplicates.
To handle the queue efficiently in Python, I suggest a dictionary (ie hashtable) keyed by the first item of the tuple. The data is a set of second item values (original primes).
As suggested elsewhere, test with small targets before trying for the big one. And don't be too surprised if you fail. It may still be that you need too many heap-allocated large integers at one time (in the queue) to complete the solution.
A:
There is a third party module for python called gmpy
It has a couple of functions that may be useful to you as they are very fast. The probabilistic stuff kicks in around the 4 billion mark.
next_prime(...)
next_prime(x): returns the smallest prime number > x. Note that
GMP may use a probabilistic definition of 'prime', and also that
if x<0 GMP considers x 'prime' iff -x is prime; gmpy reflects these
GMP design choices. x must be an mpz, or else gets coerced to one.
is_prime(...)
is_prime(x,n=25): returns 2 if x is _certainly_ prime, 1 if x is
_probably_ prime (probability > 1 - 1/2**n), 0 if x is composite.
If x<0, GMP considers x 'prime' iff -x is prime; gmpy reflects this
GMP design choice. x must be an mpz, or else gets coerced to one.
A:
range() returns a list containing all the numbers in the requested range, while xrange is a generator and yields the numbers one after another with a memory consumption close to zero.
A:
About the memory limit, how about creating a custom list (class) that internally is a linked list of lists or arrays. Magically traverse from one to the other internally, and add more as needed, as the caller uses your custom list with the external interface you've provided which will be similar to those members needed to facilitate the .append .remove, etc needs of the arrays used in your problem.
Note: I'm not a Python programmer. Not a clue how to implement what I said in Python. Maybe I don't know the context here, so I will understand if I'm voted down.
Maybe use "generators" as they're called in python to yield results of your internal lists as if it were one huge single list. Possibly with linked list.
A:
Try this:
def getPrimes(maxnum):
primes = []
for i in xrange(2, maxnum):
is_mul = False
for j in primes: # Try dividing by all previous primes
if i % j == 0:
is_mul = True # Once we find a prime that i is divisible by
break # short circuit so we don't have to try all of them
if not is_mul: # if we try every prime we've seen so far and `i`
primes.append(i) # isn't a multiple, so it must be prime
return primes
You shouldn't run out of memory until you get to a very large number of primes. This way you don't have to worry about creating a list of multiples. Not sure if this still counts as the sieve though.
Actually, this won't work for maxnum = 39312312323123123. Using the Prime number theorem we can estimate that there will be approximately 1,028,840,332,567,181 prime numbers in that range.
As pointed out in this question the maximum size of a python list on a 32-bit system is 536,870,912. So even if you don't run out of memory, you still won't be able to finish the calculation.
You shouldn't have that problem with a 64-bit system though.
2 ** 64 => 18446744073709551616
Using the math from the aforementioned question (2 ** 64) / 8, the maximum number of elements in a list would be 2,305,843,009,213,693,951 which is greater than the estimated number of primes you will encounter.
Edit:
To avoid memory issues, you could store your list of primes in a file on the hard disk. Store one prime per line and read the file every time you check a new number.
Maybe something like this:
primes_path = r'C:\temp\primes.txt'
def genPrimes():
for line in open(primes_path, 'r'):
yield int(line.strip())
def addPrime(prime):
primes_file = open(primes_path, 'a')
primes_file.write('%s\n' % prime)
primes_file.close()
def findPrimes(maxnum):
for i in xrange(2, maxnum):
is_mul = False
for prime in genPrimes(): # generate the primes from a file on disk
if i % prime == 0:
is_mul = True
break
if not is_mul:
addPrime(i) # append the new prime to the end of your primes file
At the end, you would have a file on your hard drive that contained all your primes.
Ok, so this would be pretty slow, but you wouldn't run out of memory. You could make it faster by increasing the speed at which you can read/write files (like RAID).
|
Exceeding the size of lists in python
|
I'm trying to implement the sieve of eratosthenes in python, however when trying to find all primes up to the sqare root of for instance 779695003923747564589111193840021 I get an error saying result of range() has too many items. My question is, how do I avoid this problem, if I instantiate the list with a while loop I will get an error saying I'm using too much memory (before it even starts to use the pagefile), the two are listed below:
Using range()
maxnum = 39312312323123123
primes = []
seq = []
i = 0
seq = range(2,maxnum)
for i in seq:
mul = i * seq
for j in mul:
try:
seq.remove(j)
except:
pass
primes.append(i)
print primes
Using while:
maxnum = 39312312323123123
primes = []
seq = []
i = 0
while i < maxnum:
seq.append(i)
i+=1
for i in seq:
mul = i * seq
for j in mul:
try:
seq.remove(j)
except:
pass
primes.append(i)
print primes
|
[
"I would say, \"use xrange() instead\", but you are actually using the list of ints as the sieve result..... So an integer generator is not a correct solution.\nI think it will be difficult to materialize a list with 39312312323123123 elements in it, no matter what function you use to do so.... That is, after all, 279 petabytes of 64-bit integers.\nTry this.\nclass FoundComposite(Exception): pass\n\nprimes = [2]\n\nseq = itertools.takewhile( # Take integers from a list\n lambda x: x<MAXNUM, # until we reach MAXNUM\n itertools.count(2) # the list of integers starting from 2\n )\n\n#seq = xrange(2, MAXNUM) # alternatively\n\nfor i in seq:\n try:\n for divisor in primes:\n if not (i % divisor):\n # no remainder - thus an even divisor\n # continue to next i in seq\n raise FoundComposite \n # if this is reached, we have tried all divisors.\n primes.append(i)\n except FoundComposite:\n pass\n\n",
"Your algorithm is broken. Get it to work for maxnum=100 first.\nOnce you get it working you will find maxnum=100000000 will take a long long time to run.\nPlot the time it takes to run for maxnum in (10,100,1000,10000,100000,1000000...) and you may be able to extrapolate how long 39312312323123123 will take :)\n",
"It's a more complex algorithm, perhaps technically not counting as the sieve, but one approach is to not remove all multiples of a given prime at once, but queue the next multiple (along with the prime). This could be used in a generator implementation. The queue will still end up containing a lot of (multiples of) primes, but not as many as by building then filtering a list.\nFirst few steps done manually, to show the principle...\n\n2 is prime - yield and queue (4, 2)\n3 is prime - yield and queue (6, 3)\n4 is composite - replace (4, 2) with (6, 2) in the queue\n5 is prime - yield and queue (10, 5)\n6 is composite - replace (6, 2) with (8, 2) and (6, 3) with (9, 3)\n\nNote - the queue isn't a FIFO. You will always be extracting the tuples with the lowest first item, but new/replacement tuples don't (usually) have the highest first item and (as with 6 above) there will be duplicates.\nTo handle the queue efficiently in Python, I suggest a dictionary (ie hashtable) keyed by the first item of the tuple. The data is a set of second item values (original primes).\nAs suggested elsewhere, test with small targets before trying for the big one. And don't be too surprised if you fail. It may still be that you need too many heap-allocated large integers at one time (in the queue) to complete the solution.\n",
"There is a third party module for python called gmpy\nIt has a couple of functions that may be useful to you as they are very fast. The probabilistic stuff kicks in around the 4 billion mark.\nnext_prime(...)\n next_prime(x): returns the smallest prime number > x. Note that\n GMP may use a probabilistic definition of 'prime', and also that\n if x<0 GMP considers x 'prime' iff -x is prime; gmpy reflects these\n GMP design choices. x must be an mpz, or else gets coerced to one.\n\nis_prime(...)\n is_prime(x,n=25): returns 2 if x is _certainly_ prime, 1 if x is\n _probably_ prime (probability > 1 - 1/2**n), 0 if x is composite.\n If x<0, GMP considers x 'prime' iff -x is prime; gmpy reflects this\n GMP design choice. x must be an mpz, or else gets coerced to one.\n\n",
"range() returns a list containing all the numbers in the requested range, while xrange is a generator and yields the numbers one after another with a memory consumption close to zero. \n",
"About the memory limit, how about creating a custom list (class) that internally is a linked list of lists or arrays. Magically traverse from one to the other internally, and add more as needed, as the caller uses your custom list with the external interface you've provided which will be similar to those members needed to facilitate the .append .remove, etc needs of the arrays used in your problem.\nNote: I'm not a Python programmer. Not a clue how to implement what I said in Python. Maybe I don't know the context here, so I will understand if I'm voted down.\nMaybe use \"generators\" as they're called in python to yield results of your internal lists as if it were one huge single list. Possibly with linked list.\n",
"Try this:\ndef getPrimes(maxnum):\n primes = []\n for i in xrange(2, maxnum):\n is_mul = False\n for j in primes: # Try dividing by all previous primes\n if i % j == 0:\n is_mul = True # Once we find a prime that i is divisible by\n break # short circuit so we don't have to try all of them\n if not is_mul: # if we try every prime we've seen so far and `i`\n primes.append(i) # isn't a multiple, so it must be prime\n return primes\n\nYou shouldn't run out of memory until you get to a very large number of primes. This way you don't have to worry about creating a list of multiples. Not sure if this still counts as the sieve though.\nActually, this won't work for maxnum = 39312312323123123. Using the Prime number theorem we can estimate that there will be approximately 1,028,840,332,567,181 prime numbers in that range.\nAs pointed out in this question the maximum size of a python list on a 32-bit system is 536,870,912. So even if you don't run out of memory, you still won't be able to finish the calculation.\nYou shouldn't have that problem with a 64-bit system though.\n2 ** 64 => 18446744073709551616\nUsing the math from the aforementioned question (2 ** 64) / 8, the maximum number of elements in a list would be 2,305,843,009,213,693,951 which is greater than the estimated number of primes you will encounter.\nEdit:\nTo avoid memory issues, you could store your list of primes in a file on the hard disk. Store one prime per line and read the file every time you check a new number.\nMaybe something like this:\nprimes_path = r'C:\\temp\\primes.txt'\n\ndef genPrimes():\n for line in open(primes_path, 'r'):\n yield int(line.strip()) \n\ndef addPrime(prime):\n primes_file = open(primes_path, 'a')\n primes_file.write('%s\\n' % prime)\n primes_file.close()\n\ndef findPrimes(maxnum):\n for i in xrange(2, maxnum):\n is_mul = False\n for prime in genPrimes(): # generate the primes from a file on disk\n if i % prime == 0:\n is_mul = True \n break \n if not is_mul: \n addPrime(i) # append the new prime to the end of your primes file\n\nAt the end, you would have a file on your hard drive that contained all your primes.\nOk, so this would be pretty slow, but you wouldn't run out of memory. You could make it faster by increasing the speed at which you can read/write files (like RAID).\n"
] |
[
6,
2,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"memory",
"prime_factoring",
"python",
"sieve_of_eratosthenes"
] |
stackoverflow_0002337700_memory_prime_factoring_python_sieve_of_eratosthenes.txt
|
Q:
Requesting advice on persisting objects from a dynamic language to a document database
Do you have any insights into the most elegant way of persisting objects from a dynamic language in a document database?
I have a solid background in C# and have just started programming in Python. At the same time I am trying to learn the ropes of MongoDB.
Now I am wondering: what is the most elegant way to persist my data to the MongoDB database? I have considered several approaches:
Make all my Python classes able to create a graph of dictionaries and lists representing their state. Moreover, make them able to initialize their state from such a graph. When I want to persist an object, I will ask it for its graph representation and persist that. When I want to get an object, I will retrieve a document graph and provide this to the __init__ method of my class.
Create a separate Mapper class capable of inspecting a given object and creating a graph of dictionaries and lists, which I may then store in MongoDB. The mapper would also be responsible for creating objects whose data has been retrieved from the database.
I tried out mongoengine, a document-object mapper. However, I was disappointed when it forced me to derive my classes from a particular class (Document). It reminded me of Microsoft's Entity Framework 1.0 and the lack of POCO support. I don't want to be forced to derive from a particular class. It doesn't feel right, but I am unsure whether this is really a problem in a dynamic language.
Is my thinking being hindered by my background in C#? I am sure I haven't grokked the extent of the flexibility that a dynamic language provides, so any advice or hints at best practices would be greatly appreciated.
Thank you.
A:
Python defines several special methods such as getstate and many others to allow your classes to define exactly how best to serialize and de-serialize their instances. They're all used internally by the pickle module (which then uses this information to produce a "blob", i.e. a string of bytes, and restore objects from such blobs), but, if you want better indexing obtained by storing graphs directly rather than via opaque blobs, it's basically a question of tweaking the pickle procedures to stop just before turning the graphs into blobs. I think you'll have to do it by copy-paste-edit of pickle.py (as it's not designed to be customized in this way by more elegant methods such as subclassing), but that should still save you lots of work wrt redoing it all from scratch.
I believe this approach lies somewhere between your options 1 and 2 -- classes need to define such special methods only in response to specific needs, and most of the work needed to orchestrate the various possibility will be handled by your pickle-variant (much as it's handled by pickle itself for the "normal" case where the serialized form is a blob).
|
Requesting advice on persisting objects from a dynamic language to a document database
|
Do you have any insights into the most elegant way of persisting objects from a dynamic language in a document database?
I have a solid background in C# and have just started programming in Python. At the same time I am trying to learn the ropes of MongoDB.
Now I am wondering: what is the most elegant way to persist my data to the MongoDB database? I have considered several approaches:
Make all my Python classes able to create a graph of dictionaries and lists representing their state. Moreover, make them able to initialize their state from such a graph. When I want to persist an object, I will ask it for its graph representation and persist that. When I want to get an object, I will retrieve a document graph and provide this to the __init__ method of my class.
Create a separate Mapper class capable of inspecting a given object and creating a graph of dictionaries and lists, which I may then store in MongoDB. The mapper would also be responsible for creating objects whose data has been retrieved from the database.
I tried out mongoengine, a document-object mapper. However, I was disappointed when it forced me to derive my classes from a particular class (Document). It reminded me of Microsoft's Entity Framework 1.0 and the lack of POCO support. I don't want to be forced to derive from a particular class. It doesn't feel right, but I am unsure whether this is really a problem in a dynamic language.
Is my thinking being hindered by my background in C#? I am sure I haven't grokked the extent of the flexibility that a dynamic language provides, so any advice or hints at best practices would be greatly appreciated.
Thank you.
|
[
"Python defines several special methods such as getstate and many others to allow your classes to define exactly how best to serialize and de-serialize their instances. They're all used internally by the pickle module (which then uses this information to produce a \"blob\", i.e. a string of bytes, and restore objects from such blobs), but, if you want better indexing obtained by storing graphs directly rather than via opaque blobs, it's basically a question of tweaking the pickle procedures to stop just before turning the graphs into blobs. I think you'll have to do it by copy-paste-edit of pickle.py (as it's not designed to be customized in this way by more elegant methods such as subclassing), but that should still save you lots of work wrt redoing it all from scratch.\nI believe this approach lies somewhere between your options 1 and 2 -- classes need to define such special methods only in response to specific needs, and most of the work needed to orchestrate the various possibility will be handled by your pickle-variant (much as it's handled by pickle itself for the \"normal\" case where the serialized form is a blob).\n"
] |
[
1
] |
[] |
[] |
[
"dynamic_languages",
"mongodb",
"nosql",
"orm",
"python"
] |
stackoverflow_0002337819_dynamic_languages_mongodb_nosql_orm_python.txt
|
Q:
Pickling array.array in 2.4 using cPickle
I am working on a project built on python 2.4 (It is an embedded python project, so I don't have a choice on the version of python used). Throughout the application, we use array.array to store data.
Support for pickling array.array objects was added to pickle (and cPickle) in 2.5. We have a viable workaround in 2.4 when using the pure python pickle class (we subclass Pickler/Unpickler to handle arrays) but this does not work with cPickle (we need this due to performance problems).
Any suggestions?
EDIT -- SOLUTION:
This is the final code that seems to be working (thanks for the suggestions):
# Add serialization for array objects
def array_unpickler(data):
return array.array(data[0], data[1:])
def array_pickler(arr):
return array_unpickler, ("%s%s" % (arr.typecode, arr.tostring()),)
copy_reg.pickle(array.ArrayType, array_pickler, array_unpickler)
A:
You can use the standard library module copy_reg to register functions to deal with pickling instances of types that don't natively support pickling; cPickle will use your registered functions where needed. I'd apply exactly this "hook" approach to your requirement of pickling instances of array.array.
A:
I'm not sure if the array type can be augmented with a __reduce__ method (perhaps with a subclass), but you could always try converting your arrays to sequences & back again... if the built-in extension mechanism won't work for you. (hack)
I haven't tried this before, but you could try adding support via copy_reg... essentially the same result as implementing __reduce__ on your own class or subclass, but a tad cleaner.
A:
Looks like you can pickle them, but you can't unpickle the result
Python 2.4.5 (#2, Jan 21 2010, 20:05:55)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cPickle as pickle
>>> import array
>>> a=array.array('i','12345678')
>>> pickle.dumps(a,2)
'\x80\x02carray\narray\nq\x01)\x81q\x02.'
>>> b=pickle.loads(_)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: array() takes at least 1 argument (0 given)
Looks the the dumps doesn't even include information about the typecode..or even the data :(
>>> a=array.array('c','abcdefghijkl')
>>> pickle.dumps(a,2)
'\x80\x02carray\narray\nq\x01)\x81q\x02.'
>>>
|
Pickling array.array in 2.4 using cPickle
|
I am working on a project built on python 2.4 (It is an embedded python project, so I don't have a choice on the version of python used). Throughout the application, we use array.array to store data.
Support for pickling array.array objects was added to pickle (and cPickle) in 2.5. We have a viable workaround in 2.4 when using the pure python pickle class (we subclass Pickler/Unpickler to handle arrays) but this does not work with cPickle (we need this due to performance problems).
Any suggestions?
EDIT -- SOLUTION:
This is the final code that seems to be working (thanks for the suggestions):
# Add serialization for array objects
def array_unpickler(data):
return array.array(data[0], data[1:])
def array_pickler(arr):
return array_unpickler, ("%s%s" % (arr.typecode, arr.tostring()),)
copy_reg.pickle(array.ArrayType, array_pickler, array_unpickler)
|
[
"You can use the standard library module copy_reg to register functions to deal with pickling instances of types that don't natively support pickling; cPickle will use your registered functions where needed. I'd apply exactly this \"hook\" approach to your requirement of pickling instances of array.array.\n",
"I'm not sure if the array type can be augmented with a __reduce__ method (perhaps with a subclass), but you could always try converting your arrays to sequences & back again... if the built-in extension mechanism won't work for you. (hack)\nI haven't tried this before, but you could try adding support via copy_reg... essentially the same result as implementing __reduce__ on your own class or subclass, but a tad cleaner.\n",
"Looks like you can pickle them, but you can't unpickle the result\nPython 2.4.5 (#2, Jan 21 2010, 20:05:55) \n[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import cPickle as pickle\n>>> import array\n>>> a=array.array('i','12345678')\n>>> pickle.dumps(a,2)\n'\\x80\\x02carray\\narray\\nq\\x01)\\x81q\\x02.'\n>>> b=pickle.loads(_)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nTypeError: array() takes at least 1 argument (0 given)\n\nLooks the the dumps doesn't even include information about the typecode..or even the data :(\n>>> a=array.array('c','abcdefghijkl') \n>>> pickle.dumps(a,2) \n'\\x80\\x02carray\\narray\\nq\\x01)\\x81q\\x02.'\n>>> \n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"monkeypatching",
"pickle",
"python",
"python_2.4"
] |
stackoverflow_0002338001_monkeypatching_pickle_python_python_2.4.txt
|
Q:
Keeping ORM with stored procedures
I am developing a Python web app using sqlalchemy to communicate with mysql database. So far I have mostly been using sqlalchemy's ORM layer to speak with the database. The greatest benefit to me of ORM has been the speed of development, not having to write all these sql queries and then map them to models.
Recently, however, I've been required to change my design to communicate with the database through stored procedures. Does any one know if there is any way to use sqlalchemy ORM layer to work with my models through the stored procedures? Is there another Python library which would allow me to do this?
The way I see it I should be able to write my own select, insert, update and delete statements, attach them to the model and let the library do the rest. I've gone through sqlalchemy's documentation multiple times but can't seem to find a way to do this.
Any help with this would be great!
A:
SQLAlchemy doesn't have any good way to convert inserts, updates and deletes to stored procedure calls. It probably wouldn't be that hard to add the capability to have instead_{update,insert,delete} extensions on mappers, but no one has bothered yet. I consider the requirement to have simple DML statements go through stored procedures rather silly. It really doesn't offer anything that you couldn't do with triggers.
If you can't avoid the silliness, there are some ways that you can use SQLAlchemy to go along with it. You'll lose some of the ORM functionality though. You can build ORM objects from stored procedure results using query(Obj).from_statement(text("...")), just have the column labels in the statement match the column names that you told SQLAlchemy to map.
One option to cope with DML statements is to turn autoflush off and instead of flushing go through the sessions .new, .dirty and .deleted attributes to see what has changed, issue corresponding statements as stored procedure calls and expunge the objects before committing.
Or you can just forgo SQLAlchemy state tracking and issue the stored procedure calls directly.
|
Keeping ORM with stored procedures
|
I am developing a Python web app using sqlalchemy to communicate with mysql database. So far I have mostly been using sqlalchemy's ORM layer to speak with the database. The greatest benefit to me of ORM has been the speed of development, not having to write all these sql queries and then map them to models.
Recently, however, I've been required to change my design to communicate with the database through stored procedures. Does any one know if there is any way to use sqlalchemy ORM layer to work with my models through the stored procedures? Is there another Python library which would allow me to do this?
The way I see it I should be able to write my own select, insert, update and delete statements, attach them to the model and let the library do the rest. I've gone through sqlalchemy's documentation multiple times but can't seem to find a way to do this.
Any help with this would be great!
|
[
"SQLAlchemy doesn't have any good way to convert inserts, updates and deletes to stored procedure calls. It probably wouldn't be that hard to add the capability to have instead_{update,insert,delete} extensions on mappers, but no one has bothered yet. I consider the requirement to have simple DML statements go through stored procedures rather silly. It really doesn't offer anything that you couldn't do with triggers.\nIf you can't avoid the silliness, there are some ways that you can use SQLAlchemy to go along with it. You'll lose some of the ORM functionality though. You can build ORM objects from stored procedure results using query(Obj).from_statement(text(\"...\")), just have the column labels in the statement match the column names that you told SQLAlchemy to map.\nOne option to cope with DML statements is to turn autoflush off and instead of flushing go through the sessions .new, .dirty and .deleted attributes to see what has changed, issue corresponding statements as stored procedure calls and expunge the objects before committing. \nOr you can just forgo SQLAlchemy state tracking and issue the stored procedure calls directly.\n"
] |
[
3
] |
[] |
[] |
[
"database",
"mysql",
"python",
"sqlalchemy",
"stored_procedures"
] |
stackoverflow_0002330278_database_mysql_python_sqlalchemy_stored_procedures.txt
|
Q:
python, hash function selection
Using Python and Django, I will let my users to give pdf based gifts to their friends, which the said friend will be able to claim pdf by entering to my site from the emailed link.
Here is the plan
User gives a gives to his friend, enters friends email
In the background, a gift model is saved which will contain a uniquely generated hash code at the save.
Friend receives the email, provided the link to download the pdf which will be like (www.mydomain.com/gift/<hash code here>)
When the mailed link is clicked, system checks if such gift model with the given hash code exists.
If so download starts, else 404.
Is this a clever way of solving this? If so what hashing function would you recommend ? It is interesting as the /gift/ is open to the public, if somehow lucky enough to find a link, anyone can claim it. I am planning to feed the hash function by receivers first-last name plus the pk of the gift model
A:
There is no need to use a hash, you just need a random token.
Create a string of random characters
If it is already used ( unlikely ) repeat step 1
Make the string of characters long enough that you are happy it will be hard to guess
an easy way to generate a random string is
>>> import os
>>> os.urandom(10).encode('hex')
'3fa0c2f72ff275f48d66'
>>> os.urandom(20).encode('hex')
'ecc1143b3fc90bd99bcd609b326694f13291e3d1'
>>> os.urandom(30).encode('hex')
'd4a9a2cd7b48eca831e9805e68dd6f7db7275b654e55cdec603631a5a355'
>>>
A:
UUIDs are pretty random
In [13]: import uuid
In [14]: uuid.uuid4().hex
Out[14]: 'f7a7667e94574e32b3589f84ca35a98d'
A:
It may not do things exactly the way you wish, but this project would be a good starting point:
http://github.com/mogga/django-token-auth/
|
python, hash function selection
|
Using Python and Django, I will let my users to give pdf based gifts to their friends, which the said friend will be able to claim pdf by entering to my site from the emailed link.
Here is the plan
User gives a gives to his friend, enters friends email
In the background, a gift model is saved which will contain a uniquely generated hash code at the save.
Friend receives the email, provided the link to download the pdf which will be like (www.mydomain.com/gift/<hash code here>)
When the mailed link is clicked, system checks if such gift model with the given hash code exists.
If so download starts, else 404.
Is this a clever way of solving this? If so what hashing function would you recommend ? It is interesting as the /gift/ is open to the public, if somehow lucky enough to find a link, anyone can claim it. I am planning to feed the hash function by receivers first-last name plus the pk of the gift model
|
[
"There is no need to use a hash, you just need a random token.\n\nCreate a string of random characters \nIf it is already used ( unlikely ) repeat step 1\n\nMake the string of characters long enough that you are happy it will be hard to guess \nan easy way to generate a random string is\n>>> import os\n>>> os.urandom(10).encode('hex')\n'3fa0c2f72ff275f48d66'\n>>> os.urandom(20).encode('hex')\n'ecc1143b3fc90bd99bcd609b326694f13291e3d1'\n>>> os.urandom(30).encode('hex')\n'd4a9a2cd7b48eca831e9805e68dd6f7db7275b654e55cdec603631a5a355'\n>>> \n\n",
"UUIDs are pretty random\nIn [13]: import uuid\n\nIn [14]: uuid.uuid4().hex\nOut[14]: 'f7a7667e94574e32b3589f84ca35a98d'\n\n",
"It may not do things exactly the way you wish, but this project would be a good starting point:\nhttp://github.com/mogga/django-token-auth/\n"
] |
[
6,
1,
0
] |
[] |
[] |
[
"django",
"hash",
"hashcode",
"python"
] |
stackoverflow_0002337825_django_hash_hashcode_python.txt
|
Q:
In SciPy, using ix_() with sparse matrices doesn't seem to work so what else can I use?
In Numpy, ix_() is used to grab rows and columns of a matrix, but it doesn't seem to work with sparse matrices. For instance, this code works because it uses a dense matrix:
>>> import numpy as np
>>> x = np.mat([[1,0,3],[0,4,5],[7,8,0]])
>>> print x
[[1 0 3]
[0 4 5]
[7 8 0]]
>>> print x[np.ix_([0,2],[0,2])]
[[1 3]
[7 0]]
I used ix_() to index the elements corresponding with the 0th and 2nd rows and columns which gives the 4 corners of the matrix.
The problem is that ix_ doesn't seem to work with sparse matrices. Continuing from the previous code, I try the following:
>>> import scipy.sparse as sparse
>>> xspar = sparse.csr_matrix(x)
>>> print xspar
(0, 0) 1
(0, 2) 3
(1, 1) 4
(1, 2) 5
(2, 0) 7
(2, 1) 8
>>> print xspar[np.ix_([0,2],[0,2])]
and get a huge error message saying there is this exception:
File "C:\Python26\lib\site-packages\scipy\sparse\compressed.py", line 138, in check_format
raise ValueError('data, indices, and indptr should be rank 1')
ValueError: data, indices, and indptr should be rank 1
I have tried this with the other sparse matrix formats provided by SciPy, but none of them seem to work with ix_() though they don't all raise the same exception.
The example I gave used a matrix that wasn't very big or very sparse, but the ones I am dealing with are quite sparse and potentially very large so it doesn't seem prudent to just list off the elements one by one.
Does anyone know a (hopefully easy) way to do this sort of indexing with sparse matrices in SciPy or is this feature just not built into these sparse matrices?
A:
Try this instead:
>>> print xspar
(0, 0) 1
(0, 2) 3
(1, 1) 4
(1, 2) 5
(2, 0) 7
(2, 1) 8
>>> print xspar[[[0],[2]],[0,2]]
(0, 0) 1
(0, 2) 3
(2, 0) 7
Note the difference with this:
>>> print xspar[[0,2],[0,2]]
[[1 0]]
|
In SciPy, using ix_() with sparse matrices doesn't seem to work so what else can I use?
|
In Numpy, ix_() is used to grab rows and columns of a matrix, but it doesn't seem to work with sparse matrices. For instance, this code works because it uses a dense matrix:
>>> import numpy as np
>>> x = np.mat([[1,0,3],[0,4,5],[7,8,0]])
>>> print x
[[1 0 3]
[0 4 5]
[7 8 0]]
>>> print x[np.ix_([0,2],[0,2])]
[[1 3]
[7 0]]
I used ix_() to index the elements corresponding with the 0th and 2nd rows and columns which gives the 4 corners of the matrix.
The problem is that ix_ doesn't seem to work with sparse matrices. Continuing from the previous code, I try the following:
>>> import scipy.sparse as sparse
>>> xspar = sparse.csr_matrix(x)
>>> print xspar
(0, 0) 1
(0, 2) 3
(1, 1) 4
(1, 2) 5
(2, 0) 7
(2, 1) 8
>>> print xspar[np.ix_([0,2],[0,2])]
and get a huge error message saying there is this exception:
File "C:\Python26\lib\site-packages\scipy\sparse\compressed.py", line 138, in check_format
raise ValueError('data, indices, and indptr should be rank 1')
ValueError: data, indices, and indptr should be rank 1
I have tried this with the other sparse matrix formats provided by SciPy, but none of them seem to work with ix_() though they don't all raise the same exception.
The example I gave used a matrix that wasn't very big or very sparse, but the ones I am dealing with are quite sparse and potentially very large so it doesn't seem prudent to just list off the elements one by one.
Does anyone know a (hopefully easy) way to do this sort of indexing with sparse matrices in SciPy or is this feature just not built into these sparse matrices?
|
[
"Try this instead:\n>>> print xspar\n (0, 0) 1\n (0, 2) 3\n (1, 1) 4\n (1, 2) 5\n (2, 0) 7\n (2, 1) 8\n>>> print xspar[[[0],[2]],[0,2]]\n (0, 0) 1\n (0, 2) 3\n (2, 0) 7\n\nNote the difference with this:\n>>> print xspar[[0,2],[0,2]]\n [[1 0]]\n\n"
] |
[
2
] |
[] |
[] |
[
"indexing",
"numpy",
"python",
"scipy",
"sparse_matrix"
] |
stackoverflow_0002338260_indexing_numpy_python_scipy_sparse_matrix.txt
|
Q:
parse xhtml in python 2.6
xml.etree.ElementTree.parse is choking on my xhtml file. I saw somewhere that lxml can handle html. Can someone tell me the documented way to parse, and then alter, xhtml? I want to add some javascript to xhtml on the fly.
A:
Have you tried BeautifulSoup? It handles documents that aren't well formed and I've found it pretty good.
|
parse xhtml in python 2.6
|
xml.etree.ElementTree.parse is choking on my xhtml file. I saw somewhere that lxml can handle html. Can someone tell me the documented way to parse, and then alter, xhtml? I want to add some javascript to xhtml on the fly.
|
[
"Have you tried BeautifulSoup? It handles documents that aren't well formed and I've found it pretty good.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"xhtml"
] |
stackoverflow_0002338533_python_xhtml.txt
|
Q:
Grabbing a random frame from a webcam with GStreamer in Python
I'm trying to write a program to control a robot by interpreting frames from a webcam and happened upon GStreamer.
I've been able to stream video in Python from the webcam with GStreamer with help from this page:
http://www.ndeschildre.net/2008/04/04/python-power/
However, I don't know how to ask for a single RGB-encoded frame from the Pipeline, and while I've managed to find and read some of the documentation, I've found no obvious answer.
Does anyone have any ideas?
EDIT: I've attempted to use OpenCV to solve this problem first, but the buffer isn't staying put or something, and is causing successive images to not start at the top left corner of the buffer.
(operating system is Ubuntu Linux)
A:
Look at the source code for cheese, the Gnome photobooth application.
You could also try the usersink.
A:
I've heard of some success with OpenCV's Python bindings. Here is one of those successes: http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/
|
Grabbing a random frame from a webcam with GStreamer in Python
|
I'm trying to write a program to control a robot by interpreting frames from a webcam and happened upon GStreamer.
I've been able to stream video in Python from the webcam with GStreamer with help from this page:
http://www.ndeschildre.net/2008/04/04/python-power/
However, I don't know how to ask for a single RGB-encoded frame from the Pipeline, and while I've managed to find and read some of the documentation, I've found no obvious answer.
Does anyone have any ideas?
EDIT: I've attempted to use OpenCV to solve this problem first, but the buffer isn't staying put or something, and is causing successive images to not start at the top left corner of the buffer.
(operating system is Ubuntu Linux)
|
[
"Look at the source code for cheese, the Gnome photobooth application.\nYou could also try the usersink.\n",
"I've heard of some success with OpenCV's Python bindings. Here is one of those successes: http://blog.jozilla.net/2008/06/27/fun-with-python-opencv-and-face-detection/\n"
] |
[
1,
1
] |
[] |
[] |
[
"gstreamer",
"python",
"snapshot",
"webcam"
] |
stackoverflow_0002337147_gstreamer_python_snapshot_webcam.txt
|
Q:
Why can't a Deferred be passed to a callback in Python Twisted?
d = Deferred()
d.callback(Deferred()) # Assertion error saying that a Deferred shouldn't be passed
Why is this? I looked through the code and commit messages / Trac and see no reason why this should be the case. The most obvious way to bypass this is to put the Deferred in a tuple, but why is this restriction here in the first place?
A:
There are two related reasons for this.
First, it helps catch what is likely a mistake early - near the place where the mistake is being made. A Deferred is called back with a result which is then passed to all of its callbacks. If you make the result itself a Deferred, then there's not much these callbacks can do when they're called. This leads me to the next reason.
Second, Deferreds support be chaining which handles the most common use cases one might have for passing in a Deferred. Given two Deferreds, a and b, chaining causes a to pause processing its own callback chain until b has a result, then a resumes its callback chain with the result of b. This is what happens when a callback on a Deferred returns a Deferred. It can also be done explicitly with Deferred.chainDeferred.
|
Why can't a Deferred be passed to a callback in Python Twisted?
|
d = Deferred()
d.callback(Deferred()) # Assertion error saying that a Deferred shouldn't be passed
Why is this? I looked through the code and commit messages / Trac and see no reason why this should be the case. The most obvious way to bypass this is to put the Deferred in a tuple, but why is this restriction here in the first place?
|
[
"There are two related reasons for this.\nFirst, it helps catch what is likely a mistake early - near the place where the mistake is being made. A Deferred is called back with a result which is then passed to all of its callbacks. If you make the result itself a Deferred, then there's not much these callbacks can do when they're called. This leads me to the next reason.\nSecond, Deferreds support be chaining which handles the most common use cases one might have for passing in a Deferred. Given two Deferreds, a and b, chaining causes a to pause processing its own callback chain until b has a result, then a resumes its callback chain with the result of b. This is what happens when a callback on a Deferred returns a Deferred. It can also be done explicitly with Deferred.chainDeferred.\n"
] |
[
5
] |
[] |
[] |
[
"deferred_execution",
"python",
"twisted"
] |
stackoverflow_0002321577_deferred_execution_python_twisted.txt
|
Q:
QSqlTableModel, data function overload
I'm trying to inherit QSqlTableModel to make data im my table display in way i need.
class TableViewModel(QSqlTableModel):
def __init__(self):
super(TableViewModel, self).__init__()
def flags(self, modelIndex):
if not modelIndex.isValid():
return
if modelIndex.column() != 1 and modelIndex.column() != 4:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
def data(self, modelIndex, role=Qt.DisplayRole):
if not modelIndex.isValid():
return QVariant()
if role != Qt.DisplayRole & role != Qt.EditRole:
return QVariant()
return record.value(modelIndex.column())
With this code i'm only getting empty cells. Without data() function this code work perfectly, the data displayed in TableView exactly it should be.
I'm just enmeshed by getting data from QSqlTableModel. Where can i find it? Or is it just my call wrong?
Thanks in advance.
A:
I'm not sure what that record.value is supposed to be (no indication in your code of where that record variable lives or how or when it's set). Anyway, for "getting data from QSqlTableModel" (whereby I assume you mean the base class you're subclassing), use
whatever = QSqlTableModel.data(self, modelIndex, role)
|
QSqlTableModel, data function overload
|
I'm trying to inherit QSqlTableModel to make data im my table display in way i need.
class TableViewModel(QSqlTableModel):
def __init__(self):
super(TableViewModel, self).__init__()
def flags(self, modelIndex):
if not modelIndex.isValid():
return
if modelIndex.column() != 1 and modelIndex.column() != 4:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
def data(self, modelIndex, role=Qt.DisplayRole):
if not modelIndex.isValid():
return QVariant()
if role != Qt.DisplayRole & role != Qt.EditRole:
return QVariant()
return record.value(modelIndex.column())
With this code i'm only getting empty cells. Without data() function this code work perfectly, the data displayed in TableView exactly it should be.
I'm just enmeshed by getting data from QSqlTableModel. Where can i find it? Or is it just my call wrong?
Thanks in advance.
|
[
"I'm not sure what that record.value is supposed to be (no indication in your code of where that record variable lives or how or when it's set). Anyway, for \"getting data from QSqlTableModel\" (whereby I assume you mean the base class you're subclassing), use\nwhatever = QSqlTableModel.data(self, modelIndex, role)\n\n"
] |
[
2
] |
[] |
[] |
[
"pyqt",
"python"
] |
stackoverflow_0002338276_pyqt_python.txt
|
Q:
How can I order elements in this case? - Django
So I have a list of models,
don't think the structure of these models is important.
In this case Articles.
So these Articles are ordered by popularity between a rank of 1 to 100, all the other articles have no ranks.
Whenever I update the rank of a model the model with equivalent rank must loose its rank.
Any ideas?
A:
Do you mean something like this?
def update_rank(rank, article):
old = Article.object.get(rank=rank)
old.rank = None
old.save()
article.rank = rank
article.save()
|
How can I order elements in this case? - Django
|
So I have a list of models,
don't think the structure of these models is important.
In this case Articles.
So these Articles are ordered by popularity between a rank of 1 to 100, all the other articles have no ranks.
Whenever I update the rank of a model the model with equivalent rank must loose its rank.
Any ideas?
|
[
"Do you mean something like this?\ndef update_rank(rank, article):\n old = Article.object.get(rank=rank)\n old.rank = None\n old.save()\n article.rank = rank\n article.save()\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002339203_django_django_models_python.txt
|
Q:
How can I run a py2exe program in windows without the terminal?
Could someone explain to me how can I run my py2exe program, a console program, without the terminal on Windows?
I'm trying to make a program that re-sizes windows and it supposed to start with windows, so I want it hide out but still running...
A:
Use the setup() function like this:
setup(windows=['myfile.py'])
See the list of options for setup().
A:
Not really understand your requirement, but you can try start /MIN. type start /? on the command line to see its help page.
A:
Would you consider compiling it into an EXE (using py2exe or some such) and adding it to your list of startup programs?
A:
Sounds like what you want is for your script to run as a Windows Service instead of a Windows program. Something like this tutorial might be helpful:
http://islascruz.org/html/index.php?gadget=StaticPage&action=Page&id=6
|
How can I run a py2exe program in windows without the terminal?
|
Could someone explain to me how can I run my py2exe program, a console program, without the terminal on Windows?
I'm trying to make a program that re-sizes windows and it supposed to start with windows, so I want it hide out but still running...
|
[
"Use the setup() function like this:\nsetup(windows=['myfile.py'])\nSee the list of options for setup().\n",
"Not really understand your requirement, but you can try start /MIN. type start /? on the command line to see its help page.\n",
"Would you consider compiling it into an EXE (using py2exe or some such) and adding it to your list of startup programs?\n",
"Sounds like what you want is for your script to run as a Windows Service instead of a Windows program. Something like this tutorial might be helpful: \nhttp://islascruz.org/html/index.php?gadget=StaticPage&action=Page&id=6\n"
] |
[
4,
0,
0,
0
] |
[] |
[] |
[
"py2exe",
"python",
"windows"
] |
stackoverflow_0002338951_py2exe_python_windows.txt
|
Q:
Any way of achieving the same thing as python -mpdb from inside the script?
Besides wrapping all your code in try except, is there any way of achieving the same thing as running your script like python -mpdb script? I'd like to be able to see what went wrong when an exception gets raised.
A:
If you do not want to modify the source then yOu could run it from ipython - an enhanced interactive python shell.
e.g. run ipython then execute %pdb on to enable post-mortem debugging. %run scriptname will then run the script and automatically enter the debugger on any uncaught exceptions.
Alternatively %run -d scriptname will start the script in the debugger.
A:
python -i script
will leave you in the interactive shell when an exception gets raised; then
import pdb
pdb.pm()
will put you into the post-mortem debugger so you can do all the usual debugging things.
This should work as long as your script does not call sys.exit. (Which scripts should never do, because it breaks this very useful technique! as well as making them harder to write tests for.)
|
Any way of achieving the same thing as python -mpdb from inside the script?
|
Besides wrapping all your code in try except, is there any way of achieving the same thing as running your script like python -mpdb script? I'd like to be able to see what went wrong when an exception gets raised.
|
[
"If you do not want to modify the source then yOu could run it from ipython - an enhanced interactive python shell.\ne.g. run ipython then execute %pdb on to enable post-mortem debugging. %run scriptname will then run the script and automatically enter the debugger on any uncaught exceptions.\nAlternatively %run -d scriptname will start the script in the debugger.\n",
"python -i script\n\nwill leave you in the interactive shell when an exception gets raised; then\nimport pdb\npdb.pm()\n\nwill put you into the post-mortem debugger so you can do all the usual debugging things.\nThis should work as long as your script does not call sys.exit. (Which scripts should never do, because it breaks this very useful technique! as well as making them harder to write tests for.)\n"
] |
[
3,
1
] |
[
"import pdb; pdb.set_trace()\nSource: http://docs.python.org/library/pdb.html\n"
] |
[
-1
] |
[
"debugging",
"pdb",
"python"
] |
stackoverflow_0002337216_debugging_pdb_python.txt
|
Q:
RGB to VIBGYOR in python
After downloading an image and getting the rgb color code is there any algorithm to find in which range of VIBGYOR that particular rgb color code match?
regards
Arun
A:
The color range for VIBGYOR (or spectral colors) isn't the same as RGB.
Check out wikipedia on color:
http://en.wikipedia.org/wiki/Color
Pay special attention to "Spectral colors and color reproduction"
An example of the issue is that pink and magenta are nonspectral colors. In addition, the spectral color doesn't take into account intensity while RGB does.
A:
You can use colorsys.rgb_to_hsv() to convert it, then take the hue from that.
|
RGB to VIBGYOR in python
|
After downloading an image and getting the rgb color code is there any algorithm to find in which range of VIBGYOR that particular rgb color code match?
regards
Arun
|
[
"The color range for VIBGYOR (or spectral colors) isn't the same as RGB. \nCheck out wikipedia on color:\nhttp://en.wikipedia.org/wiki/Color\nPay special attention to \"Spectral colors and color reproduction\"\nAn example of the issue is that pink and magenta are nonspectral colors. In addition, the spectral color doesn't take into account intensity while RGB does.\n",
"You can use colorsys.rgb_to_hsv() to convert it, then take the hue from that.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002339554_python.txt
|
Q:
Workaround for python 2.4's yield not allowed in try block with finally clause
I'm stuck on python2.4, so I can't use a finally clause with generators or yield. Is there any way to work around this?
I can't find any mentions of how to work around this limitation in python 2.4, and I'm not a big fan of the workarounds I've thought of (mainly involving __del__ and trying to make sure it runs within a reasonable time) aren't very appealing.
A:
You can duplicate code to avoid the finally block:
try:
yield 42
finally:
do_something()
Becomes:
try:
yield 42
except: # bare except, catches *anything*
do_something()
raise # re-raise same exception
do_something()
(I've not tried this on Python 2.4, you may have to look at sys.exc_info instead of the re-raise statement above, as in raise sys.exc_info[0], sys.exc_info[1], sys.exc_info[2].)
A:
The only code that's guaranteed to be called when a generator instance is simply abandoned (garbage collected) are the __del__ methods for its local variables (if no references to those objects exist outside) and the callbacks for weak references to its local variables (ditto). I recommend the weak reference route because it's non-invasive (you don't need a special class with a __del__ -- just anything that's weakly referenceable). E.g.:
import weakref
def gen():
x = set()
def finis(*_):
print 'finis!'
y = weakref.ref(x, finis)
for i in range(99):
yield i
for i in gen():
if i>5: break
this does print finis!, as desired.
|
Workaround for python 2.4's yield not allowed in try block with finally clause
|
I'm stuck on python2.4, so I can't use a finally clause with generators or yield. Is there any way to work around this?
I can't find any mentions of how to work around this limitation in python 2.4, and I'm not a big fan of the workarounds I've thought of (mainly involving __del__ and trying to make sure it runs within a reasonable time) aren't very appealing.
|
[
"You can duplicate code to avoid the finally block:\ntry:\n yield 42\nfinally:\n do_something()\n\nBecomes:\ntry:\n yield 42\nexcept: # bare except, catches *anything*\n do_something()\n raise # re-raise same exception\ndo_something()\n\n(I've not tried this on Python 2.4, you may have to look at sys.exc_info instead of the re-raise statement above, as in raise sys.exc_info[0], sys.exc_info[1], sys.exc_info[2].)\n",
"The only code that's guaranteed to be called when a generator instance is simply abandoned (garbage collected) are the __del__ methods for its local variables (if no references to those objects exist outside) and the callbacks for weak references to its local variables (ditto). I recommend the weak reference route because it's non-invasive (you don't need a special class with a __del__ -- just anything that's weakly referenceable). E.g.:\nimport weakref\n\ndef gen():\n x = set()\n def finis(*_):\n print 'finis!'\n y = weakref.ref(x, finis)\n for i in range(99):\n yield i\n\nfor i in gen():\n if i>5: break\n\nthis does print finis!, as desired.\n"
] |
[
7,
3
] |
[] |
[] |
[
"python",
"python_2.4",
"try_finally",
"yield"
] |
stackoverflow_0002339358_python_python_2.4_try_finally_yield.txt
|
Q:
Transaction within transaction
I want to know if open a transaction inside another is safe and encouraged?
I have a method:
def foo():
session.begin
try:
stuffs
except Exception, e:
session.rollback()
raise e
session.commit()
and a method that calls the first one, inside a transaction:
def bar():
stuffs
try:
foo() #<<<< there it is :)
stuffs
except Exception, e:
session.rollback()
raise e
session.commit()
if I get and exception on the foo method, all the operations will be
rolled back? and everything else will work just fine?
thanks!!
A:
There are two ways to nest transactions in SQLAlchemy. One is virtual transactions, where SQLAlchemy keeps track of how many begin's you have issued and issues the commit only when the outermost transaction commits. The rollback however is issued immediately. Because the transaction is virtual - i.e. the database knows nothing of the nesting, you can't do anything with that session after the rollback until you rollback all the outer transactions too. To allow the use virtual transactions add subtransactions=True argument to the begin() call. This feature exists to allow you to use transaction control inside functions that might call each other without keeping track if you are inside a transaction or not. For it to make sense, configure the session with autocommit=True and always issue a session.begin(subtransactions=True) in a transactional function.
The other way to nest transactions is to use real nested transactions. They are implemented using savepoints. If you rollback a nested transaction, all changes made within that transaction are rolled back, but the outer transaction remains usable and any changes made by the outer transaction are still there. To use nested transaction issue session.begin(nested=True) or just session.begin_nested(). Nested transactions aren't supported for all databases. SQLAlchemy's test suite library configuration function sqlalchemy.test.requires.savepoints says this about the support:
emits_warning_on('mssql', 'Savepoint support in mssql is experimental and may lead to data loss.'),
no_support('access', 'not supported by database'),
no_support('sqlite', 'not supported by database'),
no_support('sybase', 'FIXME: guessing, needs confirmation'),
exclude('mysql', '<', (5, 0, 3), 'not supported by database')
On PostgreSQL SQLAlchemy nested transactions work just fine.
A:
You can't, PostgreSQL doesn't support subtransactions. You might want to use savepoints, but thats something else.
A:
On PostgreSQL nested transactions work just fine.
Well, you're not going to get an error (just a warning), that's true. But you can't commit the inner transaction and rollback the outer transaction, the outer transaction will also rollback the inner transaction.
BEGIN;
INSERT INTO x(foo) VALUES('John');
BEGIN; -- WARNING!
INSERT INTO y(bar) VALUES('Jane');
COMMIT; -- commit inner transaction
ROLLBACK; -- will rollback both inserts, not just the first, the one in table "x"
To my knowledge, Oracle is one of the few that has this option.
|
Transaction within transaction
|
I want to know if open a transaction inside another is safe and encouraged?
I have a method:
def foo():
session.begin
try:
stuffs
except Exception, e:
session.rollback()
raise e
session.commit()
and a method that calls the first one, inside a transaction:
def bar():
stuffs
try:
foo() #<<<< there it is :)
stuffs
except Exception, e:
session.rollback()
raise e
session.commit()
if I get and exception on the foo method, all the operations will be
rolled back? and everything else will work just fine?
thanks!!
|
[
"There are two ways to nest transactions in SQLAlchemy. One is virtual transactions, where SQLAlchemy keeps track of how many begin's you have issued and issues the commit only when the outermost transaction commits. The rollback however is issued immediately. Because the transaction is virtual - i.e. the database knows nothing of the nesting, you can't do anything with that session after the rollback until you rollback all the outer transactions too. To allow the use virtual transactions add subtransactions=True argument to the begin() call. This feature exists to allow you to use transaction control inside functions that might call each other without keeping track if you are inside a transaction or not. For it to make sense, configure the session with autocommit=True and always issue a session.begin(subtransactions=True) in a transactional function.\nThe other way to nest transactions is to use real nested transactions. They are implemented using savepoints. If you rollback a nested transaction, all changes made within that transaction are rolled back, but the outer transaction remains usable and any changes made by the outer transaction are still there. To use nested transaction issue session.begin(nested=True) or just session.begin_nested(). Nested transactions aren't supported for all databases. SQLAlchemy's test suite library configuration function sqlalchemy.test.requires.savepoints says this about the support:\n emits_warning_on('mssql', 'Savepoint support in mssql is experimental and may lead to data loss.'),\n no_support('access', 'not supported by database'),\n no_support('sqlite', 'not supported by database'),\n no_support('sybase', 'FIXME: guessing, needs confirmation'),\n exclude('mysql', '<', (5, 0, 3), 'not supported by database')\n\nOn PostgreSQL SQLAlchemy nested transactions work just fine.\n",
"You can't, PostgreSQL doesn't support subtransactions. You might want to use savepoints, but thats something else.\n",
"\nOn PostgreSQL nested transactions work just fine.\n\nWell, you're not going to get an error (just a warning), that's true. But you can't commit the inner transaction and rollback the outer transaction, the outer transaction will also rollback the inner transaction.\n\nBEGIN;\n\nINSERT INTO x(foo) VALUES('John');\nBEGIN; -- WARNING!\n\nINSERT INTO y(bar) VALUES('Jane');\n\nCOMMIT; -- commit inner transaction\n\nROLLBACK; -- will rollback both inserts, not just the first, the one in table \"x\"\n\nTo my knowledge, Oracle is one of the few that has this option.\n"
] |
[
19,
0,
0
] |
[] |
[] |
[
"database",
"postgresql",
"python",
"sqlalchemy"
] |
stackoverflow_0002336950_database_postgresql_python_sqlalchemy.txt
|
Q:
Better way to represent Many to many relationship in django admin
I have a unique problem the way it should be handled in django admin.
I have following models structure...
class Product(models.Model):
name = models.CharField(max_length = 100)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length = 2)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class CountryProduct(models.Model):
country = models.ForeignKey(Country)
product = models.ForeignKey(Product)
overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)
class Meta:
unique_together = (("country", "product"),)
As shown here there is many to many relationship between products and countries.... I want to provide admin interface for overriding base price for given country and product.
One option to have ui as follows, here dash (-) represents default price and value in number represents override price for given country and product.
countries -> | US | UK
products | |
---------------------------
Product1 | - | 10
Product2 | 5 | 7
But I don't know how to do that....
I am open to look at alternative approaches (including changes in model structure) as well as long as it meets the requirement... Your input of any sort will definitely be useful to me...
Thanks in Advance :)
A:
I got the solution, here is my answer to my question... Let me share it with you... I changed the model in following way....
class Product(models.Model):
name = models.CharField(max_length = 100)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length = 2)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
products = models.ManyToManyField(Product, through = 'CountryProduct')
def __unicode__(self):
return self.name
class CountryProduct(models.Model):
country = models.ForeignKey(Country)
product = models.ForeignKey(Product)
overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)
class Meta:
unique_together = (("country", "product"),)
class CountryProductInline(admin.TabularInline):
model = CountryProduct
class CountryAdmin(admin.ModelAdmin):
inlines = [CountryProductInline]
class ProductAdmin(admin.ModelAdmin):
inlines = [CountryProductInline]
Though this is not the way I expected, this gives me even better solution....
A:
There is no way built-in to the django admin to do what you need.
You could create your own custom view, and do it that way. You can add extra views to an admin.ModelAdmin class, that will do what you need.
A:
This is -- potentially -- a terrible design. Your database table should contain the correct price.
Your application must now do two things. It must get a default price from somewhere else (not in this table) and it must also get an override price (from this table) and put the two pieces of information together.
You cannot trivially make SQL work with the kind of grid you are showing.
You cannot easily get the Django admin to work with a grid like you are showing. You can try to create a grid template, but it's unique to this many-to-many relationship, so you also have to customize the Django admin views to use your template for one many-to-many table, and use the ordinary default template for all other tables.
To create the grid you must fetch all of your countries and products. You must then create the appropriate list-of-lists. You can then write your own template to display this. After you have more than 12 or so countries, the grid will be so wide as to be nearly useless. But for the first few countries you can make this work.
You'll have to create your own template and your own view function to do this.
Edit
"I am open to look at alternative approaches (including changes in model structure) as well as long as it meets the requirement"
Which requirement? The poor design where it takes two queries to find the price? Is that required?
Or the very difficult grid layout? Is that required?
It's not clear what "the requirement" is, so it's not possible to propose any alternative. It's only possible to say
A SQL design that queries base and overrides separately will be slower and more complex.
A SQL design that has a single value which is loaded from a "dynamic default" and can be changed (or not) by the user is much, much simpler. This can be done with the initial argument. http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial
SQL can't easily turn multiple rows into a grid-like structure. This requires either sophisticated SQL (well outside the ORM's capability) or Python processing in a view function.
The Django admin won't do grid-like structures at all.
|
Better way to represent Many to many relationship in django admin
|
I have a unique problem the way it should be handled in django admin.
I have following models structure...
class Product(models.Model):
name = models.CharField(max_length = 100)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length = 2)
base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __unicode__(self):
return self.name
class CountryProduct(models.Model):
country = models.ForeignKey(Country)
product = models.ForeignKey(Product)
overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)
class Meta:
unique_together = (("country", "product"),)
As shown here there is many to many relationship between products and countries.... I want to provide admin interface for overriding base price for given country and product.
One option to have ui as follows, here dash (-) represents default price and value in number represents override price for given country and product.
countries -> | US | UK
products | |
---------------------------
Product1 | - | 10
Product2 | 5 | 7
But I don't know how to do that....
I am open to look at alternative approaches (including changes in model structure) as well as long as it meets the requirement... Your input of any sort will definitely be useful to me...
Thanks in Advance :)
|
[
"I got the solution, here is my answer to my question... Let me share it with you... I changed the model in following way....\nclass Product(models.Model):\n name = models.CharField(max_length = 100)\n base_price = models.DecimalField(max_digits = 5, decimal_places = 2)\n\n\n def __unicode__(self):\n return self.name\n\n\nclass Country(models.Model):\n name = models.CharField(max_length = 2)\n base_price = models.DecimalField(max_digits = 5, decimal_places = 2) \n products = models.ManyToManyField(Product, through = 'CountryProduct')\n\n def __unicode__(self):\n return self.name\n\n\nclass CountryProduct(models.Model):\n country = models.ForeignKey(Country)\n product = models.ForeignKey(Product)\n overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)\n\n class Meta:\n unique_together = ((\"country\", \"product\"),)\n\n\nclass CountryProductInline(admin.TabularInline):\n model = CountryProduct\n\nclass CountryAdmin(admin.ModelAdmin):\n inlines = [CountryProductInline]\n\nclass ProductAdmin(admin.ModelAdmin):\n inlines = [CountryProductInline]\n\nThough this is not the way I expected, this gives me even better solution....\n",
"There is no way built-in to the django admin to do what you need.\nYou could create your own custom view, and do it that way. You can add extra views to an admin.ModelAdmin class, that will do what you need.\n",
"This is -- potentially -- a terrible design. Your database table should contain the correct price.\nYour application must now do two things. It must get a default price from somewhere else (not in this table) and it must also get an override price (from this table) and put the two pieces of information together.\nYou cannot trivially make SQL work with the kind of grid you are showing. \nYou cannot easily get the Django admin to work with a grid like you are showing. You can try to create a grid template, but it's unique to this many-to-many relationship, so you also have to customize the Django admin views to use your template for one many-to-many table, and use the ordinary default template for all other tables.\nTo create the grid you must fetch all of your countries and products. You must then create the appropriate list-of-lists. You can then write your own template to display this. After you have more than 12 or so countries, the grid will be so wide as to be nearly useless. But for the first few countries you can make this work.\nYou'll have to create your own template and your own view function to do this.\nEdit\n\"I am open to look at alternative approaches (including changes in model structure) as well as long as it meets the requirement\"\nWhich requirement? The poor design where it takes two queries to find the price? Is that required?\nOr the very difficult grid layout? Is that required? \nIt's not clear what \"the requirement\" is, so it's not possible to propose any alternative. It's only possible to say\n\nA SQL design that queries base and overrides separately will be slower and more complex.\nA SQL design that has a single value which is loaded from a \"dynamic default\" and can be changed (or not) by the user is much, much simpler. This can be done with the initial argument. http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial\nSQL can't easily turn multiple rows into a grid-like structure. This requires either sophisticated SQL (well outside the ORM's capability) or Python processing in a view function.\nThe Django admin won't do grid-like structures at all.\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"django",
"django_admin",
"django_models",
"python"
] |
stackoverflow_0002332238_django_django_admin_django_models_python.txt
|
Q:
Why copy post data in Django instead of working with it directly?
Django code samples involving post data often shows code similar to this:
if request.method == "POST":
post = request.POST.copy()
#do stuff with post data
Is there a reason for copying the post data instead of working with it directly?
A:
I think it is because request.POST itself is defined immutable. If you want a version you can actually change (mutability), you need a copy of the data to work with.
See this link (request.POST is a QueryDict instance).
class QueryDict
QueryDict instances are immutable, unless you create a copy() of them. That means you can’t change attributes of request.POST and request.GET directly.
|
Why copy post data in Django instead of working with it directly?
|
Django code samples involving post data often shows code similar to this:
if request.method == "POST":
post = request.POST.copy()
#do stuff with post data
Is there a reason for copying the post data instead of working with it directly?
|
[
"I think it is because request.POST itself is defined immutable. If you want a version you can actually change (mutability), you need a copy of the data to work with.\nSee this link (request.POST is a QueryDict instance).\n\n\nclass QueryDict\nQueryDict instances are immutable, unless you create a copy() of them. That means you can’t change attributes of request.POST and request.GET directly.\n\n"
] |
[
10
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002339857_django_python.txt
|
Q:
Django slugified urls - how to handle collisions?
I'm currently working on a toy project in Django.
Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.
So, if a user writes a review called "The best thing ever!", the url would be something like: www.example.com/reviews/the-best-thing-ever.
That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.
I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.
Any ideas?
A:
I would recommend something like AutoSlugField. It has a few options available with respect to configuring uniqueness (unique and unique_with), and has the added benefit of being able to automatically generate slugs based on another field on your model, if you so choose.
A:
One thing I never liked about the unique slug fields/methods is that if you have a lot of clashes for a single title, you'll end up running several queries to try and determine an available slug. I know you mentioned you don't want to show the id for non-clashing slugs, but, as far as performance, I think it's the better route to take. To make the URL a little nicer looking, I prefer also to embed the id before the slug, so that a URL takes the form of www.example.com/reviews/1/the-best-thing-ever.
A:
from django.template.defaultfilters import slugify
def slugify_unique(value, model, slugfield="slug"):
suffix = 0
potential = base = slugify(value)
while True:
if suffix:
potential = "-".join([base, str(suffix)])
if not model.objects.filter(**{slugfield: potential}).count():
return potential
suffix += 1
"""
above function is not my code, but i don't remember exactly where it comes from
you can find many snippets with such solutions searching for 'unique slug' and so
"""
class ReviewForm(forms.ModelForm):
def save(self, user, commit=True):
self.instance.slug = slugify_unique(self.cleaned_data['title'], self.Meta.model)
review = super(ReviewForm, self).save(commit)
review.save()
return review
class Meta:
model = Review
of course change the appropriate names and form definition, but you get the idea :)
A:
I would (in the form validation) just check to see if the slug is used, and then add something to it, either a number "my-cool-idea_2" or the actual id
|
Django slugified urls - how to handle collisions?
|
I'm currently working on a toy project in Django.
Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.
So, if a user writes a review called "The best thing ever!", the url would be something like: www.example.com/reviews/the-best-thing-ever.
That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.
I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.
Any ideas?
|
[
"I would recommend something like AutoSlugField. It has a few options available with respect to configuring uniqueness (unique and unique_with), and has the added benefit of being able to automatically generate slugs based on another field on your model, if you so choose.\n",
"One thing I never liked about the unique slug fields/methods is that if you have a lot of clashes for a single title, you'll end up running several queries to try and determine an available slug. I know you mentioned you don't want to show the id for non-clashing slugs, but, as far as performance, I think it's the better route to take. To make the URL a little nicer looking, I prefer also to embed the id before the slug, so that a URL takes the form of www.example.com/reviews/1/the-best-thing-ever.\n",
"from django.template.defaultfilters import slugify\n\ndef slugify_unique(value, model, slugfield=\"slug\"):\n suffix = 0\n potential = base = slugify(value)\n while True:\n if suffix:\n potential = \"-\".join([base, str(suffix)])\n if not model.objects.filter(**{slugfield: potential}).count():\n return potential\n suffix += 1 \n\"\"\"\nabove function is not my code, but i don't remember exactly where it comes from\nyou can find many snippets with such solutions searching for 'unique slug' and so\n\"\"\"\n\n\nclass ReviewForm(forms.ModelForm):\n\n def save(self, user, commit=True): \n self.instance.slug = slugify_unique(self.cleaned_data['title'], self.Meta.model) \n review = super(ReviewForm, self).save(commit)\n review.save()\n return review\n\n class Meta:\n model = Review\n\nof course change the appropriate names and form definition, but you get the idea :)\n",
"I would (in the form validation) just check to see if the slug is used, and then add something to it, either a number \"my-cool-idea_2\" or the actual id\n"
] |
[
6,
6,
2,
0
] |
[] |
[] |
[
"collision",
"django",
"python",
"slug",
"url"
] |
stackoverflow_0001490559_collision_django_python_slug_url.txt
|
Q:
Why isn't Python installed on Windows by default?
Or any other normal scripting language for that matter. I know there is VBScript and JScript. But I don't really like those for any kind of computing.
I would really love to have python or ruby (or perl) interpreter installed with windows by default so when I write small console applications I wouldn't need to distribute whole python installation with it via py2exe(or similar).
Do you know if there is such incentive? Do you think this would be possible? Or it's not acceptable for Microsoft?
A:
Microsoft makes it pretty obvious they want you to use their version of everything. So what is in it for them to have Python or any other language as part of their Windows operating system?
They want you to program for Microsoft Internet Explorer using Microsoft Active Server Pages with Microsoft Visual Basic on Microsoft Internet Information Server, back-ended by Microsoft SQL Server running on top of Microsoft Windows. It goes on and on like this...
It makes perfect sense from a business perspective when you think about it.
So... Will we see competing "products"--even open source ones--installed by default on Windows? Not gonna happen anytime soon.
A:
The Microsoft scripting tool is Powershell. It is a standard part of Windows 7.
A:
You could create your own Windows Installation-Disc with the wished script or programming language installed on default..
Perhaps search on SuperUser.com (or Google) for this matter.
A:
Because Windows doesn't need those languages to run, by default ?
(While, for instance, many basic Linux utilities depend on some script-languages, like Perl)
I would add that JScript and VBScript have been implemted by Microsoft -- so Microsoft can distribute their implementation ; on the other hand, there is no Microsoft implementation of either Python, PHP, or Perl, ...
A:
Firstly, Windows doesn't need them to run, and to be honest, most people buying Windows have no knowledge of - let alone interest in - scripting languages.
It then comes down to ownership and support. There's nothing ships as part of a default Windows installation which isn't owned, designed and developed by Microsoft. They own everything, so the buck stops with them. If they shipped any third-party packages as part of the installer who would pick up support if something goes wrong?
Finally, there's the competitive advantage of providing your own products over third-party tools or packages in a default installation.
A:
Install Python/Perl on your development server, do your programming/coding there, test and compile them into executables, using tools such as py2exe (Python) or perl2exe (Perl). then distribute them (without the interpreter). That's one way.
A:
Another way to do it is to distribute your apps with an installer such as NSIS and if python is not installed, install it.
Microsoft have no incentive to install {your favourite tool here} unless:
Someone pays them to,
They are required to by law (browser ballot screen here in the EU being one example)
Microsoft includes PowerShell and Microsoft's own development libraries (like VC, previously msvbvmXX.dll's, .net) because these are Microsoft products, part of their development tools. This is to encourage use of their tools and make it easier for people using their tools to deploy, compared to other languages. Why? They're in a competitive business.
|
Why isn't Python installed on Windows by default?
|
Or any other normal scripting language for that matter. I know there is VBScript and JScript. But I don't really like those for any kind of computing.
I would really love to have python or ruby (or perl) interpreter installed with windows by default so when I write small console applications I wouldn't need to distribute whole python installation with it via py2exe(or similar).
Do you know if there is such incentive? Do you think this would be possible? Or it's not acceptable for Microsoft?
|
[
"Microsoft makes it pretty obvious they want you to use their version of everything. So what is in it for them to have Python or any other language as part of their Windows operating system? \nThey want you to program for Microsoft Internet Explorer using Microsoft Active Server Pages with Microsoft Visual Basic on Microsoft Internet Information Server, back-ended by Microsoft SQL Server running on top of Microsoft Windows. It goes on and on like this...\nIt makes perfect sense from a business perspective when you think about it.\nSo... Will we see competing \"products\"--even open source ones--installed by default on Windows? Not gonna happen anytime soon.\n",
"The Microsoft scripting tool is Powershell. It is a standard part of Windows 7.\n",
"You could create your own Windows Installation-Disc with the wished script or programming language installed on default..\nPerhaps search on SuperUser.com (or Google) for this matter.\n",
"Because Windows doesn't need those languages to run, by default ?\n(While, for instance, many basic Linux utilities depend on some script-languages, like Perl)\nI would add that JScript and VBScript have been implemted by Microsoft -- so Microsoft can distribute their implementation ; on the other hand, there is no Microsoft implementation of either Python, PHP, or Perl, ...\n",
"Firstly, Windows doesn't need them to run, and to be honest, most people buying Windows have no knowledge of - let alone interest in - scripting languages.\nIt then comes down to ownership and support. There's nothing ships as part of a default Windows installation which isn't owned, designed and developed by Microsoft. They own everything, so the buck stops with them. If they shipped any third-party packages as part of the installer who would pick up support if something goes wrong?\nFinally, there's the competitive advantage of providing your own products over third-party tools or packages in a default installation.\n",
"Install Python/Perl on your development server, do your programming/coding there, test and compile them into executables, using tools such as py2exe (Python) or perl2exe (Perl). then distribute them (without the interpreter). That's one way. \n",
"Another way to do it is to distribute your apps with an installer such as NSIS and if python is not installed, install it.\nMicrosoft have no incentive to install {your favourite tool here} unless:\n\nSomeone pays them to,\nThey are required to by law (browser ballot screen here in the EU being one example)\n\nMicrosoft includes PowerShell and Microsoft's own development libraries (like VC, previously msvbvmXX.dll's, .net) because these are Microsoft products, part of their development tools. This is to encourage use of their tools and make it easier for people using their tools to deploy, compared to other languages. Why? They're in a competitive business.\n"
] |
[
6,
3,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"default",
"python",
"ruby",
"windows"
] |
stackoverflow_0002340150_default_python_ruby_windows.txt
|
Q:
How can I make URLs in Django similar to stackoverflow?
I'm creating a video site. I want my direct urls to a video to look like example.com/watch/this-is-a-slug-1 where 1 is the video id. I don't want the slug to matter though. example.com/watch/this-is-another-slug-1 should point to the same page. On SO, /questions/id is the only part of the url that matters. How can I do that?
A:
Stack Overflow uses the form
example.com/watch/1/this-is-a-slug
which is easier to handle. You're opening a can of worms if you want the ID to be at the end of the slug token, since then it'll (for example) restrict what kinds of slugs you can use, or just make it harder on yourself.
You can use a url handler like:
(r'^watch/(?P<id>\d+)/', 'watch')
to grab only the ID and ignore anything after the ID. (Note there's no $ end-of-line character.)
A:
I haven't used Django but I've used MVC frameworks before. Generally they have some sort of URL routing feature that lets you define a pattern (usually a regular expression) which gets mapped to a controller.
This might be a good place to start: http://docs.djangoproject.com/en/dev/topics/http/urls/
As Jesse Beder stated, you would just need the regular expression to match the first URL segment (/watch) and a numerical ID, and then forward that to a watch controller, which would deal with the ID and ignore the slug.
|
How can I make URLs in Django similar to stackoverflow?
|
I'm creating a video site. I want my direct urls to a video to look like example.com/watch/this-is-a-slug-1 where 1 is the video id. I don't want the slug to matter though. example.com/watch/this-is-another-slug-1 should point to the same page. On SO, /questions/id is the only part of the url that matters. How can I do that?
|
[
"Stack Overflow uses the form\nexample.com/watch/1/this-is-a-slug\n\nwhich is easier to handle. You're opening a can of worms if you want the ID to be at the end of the slug token, since then it'll (for example) restrict what kinds of slugs you can use, or just make it harder on yourself.\nYou can use a url handler like:\n(r'^watch/(?P<id>\\d+)/', 'watch')\n\nto grab only the ID and ignore anything after the ID. (Note there's no $ end-of-line character.)\n",
"I haven't used Django but I've used MVC frameworks before. Generally they have some sort of URL routing feature that lets you define a pattern (usually a regular expression) which gets mapped to a controller.\nThis might be a good place to start: http://docs.djangoproject.com/en/dev/topics/http/urls/\nAs Jesse Beder stated, you would just need the regular expression to match the first URL segment (/watch) and a numerical ID, and then forward that to a watch controller, which would deal with the ID and ignore the slug.\n"
] |
[
9,
0
] |
[
"With all due respect to Stackoverflow, this is the wrong way to do it. You shouldn't need to have two elements in the URL that identify the page. The ID is irrelevant - it's junk. You should be able to uniquely identify a page from the slug alone.\n"
] |
[
-3
] |
[
"django",
"friendly_url",
"python",
"slug",
"url"
] |
stackoverflow_0002339436_django_friendly_url_python_slug_url.txt
|
Q:
Set a DTD using minidom in python
I am trying to include a reference to a DTD in my XML doc using minidom.
I am creating the document like:
doc = Document()
foo = doc.createElement('foo')
doc.appendChild(foo)
doc.toxml()
This gives me:
<?xml version="1.0" ?>
<foo/>
I need to get something like:
<?xml version="1.0" ?>
<!DOCTYPE something SYSTEM "http://www.path.to.my.dtd.com/my.dtd">
<foo/>
A:
The documentation is out of date. Use the source, Luke. I do it something like this.
from xml.dom.minidom import DOMImplementation
imp = DOMImplementation()
doctype = imp.createDocumentType(
qualifiedName='foo',
publicId='',
systemId='http://www.path.to.my.dtd.com/my.dtd',
)
doc = imp.createDocument(None, 'foo', doctype)
doc.toxml()
This prints the following.
<?xml version="1.0" ?><!DOCTYPE foo SYSTEM \'http://www.path.to.my.dtd.com/my.dtd\'><foo/>
Note how the root element is created automatically by createDocument(). Also, your 'something' has been changed to 'foo': the DTD needs to contain the root element name itself.
A:
According to the Python docs, there is no implementation of the DocumentType interface in the minidom.
|
Set a DTD using minidom in python
|
I am trying to include a reference to a DTD in my XML doc using minidom.
I am creating the document like:
doc = Document()
foo = doc.createElement('foo')
doc.appendChild(foo)
doc.toxml()
This gives me:
<?xml version="1.0" ?>
<foo/>
I need to get something like:
<?xml version="1.0" ?>
<!DOCTYPE something SYSTEM "http://www.path.to.my.dtd.com/my.dtd">
<foo/>
|
[
"The documentation is out of date. Use the source, Luke. I do it something like this.\nfrom xml.dom.minidom import DOMImplementation\n\nimp = DOMImplementation()\ndoctype = imp.createDocumentType(\n qualifiedName='foo',\n publicId='', \n systemId='http://www.path.to.my.dtd.com/my.dtd',\n)\ndoc = imp.createDocument(None, 'foo', doctype)\ndoc.toxml()\n\nThis prints the following.\n<?xml version=\"1.0\" ?><!DOCTYPE foo SYSTEM \\'http://www.path.to.my.dtd.com/my.dtd\\'><foo/>\n\nNote how the root element is created automatically by createDocument(). Also, your 'something' has been changed to 'foo': the DTD needs to contain the root element name itself.\n",
"According to the Python docs, there is no implementation of the DocumentType interface in the minidom.\n"
] |
[
9,
1
] |
[] |
[] |
[
"dtd",
"minidom",
"python",
"xml"
] |
stackoverflow_0002337285_dtd_minidom_python_xml.txt
|
Q:
web2py, OAuth and LinkedIn
I am new to Python and Web2py and I am developing an app that will use the LinkedIn API.
I use this library http://code.google.com/p/python-linkedin/ (it includes OAuth). My problem is very strange and that's why I am writing to the list.
When I try to connect to LinkedIn from the web2py console I get a request Token. When I do it inside a HTTP request I get a signature invalid exception.
The code I use in both cases is quite simple:
li = LinkedIn(LINKEDIN_API_KEY, LINKEDIN_SECRET_KEY, URL(r=request, c='default',f='import_accounts'))
li.requestToken()
A:
I just tried and it works but:
1) make sure you run this on the same hostname that you registered with linkedin
2) pass a full RETURN_URL, not a relative URL as returned by URL
def index():
import linkedin
from linkedin import linkedin
RETURN_URL = "http://web2py.com/linkedin/default/hello"
api = linkedin.LinkedIn(KEY, SECRET, RETURN_URL)
token = api.requestToken()
return dict(message=T('Hello World'),token=token)
A:
You mentioned that in both cases it is quite simple... it leaves me to wonder.
Is it the exact same code in both cases?
|
web2py, OAuth and LinkedIn
|
I am new to Python and Web2py and I am developing an app that will use the LinkedIn API.
I use this library http://code.google.com/p/python-linkedin/ (it includes OAuth). My problem is very strange and that's why I am writing to the list.
When I try to connect to LinkedIn from the web2py console I get a request Token. When I do it inside a HTTP request I get a signature invalid exception.
The code I use in both cases is quite simple:
li = LinkedIn(LINKEDIN_API_KEY, LINKEDIN_SECRET_KEY, URL(r=request, c='default',f='import_accounts'))
li.requestToken()
|
[
"I just tried and it works but:\n1) make sure you run this on the same hostname that you registered with linkedin\n2) pass a full RETURN_URL, not a relative URL as returned by URL\ndef index():\n import linkedin\n from linkedin import linkedin\n RETURN_URL = \"http://web2py.com/linkedin/default/hello\"\n api = linkedin.LinkedIn(KEY, SECRET, RETURN_URL)\n token = api.requestToken()\n return dict(message=T('Hello World'),token=token)\n\n",
"You mentioned that in both cases it is quite simple... it leaves me to wonder.\nIs it the exact same code in both cases?\n"
] |
[
1,
0
] |
[] |
[] |
[
"linkedin",
"oauth",
"python",
"web2py"
] |
stackoverflow_0002312464_linkedin_oauth_python_web2py.txt
|
Q:
SVN pre-commit hook to reject Python files with inconsistent tab usage
The Python interpreter can be started with -tt to raise a TabError exception if the interpreted file has inconsistent tab usage.
I'm trying to write a pre-commit hook for SVN that rejects files that raise this exception. I can pass the file being committed to python -tt but my problem is that the file is also executed, besides being checked. Is there a way to tell Python "just analyze the file, don't run it"? Or maybe some other approach would be better for accomplishing what I want.
A:
You can do this using the py_compile module:
$ python -tt -c "import py_compile; py_compile.compile('test.py', doraise=True)"
The doraise=True will raise an exception and return with a nonzero exit code that you can easily test in your pre-commit hook.
A:
The preferred tab usage in Python is no tab usage at all (use four spaces for indentation). If that is your coding style then the problem may be reduced to checking if there are any tabs in the code. And this can be easily done with simple regexp, even with 'grep', so there is no even need to run the interpreter.
The 'py_compile' way have other advantage, though: it also checks Python code syntax, which may be desirable (though costs a bit of computation power of the SVN server).
|
SVN pre-commit hook to reject Python files with inconsistent tab usage
|
The Python interpreter can be started with -tt to raise a TabError exception if the interpreted file has inconsistent tab usage.
I'm trying to write a pre-commit hook for SVN that rejects files that raise this exception. I can pass the file being committed to python -tt but my problem is that the file is also executed, besides being checked. Is there a way to tell Python "just analyze the file, don't run it"? Or maybe some other approach would be better for accomplishing what I want.
|
[
"You can do this using the py_compile module:\n$ python -tt -c \"import py_compile; py_compile.compile('test.py', doraise=True)\"\n\nThe doraise=True will raise an exception and return with a nonzero exit code that you can easily test in your pre-commit hook.\n",
"The preferred tab usage in Python is no tab usage at all (use four spaces for indentation). If that is your coding style then the problem may be reduced to checking if there are any tabs in the code. And this can be easily done with simple regexp, even with 'grep', so there is no even need to run the interpreter.\nThe 'py_compile' way have other advantage, though: it also checks Python code syntax, which may be desirable (though costs a bit of computation power of the SVN server).\n"
] |
[
6,
2
] |
[] |
[] |
[
"pre_commit_hook",
"python",
"svn"
] |
stackoverflow_0002341011_pre_commit_hook_python_svn.txt
|
Q:
Logout functionality in django
All
In django project if 2 template windows are opened and if logout is triggered in 1 window the other window cookies are not cleared.How to delete the cookies also so that the logout will be triggered.
def logout(request):
//request = redirect('webbie.home.views.loginpage')
//request.delete_cookie('user_location')
return auth_logout(request)
Thanks..
A:
In the cookie you should only store a session key. The server then needs to keep track of all session keys and associate expire date/time and user-account with them. For every user that logs in they should be given a new session key, though you may allow multiple logins/user-account. So when you check if the cookie is valid you need to consult your sever DB and see if you have this session key and that it's valid. If you now want to "kill" all active sessions for a user-account when one of them logs out you just need to remove all session keys form your servers session key list.
You should try to not store sensitive data in cookies, a session key is enough and then have the server associate data to this key. Now you have control of the signed in users.
More Django session info on there documentation: http://docs.djangoproject.com/en/dev/topics/http/sessions/
A:
What do you mean exactly? You mean if you have to windows open with the same website, and you log out in one window, you are not logged out in the other window? I doubt that.
Of course you are not redirected in the other window to a certain page because you haven't done anything in this specific window. But if you click a link that is only available for logged in users, you should be redirected to a login page.
And no, you cannot detect on client side if a user logged out from another site, at least not without Ajax and some custom checks.
|
Logout functionality in django
|
All
In django project if 2 template windows are opened and if logout is triggered in 1 window the other window cookies are not cleared.How to delete the cookies also so that the logout will be triggered.
def logout(request):
//request = redirect('webbie.home.views.loginpage')
//request.delete_cookie('user_location')
return auth_logout(request)
Thanks..
|
[
"In the cookie you should only store a session key. The server then needs to keep track of all session keys and associate expire date/time and user-account with them. For every user that logs in they should be given a new session key, though you may allow multiple logins/user-account. So when you check if the cookie is valid you need to consult your sever DB and see if you have this session key and that it's valid. If you now want to \"kill\" all active sessions for a user-account when one of them logs out you just need to remove all session keys form your servers session key list.\nYou should try to not store sensitive data in cookies, a session key is enough and then have the server associate data to this key. Now you have control of the signed in users.\nMore Django session info on there documentation: http://docs.djangoproject.com/en/dev/topics/http/sessions/\n",
"What do you mean exactly? You mean if you have to windows open with the same website, and you log out in one window, you are not logged out in the other window? I doubt that.\nOf course you are not redirected in the other window to a certain page because you haven't done anything in this specific window. But if you click a link that is only available for logged in users, you should be redirected to a login page.\nAnd no, you cannot detect on client side if a user logged out from another site, at least not without Ajax and some custom checks.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002339941_django_python.txt
|
Q:
As a Java programmer learning Python, what should I look out for?
Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I should look out for?
A quick example - when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See here and here if you don't understand the example.)
Someone also provided me with this list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python...? Or things a Java programmer would falsely assume or have trouble understanding?
Edit: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I've only just started with Python so I may not understand all the concepts fully. And a disclaimer - these are going to be very brief, so if you don't understand what it's getting at check out the link.)
A static method in Java does not translate to a Python classmethod
A switch statement in Java translates to a hash table in Python
Don't use XML
Getters and setters are evil (hey, I'm just quoting :) )
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python
(And if you find this question at all interesting, check out the link anyway. :) It's quite good.)
A:
Don't put everything into classes. Python's built-in list and dictionaries will take you far.
Don't worry about keeping one class per module. Divide modules by purpose, not by class.
Use inheritance for behavior, not interfaces. Don't create an "Animal" class for "Dog" and "Cat" to inherit from, just so you can have a generic "make_sound" method.
Just do this:
class Dog(object):
def make_sound(self):
return "woof!"
class Cat(object):
def make_sound(self):
return "meow!"
class LolCat(object):
def make_sound(self):
return "i can has cheezburger?"
A:
The referenced article has some good advice that can easily be misquoted and misunderstood. And some bad advice.
Leave Java behind. Start fresh. "do not trust your [Java-based] instincts". Saying things are "counter-intuitive" is a bad habit in any programming discipline. When learning a new language, start fresh, and drop your habits. Your intuition must be wrong.
Languages are different. Otherwise, they'd be the same language with different syntax, and there'd be simple translators. Because there are not simple translators, there's no simple mapping. That means that intuition is unhelpful and dangerous.
"A static method in Java does not translate to a Python classmethod." This kind of thing is really limited and unhelpful. Python has a staticmethod decorator. It also has a classmethod decorator, for which Java has no equivalent.
This point, BTW, also included the much more helpful advice on not needlessly wrapping everything in a class. "The idiomatic translation of a Java static method is usually a module-level function".
The Java switch statement in Java can be implemented several ways. First, and foremost, it's usually an if elif elif elif construct. The article is unhelpful in this respect. If you're absolutely sure this is too slow (and can prove it) you can use a Python dictionary as a slightly faster mapping from value to block of code. Blindly translating switch to dictionary (without thinking) is really bad advice.
Don't use XML. Doesn't make sense when taken out of context. In context it means don't rely on XML to add flexibility. Java relies on describing stuff in XML; WSDL files, for example, repeat information that's obvious from inspecting the code. Python relies on introspection instead of restating everything in XML.
But Python has excellent XML processing libraries. Several.
Getters and setters are not required in Python they way they're required in Java. First, you have better introspection in Python, so you don't need getters and setters to help make dynamic bean objects. (For that, you use collections.namedtuple).
However, you have the property decorator which will bundle getters (and setters) into an attribute-like construct. The point is that Python prefers naked attributes; when necessary, we can bundle getters and setters to appear as if there's a simple attribute.
Also, Python has descriptor classes if properties aren't sophisticated enough.
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python. Correct. Python uses optional arguments instead of method overloading.
The bullet point went on to talk about closure; that isn't as helpful as the simple advice to use default argument values wisely.
A:
One thing you might be used to in Java that you won't find in Python is strict privacy. This is not so much something to look out for as it is something not to look for (I am embarrassed by how long I searched for a Python equivalent to 'private' when I started out!). Instead, Python has much more transparency and easier introspection than Java. This falls under what is sometimes described as the "we're all consenting adults here" philosophy. There are a few conventions and language mechanisms to help prevent accidental use of "unpublic" methods and so forth, but the whole mindset of information hiding is virtually absent in Python.
A:
The biggest one I can think of is not understanding or not fully utilizing duck typing. In Java you're required to specify very explicit and detailed type information upfront. In Python typing is both dynamic and largely implicit. The philosophy is that you should be thinking about your program at a higher level than nominal types. For example, in Python, you don't use inheritance to model substitutability. Substitutability comes by default as a result of duck typing. Inheritance is only a programmer convenience for reusing implementation.
Similarly, the Pythonic idiom is "beg forgiveness, don't ask permission". Explicit typing is considered evil. Don't check whether a parameter is a certain type upfront. Just try to do whatever you need to do with the parameter. If it doesn't conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly. If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you've gained flexibility for free.
A:
The most important thing, from a Java POV, is that it's perfectly ok to not make classes for everything. There are many situations where a procedural approach is simpler and shorter.
The next most important thing is that you will have to get over the notion that the type of an object controls what it may do; rather, the code controls what objects must be able to support at runtime (this is by virtue of duck-typing).
Oh, and use native lists and dicts (not customized descendants) as far as possible.
A:
The way exceptions are treated in Python is different from
how they are treated in Java. While in Java the advice
is to use exceptions only for exceptional conditions this is not
so with Python.
In Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.
As Alex Martelli puts in his book Python in a Nutshell
the exception mechanism with other languages (and applicable to Java)
is LBYL (Look Before You Leap) :
is to check in advance, before attempting an operation, for all circumstances that might make the operation invalid.
Where as with Python the approach is EAFP (it's easier to Ask for forgiveness than permission)
A:
A corrollary to "Don't use classes for everything": callbacks.
The Java way for doing callbacks relies on passing objects that implement the callback interface (for example ActionListener with its actionPerformed() method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:
def handler():
print("click!")
button.onclick(handler)
Or even lambdas:
button.onclick(lambda: print("click!\n"))
|
As a Java programmer learning Python, what should I look out for?
|
Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I should look out for?
A quick example - when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See here and here if you don't understand the example.)
Someone also provided me with this list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python...? Or things a Java programmer would falsely assume or have trouble understanding?
Edit: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I've only just started with Python so I may not understand all the concepts fully. And a disclaimer - these are going to be very brief, so if you don't understand what it's getting at check out the link.)
A static method in Java does not translate to a Python classmethod
A switch statement in Java translates to a hash table in Python
Don't use XML
Getters and setters are evil (hey, I'm just quoting :) )
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python
(And if you find this question at all interesting, check out the link anyway. :) It's quite good.)
|
[
"\nDon't put everything into classes. Python's built-in list and dictionaries will take you far.\nDon't worry about keeping one class per module. Divide modules by purpose, not by class.\nUse inheritance for behavior, not interfaces. Don't create an \"Animal\" class for \"Dog\" and \"Cat\" to inherit from, just so you can have a generic \"make_sound\" method. \n\nJust do this:\nclass Dog(object):\n def make_sound(self):\n return \"woof!\"\n\nclass Cat(object):\n def make_sound(self):\n return \"meow!\"\n\nclass LolCat(object):\n def make_sound(self):\n return \"i can has cheezburger?\"\n\n",
"The referenced article has some good advice that can easily be misquoted and misunderstood. And some bad advice.\nLeave Java behind. Start fresh. \"do not trust your [Java-based] instincts\". Saying things are \"counter-intuitive\" is a bad habit in any programming discipline. When learning a new language, start fresh, and drop your habits. Your intuition must be wrong. \nLanguages are different. Otherwise, they'd be the same language with different syntax, and there'd be simple translators. Because there are not simple translators, there's no simple mapping. That means that intuition is unhelpful and dangerous.\n\n\"A static method in Java does not translate to a Python classmethod.\" This kind of thing is really limited and unhelpful. Python has a staticmethod decorator. It also has a classmethod decorator, for which Java has no equivalent. \nThis point, BTW, also included the much more helpful advice on not needlessly wrapping everything in a class. \"The idiomatic translation of a Java static method is usually a module-level function\".\nThe Java switch statement in Java can be implemented several ways. First, and foremost, it's usually an if elif elif elif construct. The article is unhelpful in this respect. If you're absolutely sure this is too slow (and can prove it) you can use a Python dictionary as a slightly faster mapping from value to block of code. Blindly translating switch to dictionary (without thinking) is really bad advice.\nDon't use XML. Doesn't make sense when taken out of context. In context it means don't rely on XML to add flexibility. Java relies on describing stuff in XML; WSDL files, for example, repeat information that's obvious from inspecting the code. Python relies on introspection instead of restating everything in XML.\nBut Python has excellent XML processing libraries. Several.\nGetters and setters are not required in Python they way they're required in Java. First, you have better introspection in Python, so you don't need getters and setters to help make dynamic bean objects. (For that, you use collections.namedtuple). \nHowever, you have the property decorator which will bundle getters (and setters) into an attribute-like construct. The point is that Python prefers naked attributes; when necessary, we can bundle getters and setters to appear as if there's a simple attribute.\nAlso, Python has descriptor classes if properties aren't sophisticated enough.\nCode duplication is often a necessary evil in Java (e.g. method overloading), but not in Python. Correct. Python uses optional arguments instead of method overloading. \nThe bullet point went on to talk about closure; that isn't as helpful as the simple advice to use default argument values wisely.\n\n",
"One thing you might be used to in Java that you won't find in Python is strict privacy. This is not so much something to look out for as it is something not to look for (I am embarrassed by how long I searched for a Python equivalent to 'private' when I started out!). Instead, Python has much more transparency and easier introspection than Java. This falls under what is sometimes described as the \"we're all consenting adults here\" philosophy. There are a few conventions and language mechanisms to help prevent accidental use of \"unpublic\" methods and so forth, but the whole mindset of information hiding is virtually absent in Python.\n",
"The biggest one I can think of is not understanding or not fully utilizing duck typing. In Java you're required to specify very explicit and detailed type information upfront. In Python typing is both dynamic and largely implicit. The philosophy is that you should be thinking about your program at a higher level than nominal types. For example, in Python, you don't use inheritance to model substitutability. Substitutability comes by default as a result of duck typing. Inheritance is only a programmer convenience for reusing implementation.\nSimilarly, the Pythonic idiom is \"beg forgiveness, don't ask permission\". Explicit typing is considered evil. Don't check whether a parameter is a certain type upfront. Just try to do whatever you need to do with the parameter. If it doesn't conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly. If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you've gained flexibility for free.\n",
"The most important thing, from a Java POV, is that it's perfectly ok to not make classes for everything. There are many situations where a procedural approach is simpler and shorter.\nThe next most important thing is that you will have to get over the notion that the type of an object controls what it may do; rather, the code controls what objects must be able to support at runtime (this is by virtue of duck-typing). \nOh, and use native lists and dicts (not customized descendants) as far as possible.\n",
"The way exceptions are treated in Python is different from \nhow they are treated in Java. While in Java the advice\nis to use exceptions only for exceptional conditions this is not\nso with Python. \nIn Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.\nAs Alex Martelli puts in his book Python in a Nutshell\nthe exception mechanism with other languages (and applicable to Java) \nis LBYL (Look Before You Leap) : \nis to check in advance, before attempting an operation, for all circumstances that might make the operation invalid. \nWhere as with Python the approach is EAFP (it's easier to Ask for forgiveness than permission)\n",
"A corrollary to \"Don't use classes for everything\": callbacks. \nThe Java way for doing callbacks relies on passing objects that implement the callback interface (for example ActionListener with its actionPerformed() method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:\ndef handler():\n print(\"click!\")\nbutton.onclick(handler)\n\nOr even lambdas:\nbutton.onclick(lambda: print(\"click!\\n\")) \n\n"
] |
[
25,
23,
14,
10,
7,
6,
1
] |
[] |
[] |
[
"java",
"python"
] |
stackoverflow_0002339371_java_python.txt
|
Q:
unladen-swallow with numpy/scipy
has anyone used unladen-swallow with numpy/scipy for numeric/scientific applications? Is it significantly faster in your experience? Any opinions would be great.
A:
Nobody has extensive experience with Unladen Swallow yet (except the developers), so it's going to be difficult to find many people who can discuss it. Also, with the talk of merging Unladen Swallow (which is built using LLVM) with the CPython runtime, things are going to be something of a moving target until everything's more stable.
There are benchmarks available for Unladen Swallow, but numpy and scipy aren't included. As the developers themselves explain: "... the performance of extension modules like numpy is uninteresting since numpy's core routines are implemented in C".
In short, if you're writing good code for numpy and scipy, your code won't run "significantly faster" under Unladen Swallow, since it's already running below the virtual machine level. If you're writing bad code for numpy and scipy, you need to fix your code, then refer back to the first sentence.
A:
It should be faster. I have not tested it myself, but i just got back from pycon and they had a talk about unladen-swallow in which they mentioned the performance increase with numpy and other packages. You can watch the talk here.
A:
On the question, not an answer:
Total runtime = python + numpy + interface,
cpython/unladenswallow + mostlyC + interface.
Without real data on how these 3 split -- 20 70 10, 40 40 20 ? and that for > 1 benchmark,
there's no way of telling which way is up.
|
unladen-swallow with numpy/scipy
|
has anyone used unladen-swallow with numpy/scipy for numeric/scientific applications? Is it significantly faster in your experience? Any opinions would be great.
|
[
"Nobody has extensive experience with Unladen Swallow yet (except the developers), so it's going to be difficult to find many people who can discuss it. Also, with the talk of merging Unladen Swallow (which is built using LLVM) with the CPython runtime, things are going to be something of a moving target until everything's more stable.\nThere are benchmarks available for Unladen Swallow, but numpy and scipy aren't included. As the developers themselves explain: \"... the performance of extension modules like numpy is uninteresting since numpy's core routines are implemented in C\".\nIn short, if you're writing good code for numpy and scipy, your code won't run \"significantly faster\" under Unladen Swallow, since it's already running below the virtual machine level. If you're writing bad code for numpy and scipy, you need to fix your code, then refer back to the first sentence.\n",
"It should be faster. I have not tested it myself, but i just got back from pycon and they had a talk about unladen-swallow in which they mentioned the performance increase with numpy and other packages. You can watch the talk here.\n",
"On the question, not an answer: \nTotal runtime = python + numpy + interface, \n cpython/unladenswallow + mostlyC + interface.\n\nWithout real data on how these 3 split -- 20 70 10, 40 40 20 ? and that for > 1 benchmark,\nthere's no way of telling which way is up.\n"
] |
[
5,
1,
1
] |
[] |
[] |
[
"numpy",
"optimization",
"python",
"scipy",
"unladen_swallow"
] |
stackoverflow_0002328267_numpy_optimization_python_scipy_unladen_swallow.txt
|
Q:
How do I get started with zc.buildout and Distribute?
I want to use buildout for dependency management, and I hear distribute is the new good way to manage installation of your project.
However, easy tutorials to get started seem to be thin on the ground. The most straight forward I've seen is Jacob Kaplan-Moss's Developing Django apps with zc.buildout (my use case is a web application), but that still isn't very clear as to what each piece of the chain does, and what best practices are.
How do I get going on this stuff? I want to do things right.
A:
I've just started documenting the whole toolchain at http://reinout.vanrees.org/weblog/tags/softwarereleasesseries.html (2010-02-25: still got to write the buildout and the pastescript article).
Basic toolchain idea: use setuptools to package your python code. Like the "developing django apps" article you mention: every application is its own package. Put your code in a directory and add a setup.py. The setup.py contains the version number, name, dependencies and so and you can run it to create a yourproject-0.1.tar.gz, for instance.
Downloading everything ("easy_install xyz") quickly makes a total and utter mess of your system python's site_packages. Probably with incompatible versions. Buildout (and for instance virtualenv) give you an isolated environment: installed packages are only installed local to that virtualenv/buildout.
Mess part 2: which versions do you want? To get any measure of repeatability and reliability, you've got to be able to control the versions you use ("Django 1.0 or 1.1?"). Buildout allows that.
A:
You've probably already found it, but have you checked out the buildout website already?
|
How do I get started with zc.buildout and Distribute?
|
I want to use buildout for dependency management, and I hear distribute is the new good way to manage installation of your project.
However, easy tutorials to get started seem to be thin on the ground. The most straight forward I've seen is Jacob Kaplan-Moss's Developing Django apps with zc.buildout (my use case is a web application), but that still isn't very clear as to what each piece of the chain does, and what best practices are.
How do I get going on this stuff? I want to do things right.
|
[
"I've just started documenting the whole toolchain at http://reinout.vanrees.org/weblog/tags/softwarereleasesseries.html (2010-02-25: still got to write the buildout and the pastescript article).\nBasic toolchain idea: use setuptools to package your python code. Like the \"developing django apps\" article you mention: every application is its own package. Put your code in a directory and add a setup.py. The setup.py contains the version number, name, dependencies and so and you can run it to create a yourproject-0.1.tar.gz, for instance.\nDownloading everything (\"easy_install xyz\") quickly makes a total and utter mess of your system python's site_packages. Probably with incompatible versions. Buildout (and for instance virtualenv) give you an isolated environment: installed packages are only installed local to that virtualenv/buildout.\nMess part 2: which versions do you want? To get any measure of repeatability and reliability, you've got to be able to control the versions you use (\"Django 1.0 or 1.1?\"). Buildout allows that.\n",
"You've probably already found it, but have you checked out the buildout website already?\n"
] |
[
6,
0
] |
[] |
[] |
[
"buildout",
"distribute",
"python"
] |
stackoverflow_0002305723_buildout_distribute_python.txt
|
Q:
how are pgp keys formatted?
i want to write a program in python to simply read pgp keys. however, i cant seem to find any documentation describing how pgp keys are formatted. i dont want to be searching through the source code of open pgp to look for source code that i wont be able to understand.
say i open a public key, remove the top "-----BEGIN PGP PUBLIC KEY BLOCK-----" and bottom "-----END PGP PUBLIC KEY BLOCK-----", and change the data back into bytes, then what? i saw my name and email somewhere in the middle, but i cant see anything else. which part tells the computer the cipher name/value (say rsa = 1, elgamal = 2, etc.) in the string? where is the key size? where is the time-the-key-is-valid-for? in general, how do pkc programs read the public/private keys?
A:
You can read the PGP RFCs (looks like the latest is RFC 4880). But why not use pyme instead?
|
how are pgp keys formatted?
|
i want to write a program in python to simply read pgp keys. however, i cant seem to find any documentation describing how pgp keys are formatted. i dont want to be searching through the source code of open pgp to look for source code that i wont be able to understand.
say i open a public key, remove the top "-----BEGIN PGP PUBLIC KEY BLOCK-----" and bottom "-----END PGP PUBLIC KEY BLOCK-----", and change the data back into bytes, then what? i saw my name and email somewhere in the middle, but i cant see anything else. which part tells the computer the cipher name/value (say rsa = 1, elgamal = 2, etc.) in the string? where is the key size? where is the time-the-key-is-valid-for? in general, how do pkc programs read the public/private keys?
|
[
"You can read the PGP RFCs (looks like the latest is RFC 4880). But why not use pyme instead?\n"
] |
[
3
] |
[] |
[] |
[
"encryption",
"gnupg",
"pgp",
"python"
] |
stackoverflow_0002341486_encryption_gnupg_pgp_python.txt
|
Q:
Python composite pattern exception handling & pylint
I'm implementig a Composite pattern in this way:
1) the "abstract" component is:
class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
2) a leaf:
class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
The Problem is that pylint generates, of course, this warning:
Leaf.__init__: __init__ method from base class 'Component' is not called
but into my Leaf i cannot call for:
def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
without raise of the exception.
Must I ignore pylint warning or there is some bad coding?
A:
Abstract initializers are a bad idea. Your code might evolve so that you want to do some initialization in the root component. And even if you don't why require the implementation of the initializer. For some subclasses an empty initializer would be an acceptable choice.
If you don't want any instances of the Component class around, check for that in the initializer:
class Component(object):
def __init__(self, **kwargs):
assert type(self) != Component, "Component must not be instantiated directly"
class Leaf(Component):
def __init__(self, some, args, **kwargs):
# regular initialization
Component.__init__(self, **kwargs)
A:
Another suggestion to complement the idea of Markus:
If you really must, I suggest that you use __new __ and check for the given object type. When it is "Component" you could fire your exception:
class Component(object):
"""Basic Component Abstraction"""
def __new__(objType, *args, **kwargs):
if objType == Component:
raise NotImplementedError("must be subclassed")
return object.__new__(type, *args, **kwargs)
When a subclass is created, objType will be != Component and all will be fine!
A:
Renaming your class Component to AbstractComponent should help. And don't provide an __init__ method in your base class if it's not supposed to be called by subclasses.
A:
You want to guarantee, that the base class Component is not instanciated. This is a noble guesture common in other programming languages like C++ (where you can make the constructors private or so to prevent direct usage).
But it is not supported in Python. Python does not support all programming notions and also is more "dynamic". So initialization is done in a "Pythonic" way and your notion is not supported thus.
Python is much more based on trust than other languages -- so, for example static variables are not supported and private ones also only in a limited way.
What you could do (when you distrust the users of your module) -- you could hide the base class by naming it "_Component" -- make it an internal secret. But of course this can create other troubles.
A:
Not bad coding as such, but the __init__ of the component is simply not needed. If you want it, you can ignore pylint, but it's a better idea to simply remove the __init__ from Component.
Embrace the dynamicism!
|
Python composite pattern exception handling & pylint
|
I'm implementig a Composite pattern in this way:
1) the "abstract" component is:
class Component(object):
"""Basic Component Abstraction"""
def __init__(self, *args, **kw):
raise NotImplementedError("must be subclassed")
def status(self):
"""Base Abstract method"""
raise NotImplementedError("must be implemented")
2) a leaf:
class Leaf(Component):
"""Basic atomic component
"""
def __init__(self, *args, **kw):
self.dict = {}
def status(self):
"""Retrieves properties
"""
return self.dict
The Problem is that pylint generates, of course, this warning:
Leaf.__init__: __init__ method from base class 'Component' is not called
but into my Leaf i cannot call for:
def __init__(self, *args, **kw):
Component.__init__(self, *args, **kw)
self.dict = {}
without raise of the exception.
Must I ignore pylint warning or there is some bad coding?
|
[
"Abstract initializers are a bad idea. Your code might evolve so that you want to do some initialization in the root component. And even if you don't why require the implementation of the initializer. For some subclasses an empty initializer would be an acceptable choice.\nIf you don't want any instances of the Component class around, check for that in the initializer:\nclass Component(object):\n def __init__(self, **kwargs):\n assert type(self) != Component, \"Component must not be instantiated directly\"\n\nclass Leaf(Component):\n def __init__(self, some, args, **kwargs):\n # regular initialization\n Component.__init__(self, **kwargs)\n\n",
"Another suggestion to complement the idea of Markus:\nIf you really must, I suggest that you use __new __ and check for the given object type. When it is \"Component\" you could fire your exception:\nclass Component(object):\n\"\"\"Basic Component Abstraction\"\"\"\n\ndef __new__(objType, *args, **kwargs):\n if objType == Component:\n raise NotImplementedError(\"must be subclassed\")\n return object.__new__(type, *args, **kwargs)\n\nWhen a subclass is created, objType will be != Component and all will be fine!\n",
"Renaming your class Component to AbstractComponent should help. And don't provide an __init__ method in your base class if it's not supposed to be called by subclasses. \n",
"You want to guarantee, that the base class Component is not instanciated. This is a noble guesture common in other programming languages like C++ (where you can make the constructors private or so to prevent direct usage).\nBut it is not supported in Python. Python does not support all programming notions and also is more \"dynamic\". So initialization is done in a \"Pythonic\" way and your notion is not supported thus.\nPython is much more based on trust than other languages -- so, for example static variables are not supported and private ones also only in a limited way.\nWhat you could do (when you distrust the users of your module) -- you could hide the base class by naming it \"_Component\" -- make it an internal secret. But of course this can create other troubles.\n",
"Not bad coding as such, but the __init__ of the component is simply not needed. If you want it, you can ignore pylint, but it's a better idea to simply remove the __init__ from Component.\nEmbrace the dynamicism!\n"
] |
[
5,
2,
2,
1,
1
] |
[] |
[] |
[
"composite",
"pylint",
"python"
] |
stackoverflow_0001091337_composite_pylint_python.txt
|
Q:
customize the django admin panel?
I want to change the django bydefault admin panel title bar where wirte the django administration.
Actually I want to replace the django administration with the my site name.
A:
I found out the solution:
Make the file in notpad
{% extends "admin/base.html" %}
{% load i18n %}
{% block title %}{{ title }} | {% trans 'Your Customize name' %}{% endblock %}
{% block branding %}
<h1 id="site-name">{% trans 'Your Customize name administration' %}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
and then save the above file with the name "base_site.html" in the folder name "admin" of your project directory.
Also give the path of admin parent directory in the settings.py file under TEMPLATE_DIRS in inverted commas.
A:
Have a look a django-grappelli : http://code.google.com/p/django-grappelli/
Or
Do it yourself : http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates
|
customize the django admin panel?
|
I want to change the django bydefault admin panel title bar where wirte the django administration.
Actually I want to replace the django administration with the my site name.
|
[
"I found out the solution:\nMake the file in notpad \n{% extends \"admin/base.html\" %}\n{% load i18n %}\n\n{% block title %}{{ title }} | {% trans 'Your Customize name' %}{% endblock %}\n\n{% block branding %}\n<h1 id=\"site-name\">{% trans 'Your Customize name administration' %}</h1>\n{% endblock %}\n\n{% block nav-global %}{% endblock %}\n\nand then save the above file with the name \"base_site.html\" in the folder name \"admin\" of your project directory. \nAlso give the path of admin parent directory in the settings.py file under TEMPLATE_DIRS in inverted commas.\n",
"Have a look a django-grappelli : http://code.google.com/p/django-grappelli/\nOr\nDo it yourself : http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates\n"
] |
[
6,
2
] |
[] |
[] |
[
"django",
"django_admin",
"python"
] |
stackoverflow_0002333360_django_django_admin_python.txt
|
Q:
Can't modify value returned by time.time() in Python code embedded in C++
I'm facing a very strange problem.
The following code:
import time
target_time = time.time() + 30.0
doesn't work in Python code called from C++ (embedding)!
target_time has the same value as time.time() and any attempt to modify it leaves the value unchanged in a pdb console...
alt text http://dl.dropbox.com/u/3545118/time_bug.png
It happens after I've called root.initialise() in Ogre3D graphics engine, but only when using Direct3D, not when using OpenGL.
So this might be related to Direct3D...
A:
Found the answer in that thread:
http://www.ogre3d.org/forums/viewtopic.php?f=1&t=55013&p=373940&hilit=D3DCREATE_FPU_PRESERVE#p373940
http://msdn.microsoft.com/en-us/library/ee416457%28VS.85%29.aspx
D3DCREATE_FPU_PRESERVE Set the precision for Direct3D floating-point calculations to the precision used by the calling thread. If you do not specify this flag, Direct3D defaults to single-precision round-to-nearest mode for two reasons:
Double-precision mode will reduce Direct3D performance.
Portions of Direct3D assume floating-point unit exceptions are masked; unmasking these exceptions may result in undefined behavior.
|
Can't modify value returned by time.time() in Python code embedded in C++
|
I'm facing a very strange problem.
The following code:
import time
target_time = time.time() + 30.0
doesn't work in Python code called from C++ (embedding)!
target_time has the same value as time.time() and any attempt to modify it leaves the value unchanged in a pdb console...
alt text http://dl.dropbox.com/u/3545118/time_bug.png
It happens after I've called root.initialise() in Ogre3D graphics engine, but only when using Direct3D, not when using OpenGL.
So this might be related to Direct3D...
|
[
"Found the answer in that thread:\nhttp://www.ogre3d.org/forums/viewtopic.php?f=1&t=55013&p=373940&hilit=D3DCREATE_FPU_PRESERVE#p373940\nhttp://msdn.microsoft.com/en-us/library/ee416457%28VS.85%29.aspx\nD3DCREATE_FPU_PRESERVE Set the precision for Direct3D floating-point calculations to the precision used by the calling thread. If you do not specify this flag, Direct3D defaults to single-precision round-to-nearest mode for two reasons:\n\nDouble-precision mode will reduce Direct3D performance.\nPortions of Direct3D assume floating-point unit exceptions are masked; unmasking these exceptions may result in undefined behavior.\n\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"direct3d",
"embedding",
"ogre3d",
"python"
] |
stackoverflow_0002333848_c++_direct3d_embedding_ogre3d_python.txt
|
Q:
Django 1.1.1 chokes on multipart/form-data
Initial story
I'm trying to implement file upload using a simple form (I'm pasting stripped version, but all important parts are included):
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="up_file" size="50">
<input type="hidden" name="cpk" value="{{c.pk}}">
<input type="submit" name="btn_submit">
</form>
Now, server-side script running under wsgi was receiving strange values for "cpk" field and request.FILES was empty empty request.FILES and request.POST dictionaries, so I decided to switch to development server for debugging.
Surprisingly, ipdb debugger hangs after typing both request.POST and request.FILES and pressing enter... On the other hand, when I remove enctype="multipart/form-data" from tag, I'm able to check both request.POST and request.FILES, but of course request.FILES is empty then.
(Also wsgi version seems to be healed by removal of enctype="multipart/form-data"...)
Update
I tried all combinations of Opera 10//Firefox 3.5, enctype="multipart/form-data"//no multipart/form-data and dev server//mod_wsgi. The result is that it's enctype="multipart/form-data" that breaks the show. So now I'm going to check Django bugtracker if it's a known issue.
Meantime, maybe someone here can point me in the right direction
A:
You may need to provide your view and form code as we use form uploads with enctype="multipart/form-data" in Django 1.1.1 with great success.
The following dummy app, for example, works perfectly in the dev server.
views.py
from django import forms
from django.shortcuts import render_to_response
class UploadForm(forms.Form):
cpk = forms.CharField(max_length=256)
f = forms.FileField()
def my_upload_view(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
print "Got cpk",form.cleaned_data['cpk']
print "Got file",request.FILES['f'].read()
else:
form = UploadForm()
return render_to_response('upload.html', {'form':form})
upload.html
<html>
<body>
<form enctype="multipart/form-data" method="post">
{{ form.f }}
{{ form.cpk }}
<input type="submit" />
</form>
</body>
</html>
I'm using the django form instance to render the file input, but it renders the very common <input type="file" name="f" id="id_f" />.
Using this sample, I get the content of the file (I've tested using a simple text file) printed to the terminal from my dev server. The few gotchas and tests I can recommend are:
ensure that the file you are uploading is less than settings.FILE_UPLOAD_MAX_MEMORY_SIZE (the default is 2.5 MB)
double-check that you haven't defined any custom file upload handlers that may be breaking the upload process (settings.FILE_UPLOAD_HANDLERS)
try uploading a very simple file (like a small text file) to see if the issue still persists with something basic
use a tool to inspect the raw HTTP request/response traffic (firebug will do this for you, and there are some stand-alone apps that will act as a proxy to help you here too)... sometimes the solution will jump out when you can see the raw traffic.
In case you haven't found them yet, the django file upload docs have a fair number of examples.
|
Django 1.1.1 chokes on multipart/form-data
|
Initial story
I'm trying to implement file upload using a simple form (I'm pasting stripped version, but all important parts are included):
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="up_file" size="50">
<input type="hidden" name="cpk" value="{{c.pk}}">
<input type="submit" name="btn_submit">
</form>
Now, server-side script running under wsgi was receiving strange values for "cpk" field and request.FILES was empty empty request.FILES and request.POST dictionaries, so I decided to switch to development server for debugging.
Surprisingly, ipdb debugger hangs after typing both request.POST and request.FILES and pressing enter... On the other hand, when I remove enctype="multipart/form-data" from tag, I'm able to check both request.POST and request.FILES, but of course request.FILES is empty then.
(Also wsgi version seems to be healed by removal of enctype="multipart/form-data"...)
Update
I tried all combinations of Opera 10//Firefox 3.5, enctype="multipart/form-data"//no multipart/form-data and dev server//mod_wsgi. The result is that it's enctype="multipart/form-data" that breaks the show. So now I'm going to check Django bugtracker if it's a known issue.
Meantime, maybe someone here can point me in the right direction
|
[
"You may need to provide your view and form code as we use form uploads with enctype=\"multipart/form-data\" in Django 1.1.1 with great success.\nThe following dummy app, for example, works perfectly in the dev server.\nviews.py\nfrom django import forms\nfrom django.shortcuts import render_to_response\n\nclass UploadForm(forms.Form):\n cpk = forms.CharField(max_length=256)\n f = forms.FileField()\n\ndef my_upload_view(request):\n if request.method == 'POST':\n form = UploadForm(request.POST, request.FILES)\n if form.is_valid():\n print \"Got cpk\",form.cleaned_data['cpk']\n print \"Got file\",request.FILES['f'].read()\n else:\n form = UploadForm()\n return render_to_response('upload.html', {'form':form})\n\nupload.html\n<html>\n<body>\n <form enctype=\"multipart/form-data\" method=\"post\">\n {{ form.f }}\n {{ form.cpk }}\n <input type=\"submit\" />\n </form>\n</body>\n</html>\n\nI'm using the django form instance to render the file input, but it renders the very common <input type=\"file\" name=\"f\" id=\"id_f\" />.\nUsing this sample, I get the content of the file (I've tested using a simple text file) printed to the terminal from my dev server. The few gotchas and tests I can recommend are:\n\nensure that the file you are uploading is less than settings.FILE_UPLOAD_MAX_MEMORY_SIZE (the default is 2.5 MB)\ndouble-check that you haven't defined any custom file upload handlers that may be breaking the upload process (settings.FILE_UPLOAD_HANDLERS)\ntry uploading a very simple file (like a small text file) to see if the issue still persists with something basic\nuse a tool to inspect the raw HTTP request/response traffic (firebug will do this for you, and there are some stand-alone apps that will act as a proxy to help you here too)... sometimes the solution will jump out when you can see the raw traffic.\n\nIn case you haven't found them yet, the django file upload docs have a fair number of examples.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"file_upload",
"python"
] |
stackoverflow_0002341314_django_file_upload_python.txt
|
Q:
wxPython Application.DoEvents() equivalent?
Is there an Application.DoEvents() equivalent in wxPython?
I am creating a form, then doing a slow I/O event, and the form is only partially drawn until the event finishes. I'd like to have the form fully drawn before the I/O starts.
I've tried self.Refresh(), but it has no effect.
A:
wx.Yield or wx.SafeYield
Although you should really use a separate thread to do the I/O and use wx.CallAfter to post updates to the GUI thread.
I usually use a pattern like this:
def start_work(self):
thread = threading.Thread(target=self.do_work, args=(args, go, here))
thread.setDaemon(True)
thread.start()
def do_work(self, args, go, here):
# do work here
# wx.CallAfter will call the specified function on the GUI thread
# and it's safe to call from a separate thread
wx.CallAfter(self.work_completed, result, args, here)
def work_completed(self, result, args, here):
# use result args to update GUI controls here
self.text.SetLabel(result)
You would call start_work from the GUI, for example on an EVT_BUTTON event to start the work. do_work is run on a separate thread but it cannot do anything GUI related because that has to be done on the GUI thread. So you use wx.CallAfter to run a function on the GUI thread, and you can pass it arguments from the work thread.
|
wxPython Application.DoEvents() equivalent?
|
Is there an Application.DoEvents() equivalent in wxPython?
I am creating a form, then doing a slow I/O event, and the form is only partially drawn until the event finishes. I'd like to have the form fully drawn before the I/O starts.
I've tried self.Refresh(), but it has no effect.
|
[
"wx.Yield or wx.SafeYield\nAlthough you should really use a separate thread to do the I/O and use wx.CallAfter to post updates to the GUI thread.\nI usually use a pattern like this:\ndef start_work(self):\n thread = threading.Thread(target=self.do_work, args=(args, go, here))\n thread.setDaemon(True)\n thread.start()\ndef do_work(self, args, go, here):\n # do work here\n # wx.CallAfter will call the specified function on the GUI thread\n # and it's safe to call from a separate thread\n wx.CallAfter(self.work_completed, result, args, here)\ndef work_completed(self, result, args, here):\n # use result args to update GUI controls here\n self.text.SetLabel(result)\n\nYou would call start_work from the GUI, for example on an EVT_BUTTON event to start the work. do_work is run on a separate thread but it cannot do anything GUI related because that has to be done on the GUI thread. So you use wx.CallAfter to run a function on the GUI thread, and you can pass it arguments from the work thread.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"wxpython",
"wxwidgets"
] |
stackoverflow_0002342183_python_wxpython_wxwidgets.txt
|
Q:
capture using v4l2 and display preview using gstreamer
How to pass the buffer/userpointer to gstreamer after Q_BUF, STREAM_ON, DQ_BUF.
I tried using PIL's method frombuffer, but with no success. so I want to use gst sink now.
Should I use gst.parse_launch() and how?
Have anybody done it?
A:
The source code to Cheese tells all. http://projects.gnome.org/cheese/
|
capture using v4l2 and display preview using gstreamer
|
How to pass the buffer/userpointer to gstreamer after Q_BUF, STREAM_ON, DQ_BUF.
I tried using PIL's method frombuffer, but with no success. so I want to use gst sink now.
Should I use gst.parse_launch() and how?
Have anybody done it?
|
[
"The source code to Cheese tells all. http://projects.gnome.org/cheese/\n"
] |
[
0
] |
[] |
[] |
[
"gstreamer",
"python",
"v4l2"
] |
stackoverflow_0002133822_gstreamer_python_v4l2.txt
|
Q:
Python's c api and __add__ calls
I am writing a binding system that exposes classes and functions to python in a slightly unusual way.
Normally one would create a python type and provide a list of functions that represent the methods of that type, and then allow python to use its generic tp_getattro function to select the right one.
For reasons I wont go into here, I can't do it this way, and must provide my own tp_getattro function, that selects methods from elsewhere and returns my own 'bound method' wrapper. This works fine, but means that a types methods are not listed in its dictionary (so dir(MyType()) doesn't show anything interesting).
The problem is that I cannot seem to get __add__ methods working. see the following sample:
>>> from mymod import Vec3
>>> v=Vec3()
>>> v.__add__
<Bound Method of a mymod Class object at 0xb754e080>
>>> v.__add__(v)
<mymod.Vec3 object at 0xb751d710>
>>> v+v
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'mymod.Vec3' and 'mymod.Vec3'
As you can see, Vec3 has an __add__ method which can be called, but python's + refuses to use it.
How can I get python to use it? How does the + operator actually work in python, and what method does it use to see if you can add two arbitrary objects?
Thanks.
(P.S. I am aware of other systems such as Boost.Python and SWIG which do this automatically, and I have good reason for not using them, however wonderful they may be.)
A:
Do you have an nb_add in your type's number methods structure (pointed by field tp_as_number of your type object)?
|
Python's c api and __add__ calls
|
I am writing a binding system that exposes classes and functions to python in a slightly unusual way.
Normally one would create a python type and provide a list of functions that represent the methods of that type, and then allow python to use its generic tp_getattro function to select the right one.
For reasons I wont go into here, I can't do it this way, and must provide my own tp_getattro function, that selects methods from elsewhere and returns my own 'bound method' wrapper. This works fine, but means that a types methods are not listed in its dictionary (so dir(MyType()) doesn't show anything interesting).
The problem is that I cannot seem to get __add__ methods working. see the following sample:
>>> from mymod import Vec3
>>> v=Vec3()
>>> v.__add__
<Bound Method of a mymod Class object at 0xb754e080>
>>> v.__add__(v)
<mymod.Vec3 object at 0xb751d710>
>>> v+v
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'mymod.Vec3' and 'mymod.Vec3'
As you can see, Vec3 has an __add__ method which can be called, but python's + refuses to use it.
How can I get python to use it? How does the + operator actually work in python, and what method does it use to see if you can add two arbitrary objects?
Thanks.
(P.S. I am aware of other systems such as Boost.Python and SWIG which do this automatically, and I have good reason for not using them, however wonderful they may be.)
|
[
"Do you have an nb_add in your type's number methods structure (pointed by field tp_as_number of your type object)?\n"
] |
[
4
] |
[] |
[] |
[
"api",
"python"
] |
stackoverflow_0002342416_api_python.txt
|
Q:
In a MVC patterned framework where would a screen-scraping module be located?
In a MVC patterned framework where would a screen-scraping module most logically be located? In the model or the controller? Or is it completely outside of this pattern?
A:
You can call it as you might a model if you design it to behave like one. Then it can be easily used within a controller:
def update
@company = Company.find(params[:id])
@scraper = Scraper.find(:page => some_url, :method => :rip)
@scraper.product_details.each do |params|
@company.products.create(params)
end
end
It is always convenient when you design the output format of your scraper to be compatible with some other object, such as the column mapping of your persistent storage.
It's often handy to have "model-like" objects. In this case, you can think of a scraper as an interface to another web site instead of a database, and in that respect it is not unlike ActiveResource. There's no rule that a model has to be built off of ActiveRecord.
A:
In a sense, the screen-scraper is the user of the application -- I'd think it would be a piece outside the MVC that interacts with the controller, just like a web page sends information to the controller. This would make it easy to put a web page over it if the interface changes.
A:
I presume the scraper is only used to collect data.
if the data is scraped and stored, this process does not simply drop into either M V or C. You could run this scrapping process as a cron job on intervals you define, store the data and then define models to access the data.
i wouldn't recommend calling the scrapping process every-time the controller requests the model, unless you are caching the scrap request.
EDIT:
the cron could be a controller, but not publicly callable.
A:
It depends on how you are planning on implementing the scraper. If you are going to have a UI where you click a button to scrape a screen then it is going to be in all three (M, V, and C). If it is going to be a background process (like mentioned before) it should be in M and C.
|
In a MVC patterned framework where would a screen-scraping module be located?
|
In a MVC patterned framework where would a screen-scraping module most logically be located? In the model or the controller? Or is it completely outside of this pattern?
|
[
"You can call it as you might a model if you design it to behave like one. Then it can be easily used within a controller:\ndef update\n @company = Company.find(params[:id])\n\n @scraper = Scraper.find(:page => some_url, :method => :rip)\n\n @scraper.product_details.each do |params|\n @company.products.create(params)\n end\nend\n\nIt is always convenient when you design the output format of your scraper to be compatible with some other object, such as the column mapping of your persistent storage.\nIt's often handy to have \"model-like\" objects. In this case, you can think of a scraper as an interface to another web site instead of a database, and in that respect it is not unlike ActiveResource. There's no rule that a model has to be built off of ActiveRecord.\n",
"In a sense, the screen-scraper is the user of the application -- I'd think it would be a piece outside the MVC that interacts with the controller, just like a web page sends information to the controller. This would make it easy to put a web page over it if the interface changes. \n",
"I presume the scraper is only used to collect data.\nif the data is scraped and stored, this process does not simply drop into either M V or C. You could run this scrapping process as a cron job on intervals you define, store the data and then define models to access the data.\ni wouldn't recommend calling the scrapping process every-time the controller requests the model, unless you are caching the scrap request.\nEDIT:\nthe cron could be a controller, but not publicly callable.\n",
"It depends on how you are planning on implementing the scraper. If you are going to have a UI where you click a button to scrape a screen then it is going to be in all three (M, V, and C). If it is going to be a background process (like mentioned before) it should be in M and C.\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"model_view_controller",
"python",
"ruby_on_rails"
] |
stackoverflow_0002342033_model_view_controller_python_ruby_on_rails.txt
|
Q:
Create new class object
I have 2 class in python cl1 in f1.py file and cl2 in f2.py file. I wrote import f2
import f2
class cl1:
a = f2.cl2()
But i see error in a = f2.cl2(): module object has no attribute 'cl2'
Why?
Thank you.
A:
sorry, i was wrong:
your problem is probably that you have a circular import: f1 imports f2 and vice versa.
check your design, as it usually should be possible to design your software without a circular import.
see: this
A:
The following code works just fine (if you're using Python 3 you can omit the (object) parts, but in Python 2 you should leave them in -- they're not responsible for your bug, but if you get used to omitting them you'll have strange problems in the future as your code grows...):
f2.py is:
class cl2(object):
pass
f1.py is:
import f2
class cl1(object):
a = f2.cl2()
If your code is not working, it must be different from this. Please confirm that this simple code is working for you, then show us (by editing your original question, not by posting comments or "answers") how your non-working code differs (lack of imports, circular imports, wrong imports, or whatever else).
|
Create new class object
|
I have 2 class in python cl1 in f1.py file and cl2 in f2.py file. I wrote import f2
import f2
class cl1:
a = f2.cl2()
But i see error in a = f2.cl2(): module object has no attribute 'cl2'
Why?
Thank you.
|
[
"sorry, i was wrong:\nyour problem is probably that you have a circular import: f1 imports f2 and vice versa.\ncheck your design, as it usually should be possible to design your software without a circular import.\nsee: this\n",
"The following code works just fine (if you're using Python 3 you can omit the (object) parts, but in Python 2 you should leave them in -- they're not responsible for your bug, but if you get used to omitting them you'll have strange problems in the future as your code grows...):\nf2.py is:\nclass cl2(object):\n pass\n\nf1.py is:\nimport f2\n\nclass cl1(object):\n a = f2.cl2()\n\nIf your code is not working, it must be different from this. Please confirm that this simple code is working for you, then show us (by editing your original question, not by posting comments or \"answers\") how your non-working code differs (lack of imports, circular imports, wrong imports, or whatever else).\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002340915_python.txt
|
Q:
User location information mapping with lastfm music track history in python
I have two separate python scripts. One is for getting user location
information (which I get from web based geofeed provider.User Gsm is registerd
with that services).Another is for retrieving lastfm user track history.I have already
able to get user location data and user music track information.
Goal is to map those two script in such a way that I could be
able to make relation from those information" Users in certain location are listening certain music in certain time".
Can anybody have nice idea to get this out?Thanks in advance!
A:
Write a third script that import both of the other as modules, and make sure each module's functionality is embodied in a function (as is Python's best practice), not just "floating" as module-level code -- a module's top-level statements should usually be limited to import, from, def, class, and simple assignments of names to constants (possibly initial values for global variables), with all actual logic within functions and classes.
So in your third script, after importing the other two as modules, you have a main function that calls the operating functions of the others to get location and track info, calls a function from standard module datetime (e.g. datetime.datetime.now()) -- or possibly time -- to get the current time, and finally formats all this information in the way you desire and writes it somewhere (where and how do you want to "publish" this info?).
At the end of the script you do
if __name__ == '__main__':
main()
which is the usual Python idiom to ensure the module's main function executes when the file's being used as the main script rather than just being imported from elsewhere.
|
User location information mapping with lastfm music track history in python
|
I have two separate python scripts. One is for getting user location
information (which I get from web based geofeed provider.User Gsm is registerd
with that services).Another is for retrieving lastfm user track history.I have already
able to get user location data and user music track information.
Goal is to map those two script in such a way that I could be
able to make relation from those information" Users in certain location are listening certain music in certain time".
Can anybody have nice idea to get this out?Thanks in advance!
|
[
"Write a third script that import both of the other as modules, and make sure each module's functionality is embodied in a function (as is Python's best practice), not just \"floating\" as module-level code -- a module's top-level statements should usually be limited to import, from, def, class, and simple assignments of names to constants (possibly initial values for global variables), with all actual logic within functions and classes.\nSo in your third script, after importing the other two as modules, you have a main function that calls the operating functions of the others to get location and track info, calls a function from standard module datetime (e.g. datetime.datetime.now()) -- or possibly time -- to get the current time, and finally formats all this information in the way you desire and writes it somewhere (where and how do you want to \"publish\" this info?).\nAt the end of the script you do\nif __name__ == '__main__':\n main()\n\nwhich is the usual Python idiom to ensure the module's main function executes when the file's being used as the main script rather than just being imported from elsewhere.\n"
] |
[
1
] |
[] |
[] |
[
"last.fm",
"location",
"python"
] |
stackoverflow_0002340589_last.fm_location_python.txt
|
Q:
Ordering of Django models
I set up an ordering='ordering_number' Meta attribute to my Django model, thinking that Django will use it when comparing instances. (ordering_number is an IntegerField in my model.)
For example, if I have an instance a with ordering_number = 4 and an instance b with ordering_number = 7, I'd expect that a < b would be True. However, I tested it, and it didn't seem to work. I did not understand according to which logic a < b would come out as True.
Does anyone know? Why doesn't Django uses ordering for element comparisons?
A:
From the documentation:
The default ordering for the object, for use when obtaining lists of objects
So the reason your comparisons aren't working is because they're not designed that way. Define __lt__() et alia to define ordering of instances.
|
Ordering of Django models
|
I set up an ordering='ordering_number' Meta attribute to my Django model, thinking that Django will use it when comparing instances. (ordering_number is an IntegerField in my model.)
For example, if I have an instance a with ordering_number = 4 and an instance b with ordering_number = 7, I'd expect that a < b would be True. However, I tested it, and it didn't seem to work. I did not understand according to which logic a < b would come out as True.
Does anyone know? Why doesn't Django uses ordering for element comparisons?
|
[
"From the documentation:\n\nThe default ordering for the object, for use when obtaining lists of objects\n\nSo the reason your comparisons aren't working is because they're not designed that way. Define __lt__() et alia to define ordering of instances.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002342913_django_python.txt
|
Q:
How to pass data from Google App Engine(Python) to Flex 4 application
I am using python and webapp framework in app engine for backend and flex 4 for front end.
I would like to pass a string form backend to front end, so i write the following code in the main.py:
class MainPage(webapp.RequestHandler):
def get(self):
userVO = "test"
template_values = {
'url': self.request.uri,
'userVO': userVO,
}
self.response.out.write(template.render("templates/index.html", template_values))
And in the flex 4, I have the following code:
var user:String = FlexGlobals.topLevelApplication.parameters['userVO'];
However, I receive null value.
Please advice how to correct it. Thanks.
Edit: 25 Feb.
Thanks for the people who answer my question. For my question, I am try to figure out how the python app engine pass data to flex app when it render the html file that include the swf file. Maybe, there is something I can set in the main.py, swfobject.js or the index.html to do my task.
I know how to use Pyamf as a gateway to serve the flex app, I am thinking how to make the app more simple.
Thanks.
Edit: 28 Feb.
Robert, the index.html is the standard file created by flash builder 4. Wish you can give me some hints how to modify it. The following is the file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<!--
Smart developers always View Source.
This application was built using Adobe Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops via Adobe AIR.
Learn more about Flex at http://flex.org
// -->
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
html, body { height:100%; }
body { margin:0; padding:0; overflow:hidden; text-align:center; }
#flashContent { display:none; }
<script type="text/javascript" src="/js/swfobject.js"></script>
<script type="text/javascript">
<!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
var swfVersionStr = "10.0.0";
<!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
var xiSwfUrlStr = "/swfs/playerProductInstall.swf";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
var attributes = {};
attributes.id = "index";
attributes.name = "index";
attributes.align = "middle";
swfobject.embedSWF(
"/swfs/index.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
To view this page ensure that Adobe Flash Player version
10.0.0 or greater is installed.
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="index">
<param name="movie" value="index.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<!--[if !IE]>
<object type="application/x-shockwave-flash" data="index.swf" width="100%" height="100%">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<![endif]-->
<!--[if gte IE 6]>
<p>
Either scripts and active content are not permitted to run or Adobe Flash Player version
10.0.0 or greater is not installed.
</p>
<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="https://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
</a>
<!--[if !IE]>
</object>
<![endif]-->
</object>
</noscript>
Thanks, Robert.
Edit: 7 Mar.
Robert,
Refer to http://help.adobe.com/en_US/Flex/4.0/html/WS2db454920e96a9e51e63e3d11c0bf626ae-7feb.html
Before I post the question here, I tried the following code:
In the index.html,
<%
String user = (String) request.getParameter("userVO");
%>
and also
flashvars.userVO = "<%= user %>";
The result, I get:
< user
Do you know why I can't get the correct data. Thanks.
A:
The best way to talk from Flex to GAE is using AMF. Here is how:
app.yaml
application: flexandthecloud
version: 3
runtime: python
api_version: 1
handlers:
- url: /services/.*
script: main.py
main.py
#!/usr/bin/env python
import wsgiref.handlers
from pyamf.remoting.gateway.wsgi import WSGIGateway
def sayHello(name):
return "howdy " + name
services = {
'services.sayHello': sayHello
}
def main():
application = WSGIGateway(services)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Flex 3 code (can be easily modified for Flex 4):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:RemoteObject id="ro" destination="services" endpoint="http://flexandthecloud.appspot.com/services/">
<mx:result>
l.text = event.result as String;
</mx:result>
</mx:RemoteObject>
<mx:TextInput id="ti"/>
<mx:Label id="l"/>
<mx:Button label="say hello" click="ro.sayHello(ti.text)"/>
</mx:Application>
A:
What's in your index.html?
You can pass the values to index.html, set a javascript function like:
function passvalue {
PassParameter("userVO", "{{userVO}}");
}
Then set a function in Flex:
public function gethtmlparam(name:String, val:String):void {
switch (name) {
case "userVO": userVO= val; break;}
}
and call back these two function in :
ExternalInterface.addCallback("PassParameter", gethtmlparam);
Hope it can help.
A:
Based on your comment to James Ward's response, I wonder if you can accomplish what you need with a FlashVars param element?
http://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_3.html
You will probably just need to adjust the index.html template to build the FlashVars param element.
Edit: 6 Mar
You might try looking at:
http://polygeek.com/801_flex_reading-flashvars-in-flex
You need to be sure you wait until the app has been loaded to access the flashVars.
Edit: 7 Mar
Correct, in those examples they hard code the value. You need to edit your template so the value is set to the value of the template parameter.
So, in index.html:
flashvars.userVO = "{{ userVO }}"
|
How to pass data from Google App Engine(Python) to Flex 4 application
|
I am using python and webapp framework in app engine for backend and flex 4 for front end.
I would like to pass a string form backend to front end, so i write the following code in the main.py:
class MainPage(webapp.RequestHandler):
def get(self):
userVO = "test"
template_values = {
'url': self.request.uri,
'userVO': userVO,
}
self.response.out.write(template.render("templates/index.html", template_values))
And in the flex 4, I have the following code:
var user:String = FlexGlobals.topLevelApplication.parameters['userVO'];
However, I receive null value.
Please advice how to correct it. Thanks.
Edit: 25 Feb.
Thanks for the people who answer my question. For my question, I am try to figure out how the python app engine pass data to flex app when it render the html file that include the swf file. Maybe, there is something I can set in the main.py, swfobject.js or the index.html to do my task.
I know how to use Pyamf as a gateway to serve the flex app, I am thinking how to make the app more simple.
Thanks.
Edit: 28 Feb.
Robert, the index.html is the standard file created by flash builder 4. Wish you can give me some hints how to modify it. The following is the file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<!--
Smart developers always View Source.
This application was built using Adobe Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops via Adobe AIR.
Learn more about Flex at http://flex.org
// -->
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
html, body { height:100%; }
body { margin:0; padding:0; overflow:hidden; text-align:center; }
#flashContent { display:none; }
<script type="text/javascript" src="/js/swfobject.js"></script>
<script type="text/javascript">
<!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
var swfVersionStr = "10.0.0";
<!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
var xiSwfUrlStr = "/swfs/playerProductInstall.swf";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
var attributes = {};
attributes.id = "index";
attributes.name = "index";
attributes.align = "middle";
swfobject.embedSWF(
"/swfs/index.swf", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
To view this page ensure that Adobe Flash Player version
10.0.0 or greater is installed.
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="index">
<param name="movie" value="index.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<!--[if !IE]>
<object type="application/x-shockwave-flash" data="index.swf" width="100%" height="100%">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<![endif]-->
<!--[if gte IE 6]>
<p>
Either scripts and active content are not permitted to run or Adobe Flash Player version
10.0.0 or greater is not installed.
</p>
<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="https://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
</a>
<!--[if !IE]>
</object>
<![endif]-->
</object>
</noscript>
Thanks, Robert.
Edit: 7 Mar.
Robert,
Refer to http://help.adobe.com/en_US/Flex/4.0/html/WS2db454920e96a9e51e63e3d11c0bf626ae-7feb.html
Before I post the question here, I tried the following code:
In the index.html,
<%
String user = (String) request.getParameter("userVO");
%>
and also
flashvars.userVO = "<%= user %>";
The result, I get:
< user
Do you know why I can't get the correct data. Thanks.
|
[
"The best way to talk from Flex to GAE is using AMF. Here is how:\napp.yaml\napplication: flexandthecloud\nversion: 3\nruntime: python\napi_version: 1\n\nhandlers:\n- url: /services/.*\n script: main.py\n\nmain.py\n#!/usr/bin/env python\nimport wsgiref.handlers\n\nfrom pyamf.remoting.gateway.wsgi import WSGIGateway\n\ndef sayHello(name):\n return \"howdy \" + name\n\nservices = {\n 'services.sayHello': sayHello\n}\n\ndef main():\n application = WSGIGateway(services)\n wsgiref.handlers.CGIHandler().run(application)\n\nif __name__ == '__main__':\n main()\n\nFlex 3 code (can be easily modified for Flex 4):\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\">\n\n <mx:RemoteObject id=\"ro\" destination=\"services\" endpoint=\"http://flexandthecloud.appspot.com/services/\">\n <mx:result>\n l.text = event.result as String;\n </mx:result>\n </mx:RemoteObject>\n\n <mx:TextInput id=\"ti\"/>\n <mx:Label id=\"l\"/>\n <mx:Button label=\"say hello\" click=\"ro.sayHello(ti.text)\"/>\n\n</mx:Application>\n\n",
"What's in your index.html?\nYou can pass the values to index.html, set a javascript function like:\nfunction passvalue {\n PassParameter(\"userVO\", \"{{userVO}}\");\n}\n\nThen set a function in Flex:\npublic function gethtmlparam(name:String, val:String):void {\n switch (name) {\n case \"userVO\": userVO= val; break;}\n}\n\nand call back these two function in :\nExternalInterface.addCallback(\"PassParameter\", gethtmlparam);\n\nHope it can help.\n",
"Based on your comment to James Ward's response, I wonder if you can accomplish what you need with a FlashVars param element?\nhttp://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_3.html\nYou will probably just need to adjust the index.html template to build the FlashVars param element.\nEdit: 6 Mar\nYou might try looking at:\nhttp://polygeek.com/801_flex_reading-flashvars-in-flex\nYou need to be sure you wait until the app has been loaded to access the flashVars. \nEdit: 7 Mar\nCorrect, in those examples they hard code the value. You need to edit your template so the value is set to the value of the template parameter.\nSo, in index.html:\nflashvars.userVO = \"{{ userVO }}\"\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"apache_flex",
"google_app_engine",
"python",
"swfobject"
] |
stackoverflow_0002311796_apache_flex_google_app_engine_python_swfobject.txt
|
Q:
django admin.site.name in template
Hallo,
is there any chance to access the "name" value of the current admin.site object in a admin template?
I have 3 different admin.site-objects and want a template tag to generate generic content,depending on the current admin.site.name.
thanks in advance
A:
You could provide the name of the current site to all of your templates by writing a custom template context processor that would set a variable (e.g., SITE_NAME) in the context for every template.
|
django admin.site.name in template
|
Hallo,
is there any chance to access the "name" value of the current admin.site object in a admin template?
I have 3 different admin.site-objects and want a template tag to generate generic content,depending on the current admin.site.name.
thanks in advance
|
[
"You could provide the name of the current site to all of your templates by writing a custom template context processor that would set a variable (e.g., SITE_NAME) in the context for every template.\n"
] |
[
3
] |
[] |
[] |
[
"admin",
"django",
"python"
] |
stackoverflow_0002343286_admin_django_python.txt
|
Q:
Python sub-package references
I am about at wits end with what should be an extremely simple issue. Here is the format of a simple example that I wrote to try to fix my problem. I have a folder top with __all__ = ["p1","p2"] in __init__.py . I then have sub-folders p1 and p2 with __init__.py in both of them with __all__ again defined with the names of two simple module quick1 and quick 2 with quick1 in p1 and quick2 in p2. If I import top.p1.quick1 from a script outside of top then the import works fine. However, trying to import top.p1.quick1 from quick2 gives the error
File "quick1.py", line 1, in <module>
import top.p2.quick2
ImportError: No module named top.p2.quick2
How can I import a module from another sub-package? This is supposed to work according to the python documentation as far as I can tell. Does anyone see an obvious, trivial mistake that I made?
Edit: It appears that I need to add the directory with top to my search path. I can do this temporarily by setting PYTHONPATH. However, is there a better way to do this from a distutils script?
A:
Your problem is that your top package is not in your sys.path.
A:
All you describe is just fine and does not reproduce the error -- here's the simplest version I can think of:
$ mkdir /tmp/path
$ mkdir /tmp/path/top /tmp/path/top/p1 /tmp/path/top/p2
$ touch /tmp/path/top/__init__.py /tmp/path/top/p1/__init__.py /tmp/path/top/p2/__init__.py
$ touch /tmp/path/top/p1/quick1.py /tmp/path/top/p2/quick2.py$ echo 'import top.p1.quick1' > /tmp/path/top/p2/quick2.py
$ PYTHONPATH=/tmp/path python /tmp/path/top/p2/quick2.py
$ python -c 'import sys; sys.path.append("/tmp/path"); import top.p2.quick2'
and it runs just fine. The __all__ are not relevant unless you're using from ... import * which you aren't (and right you are not to). As long as the parent directory of top (here, /tmp/path) is on sys.path, things will be fine; if that parent directory is not there, you'll get an error.
So what's the minimal change you can make to this sequence of operations to reproduce the error you observe?
|
Python sub-package references
|
I am about at wits end with what should be an extremely simple issue. Here is the format of a simple example that I wrote to try to fix my problem. I have a folder top with __all__ = ["p1","p2"] in __init__.py . I then have sub-folders p1 and p2 with __init__.py in both of them with __all__ again defined with the names of two simple module quick1 and quick 2 with quick1 in p1 and quick2 in p2. If I import top.p1.quick1 from a script outside of top then the import works fine. However, trying to import top.p1.quick1 from quick2 gives the error
File "quick1.py", line 1, in <module>
import top.p2.quick2
ImportError: No module named top.p2.quick2
How can I import a module from another sub-package? This is supposed to work according to the python documentation as far as I can tell. Does anyone see an obvious, trivial mistake that I made?
Edit: It appears that I need to add the directory with top to my search path. I can do this temporarily by setting PYTHONPATH. However, is there a better way to do this from a distutils script?
|
[
"Your problem is that your top package is not in your sys.path.\n",
"All you describe is just fine and does not reproduce the error -- here's the simplest version I can think of:\n$ mkdir /tmp/path\n$ mkdir /tmp/path/top /tmp/path/top/p1 /tmp/path/top/p2\n$ touch /tmp/path/top/__init__.py /tmp/path/top/p1/__init__.py /tmp/path/top/p2/__init__.py\n$ touch /tmp/path/top/p1/quick1.py /tmp/path/top/p2/quick2.py$ echo 'import top.p1.quick1' > /tmp/path/top/p2/quick2.py\n$ PYTHONPATH=/tmp/path python /tmp/path/top/p2/quick2.py\n$ python -c 'import sys; sys.path.append(\"/tmp/path\"); import top.p2.quick2'\n\nand it runs just fine. The __all__ are not relevant unless you're using from ... import * which you aren't (and right you are not to). As long as the parent directory of top (here, /tmp/path) is on sys.path, things will be fine; if that parent directory is not there, you'll get an error.\nSo what's the minimal change you can make to this sequence of operations to reproduce the error you observe?\n"
] |
[
3,
2
] |
[] |
[] |
[
"import",
"package",
"python"
] |
stackoverflow_0002343311_import_package_python.txt
|
Q:
Open a file in the proper encoding automatically
I'm dealing with some problems in a few files about the encoding. We receive files from other company and have to read them (the files are in csv format)
Strangely, the files appear to be encoded in UTF-16. I am managing to do that, but I have to open them using the codecs module and specifying the encoding, this way.
ENCODING = 'utf-16'
with codecs.open(test_file, encoding=ENCODING) as csv_file:
# Autodetect dialect
dialect = csv.Sniffer().sniff(descriptor.read(1024))
descriptor.seek(0)
input_file = csv.reader(descriptor, dialect=dialect)
for line in input_file:
do_funny_things()
But, just like I am able to get the dialect in a more agnostic way, I 'm thinking it will be great to have a way of opening automatically the files with its proper encoding, at least all the text files. There are other programs, like vim that achieve that.
Anyone knows a way of doing that in python 2.6?
PD: I hope that this will be solved in Python 3, as all the strings are Unicode...
A:
chardet can help you.
Character encoding auto-detection in
Python 2 and 3. As smart as your
browser. Open source.
A:
It won't be "fixed" in python 3, as it's not a fixable problem. Many documents are valid in several encodings, so the only way to determine the proper encoding is to know something about the document. Fortunately, in most cases we do know something about the document, like for instance, most characters will come clustered into distinct unicode blocks. A document in english will mostly contain characters within the first 128 codepoints. A document in russian will contain mostly cyrillic codepoints. Most document will contain spaces and newlines. These clues can be used to help you make educated guesses about what encodings are being used. Better yet, use a library written by someone who's already done the work. (Like chardet, mentioned in another answer by Desintegr.
A:
csv.reader cannot handle Unicode strings in 2.x. See the bottom of the csv documentation and this question for ways to handle it.
|
Open a file in the proper encoding automatically
|
I'm dealing with some problems in a few files about the encoding. We receive files from other company and have to read them (the files are in csv format)
Strangely, the files appear to be encoded in UTF-16. I am managing to do that, but I have to open them using the codecs module and specifying the encoding, this way.
ENCODING = 'utf-16'
with codecs.open(test_file, encoding=ENCODING) as csv_file:
# Autodetect dialect
dialect = csv.Sniffer().sniff(descriptor.read(1024))
descriptor.seek(0)
input_file = csv.reader(descriptor, dialect=dialect)
for line in input_file:
do_funny_things()
But, just like I am able to get the dialect in a more agnostic way, I 'm thinking it will be great to have a way of opening automatically the files with its proper encoding, at least all the text files. There are other programs, like vim that achieve that.
Anyone knows a way of doing that in python 2.6?
PD: I hope that this will be solved in Python 3, as all the strings are Unicode...
|
[
"chardet can help you.\n\nCharacter encoding auto-detection in\n Python 2 and 3. As smart as your\n browser. Open source.\n\n",
"It won't be \"fixed\" in python 3, as it's not a fixable problem. Many documents are valid in several encodings, so the only way to determine the proper encoding is to know something about the document. Fortunately, in most cases we do know something about the document, like for instance, most characters will come clustered into distinct unicode blocks. A document in english will mostly contain characters within the first 128 codepoints. A document in russian will contain mostly cyrillic codepoints. Most document will contain spaces and newlines. These clues can be used to help you make educated guesses about what encodings are being used. Better yet, use a library written by someone who's already done the work. (Like chardet, mentioned in another answer by Desintegr.\n",
"csv.reader cannot handle Unicode strings in 2.x. See the bottom of the csv documentation and this question for ways to handle it.\n"
] |
[
13,
6,
0
] |
[
"If it will be fixed in Python 3, it should also be fixed by using\nfrom __future__ import unicode_literals\n\n"
] |
[
-3
] |
[
"python"
] |
stackoverflow_0002342284_python.txt
|
Q:
how to make python to return floating point?
I want python to return 0.5 if I write 1/2 (and not 1.0/2.0).
how do I make python to return the floating point?
(I tried using getcontext().prec form decimal module)
thanks
Ariel
A:
Use this, or switch to Python 3.0+
from __future__ import division
A:
from __future__ import division
A:
Python 3.x works the way you want by default.
Python 2.2 and greater support from __future__ import division, which makes / return floating point. There is also the // operator that still performs integer division when needed.
Also see PEP238 - Changing the Division Operator.
|
how to make python to return floating point?
|
I want python to return 0.5 if I write 1/2 (and not 1.0/2.0).
how do I make python to return the floating point?
(I tried using getcontext().prec form decimal module)
thanks
Ariel
|
[
"Use this, or switch to Python 3.0+\nfrom __future__ import division\n\n",
"from __future__ import division\n\n",
"Python 3.x works the way you want by default.\nPython 2.2 and greater support from __future__ import division, which makes / return floating point. There is also the // operator that still performs integer division when needed.\nAlso see PEP238 - Changing the Division Operator.\n"
] |
[
8,
4,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002341771_python.txt
|
Q:
Writing to file doesn't flush content automatically and cause out of memory in Python
I made simple python program to generate big text file:
import sys
import random
f = open('data.txt', 'w')
for i in range(100000000):
f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n")
f.close()
When I launch it using CPython it eat all available OS memory and write nothing to the file.
When I launch it on Jython I get OutOfMemoryException.
As far as I understand it stores everything in memory buffer and never did flush before close() call.
My question is: how to limit the file buffer and trigger autoflush?
I don't want to callflush() manually, I think it's wrong from performance point of view. I want flush() to be called automatically when file buffer is overloaded or so.
Thanks!
A:
Buffering is not the problem. The problem is calling the range() function with a giant argument, which will attempt to allocate an array with lots of elements. You will get the same error if you just say
r = range(100000000)
|
Writing to file doesn't flush content automatically and cause out of memory in Python
|
I made simple python program to generate big text file:
import sys
import random
f = open('data.txt', 'w')
for i in range(100000000):
f.write(str(i) + "\t" + str(random.randint(0,1000)) + "\n")
f.close()
When I launch it using CPython it eat all available OS memory and write nothing to the file.
When I launch it on Jython I get OutOfMemoryException.
As far as I understand it stores everything in memory buffer and never did flush before close() call.
My question is: how to limit the file buffer and trigger autoflush?
I don't want to callflush() manually, I think it's wrong from performance point of view. I want flush() to be called automatically when file buffer is overloaded or so.
Thanks!
|
[
"Buffering is not the problem. The problem is calling the range() function with a giant argument, which will attempt to allocate an array with lots of elements. You will get the same error if you just say\nr = range(100000000)\n\n"
] |
[
9
] |
[
"Have you tried passing in a buffer size to the open function?\nf = open('data.txt', 'w', 5000)\n\n"
] |
[
-1
] |
[
"buffer",
"file",
"flush",
"python"
] |
stackoverflow_0002343600_buffer_file_flush_python.txt
|
Q:
How to add an Admin class to a model after syncdb?
I added some models in my models.py and I want to add an admin class to use a wysiwyg-editor in text-fields.
Well, I know that Django itself doesn't support migrations and I've used South, but it doesn't work either.
South doesn't "see" the change.
Could it be, that South just detects changes to fields, but not if I add a new class?
How can I tweak Django to detect such changes?
A:
syncdb and South are only concerned with descendants of Model in apps listed in INSTALLED_APPS. Everything else is handled by Django directly.
A:
I'm fairly sure that if you follow the steps as outlined in the tutorial to create an admin app it'll just work. Migration isn't an issue as the admin app creates new tables rather than altering the existing one.
A:
You seem to be very confused, unfortunately. Of course Django reads the code in models.py - otherwise what would be the point of it? Django uses that code initially to define the model SQL when doing syncdb, but it doesn't modify existing database tables in subsequent calls to syncdb - hence the need for South.
But naturally, Django uses models.py and admin.py and all the other Python code to define its own configuration and state. (And note that admin classes are not defined in models.py but in admin.py.)
If you are not seeing changes, you will need to restart your server.
|
How to add an Admin class to a model after syncdb?
|
I added some models in my models.py and I want to add an admin class to use a wysiwyg-editor in text-fields.
Well, I know that Django itself doesn't support migrations and I've used South, but it doesn't work either.
South doesn't "see" the change.
Could it be, that South just detects changes to fields, but not if I add a new class?
How can I tweak Django to detect such changes?
|
[
"syncdb and South are only concerned with descendants of Model in apps listed in INSTALLED_APPS. Everything else is handled by Django directly.\n",
"I'm fairly sure that if you follow the steps as outlined in the tutorial to create an admin app it'll just work. Migration isn't an issue as the admin app creates new tables rather than altering the existing one.\n",
"You seem to be very confused, unfortunately. Of course Django reads the code in models.py - otherwise what would be the point of it? Django uses that code initially to define the model SQL when doing syncdb, but it doesn't modify existing database tables in subsequent calls to syncdb - hence the need for South.\nBut naturally, Django uses models.py and admin.py and all the other Python code to define its own configuration and state. (And note that admin classes are not defined in models.py but in admin.py.)\nIf you are not seeing changes, you will need to restart your server.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"django",
"django_models",
"django_south",
"python"
] |
stackoverflow_0002343053_django_django_models_django_south_python.txt
|
Q:
How to build an image object in PIL/Python
I have a list of 3-item tuples that is the result of list(PIL.Image.getdata()).
How do I do the opposite: build a PIL.Image object from this list?
A:
The output of getdata() does not include the image format or the size, so you'll need to preserve those (or get the information some other way). Then do this, using the putdata() method:
# get data from old image (as you already did)
data = list(oldimg.getdata())
# create empty new image of appropriate format
newimg = Image.new(format, size) # e.g. ('RGB', (640, 480))
# insert saved data into the image
newimg.putdata(data)
|
How to build an image object in PIL/Python
|
I have a list of 3-item tuples that is the result of list(PIL.Image.getdata()).
How do I do the opposite: build a PIL.Image object from this list?
|
[
"The output of getdata() does not include the image format or the size, so you'll need to preserve those (or get the information some other way). Then do this, using the putdata() method:\n# get data from old image (as you already did)\ndata = list(oldimg.getdata())\n\n# create empty new image of appropriate format\nnewimg = Image.new(format, size) # e.g. ('RGB', (640, 480))\n\n# insert saved data into the image\nnewimg.putdata(data)\n\n"
] |
[
9
] |
[] |
[] |
[
"image",
"python",
"python_imaging_library"
] |
stackoverflow_0002343115_image_python_python_imaging_library.txt
|
Q:
clicking "cancel" in tkColorChooser dialog leads to Error
I use python 2.6 under linux (SUSE Linux Enterprise Desktop 11 (x86_64)). I tested some very simple code :
import tkColorChooser
tkColorChooser.askcolor()
then if I click on cancel, I always get error like:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/lib-tk/tkColorChooser.py", line 62, in askcolor
return Chooser(**options).show()
File "/usr/lib64/python2.6/lib-tk/tkCommonDialog.py", line 50, in show
s = self._fixresult(w, s)
File "/usr/lib64/python2.6/lib-tk/tkColorChooser.py", line 48, in _fixresult
r, g, b = widget.winfo_rgb(result)
File "/usr/lib64/python2.6/lib-tk/Tkinter.py", line 786, in winfo_rgb
self.tk.call('winfo', 'rgb', self._w, color))
_tkinter.TclError: unknown color name ""
I have more complicated code using tkColorChooser, which gives same error if I click on cancel in the color chooser dialog. I think I can catch the error. But is tkColorChooser designed to be like this? Is there any other neater way to cope with this problem? Thanks!
A:
Looking at the version of tkColorChooser.py I have (Python 2.6.4, Win32), it should support the user pressing cancel (as do and should the other predefined dialogs): it is indeed supposed to return None when the results evals to False in a boolean context.
Therefore, something strange is happening.
edit: as I noted in the comments, it is indeed a bug that has been fixed in version 2.6.2.
|
clicking "cancel" in tkColorChooser dialog leads to Error
|
I use python 2.6 under linux (SUSE Linux Enterprise Desktop 11 (x86_64)). I tested some very simple code :
import tkColorChooser
tkColorChooser.askcolor()
then if I click on cancel, I always get error like:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/lib-tk/tkColorChooser.py", line 62, in askcolor
return Chooser(**options).show()
File "/usr/lib64/python2.6/lib-tk/tkCommonDialog.py", line 50, in show
s = self._fixresult(w, s)
File "/usr/lib64/python2.6/lib-tk/tkColorChooser.py", line 48, in _fixresult
r, g, b = widget.winfo_rgb(result)
File "/usr/lib64/python2.6/lib-tk/Tkinter.py", line 786, in winfo_rgb
self.tk.call('winfo', 'rgb', self._w, color))
_tkinter.TclError: unknown color name ""
I have more complicated code using tkColorChooser, which gives same error if I click on cancel in the color chooser dialog. I think I can catch the error. But is tkColorChooser designed to be like this? Is there any other neater way to cope with this problem? Thanks!
|
[
"Looking at the version of tkColorChooser.py I have (Python 2.6.4, Win32), it should support the user pressing cancel (as do and should the other predefined dialogs): it is indeed supposed to return None when the results evals to False in a boolean context.\nTherefore, something strange is happening.\nedit: as I noted in the comments, it is indeed a bug that has been fixed in version 2.6.2.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0002317680_python_tkinter.txt
|
Q:
pylint: Using possibly undefined loop variable 'n'
Pylint says
W: 6: Using possibly undefined loop variable 'n'
... with this code:
iterator = (i*i for i in range(100) if i % 3 == 0)
for n, i in enumerate(iterator):
do_something(i)
print n
because if the iterator is empty (for example []) n is undefined, ok. But I like this trick. How to use it in a safe way?
I think that using len(list(iterator)) is not the best choice because you have to do two loops. I think that using a counter and incrementing it is not very pythonic.
A:
Have you considered merely initializing n to None before running the loop?
A:
Define a default value for n before the for statement:
iterator = (i*i for i in range(100) if i % 3 == 0)
n=None
for n, i in enumerate(iterator):
do_something(i)
print n
|
pylint: Using possibly undefined loop variable 'n'
|
Pylint says
W: 6: Using possibly undefined loop variable 'n'
... with this code:
iterator = (i*i for i in range(100) if i % 3 == 0)
for n, i in enumerate(iterator):
do_something(i)
print n
because if the iterator is empty (for example []) n is undefined, ok. But I like this trick. How to use it in a safe way?
I think that using len(list(iterator)) is not the best choice because you have to do two loops. I think that using a counter and incrementing it is not very pythonic.
|
[
"Have you considered merely initializing n to None before running the loop?\n",
"Define a default value for n before the for statement:\niterator = (i*i for i in range(100) if i % 3 == 0)\n\nn=None\nfor n, i in enumerate(iterator):\n do_something(i)\n\nprint n\n\n"
] |
[
14,
4
] |
[] |
[] |
[
"enumerate",
"python"
] |
stackoverflow_0002344315_enumerate_python.txt
|
Q:
Creating a Cron Job - Linux / Python
Hi I have a Django script that I need to run,
I think the commands could be called through bash.
Thing is the script causes memory leaks after a long a period of time, so I would like to create an external cron job which calls the Python script. So the script would terminate and restart while retaking the lost memory.
Can someone point me in the right direction? I know quite little on the subject, and feel a bit lost.
A:
If you have an executable, say /home/bin/foobar, that restarts the script, and want to run it (say) every 10 minutes, the crontab entry needs to be:
*/10 * * * * /home/bin/foobar
which says to run it at every minute divisible by 10, every hour, every day.
If you save this (and any other periodic jobs you want to run) as, say, /home/bin/mycrontab, then just do crontab /home/bin/crontab and the system will do the rest (the script runs with your userid).
To see what periodic jobs you have already scheduled under the current userid, if any, do crontab -l.
A:
Have you taken a look at custom management commands for your django app? They work like any other command from manage.py, except you can write them.
Applications can register their own
actions with manage.py. For example,
you might want to add a manage.py
action for a Django app that you’re
distributing.
To do this, just add a
management/commands directory to your
application. Each Python module in
that directory will be auto-discovered
and registered as a command that can
be executed as an action when you run
manage.py.
A:
The problem with a cron job is that it will start every so often regardless of whether the previous instance is finished. What I would recommend is to have your script start a new instance of itself after a certain amount of time, then exit.
A:
i think http://code.google.com/p/django-cron/ should be interesting for you
its a platform independand cron-lib for django, and works as well on windows servers
|
Creating a Cron Job - Linux / Python
|
Hi I have a Django script that I need to run,
I think the commands could be called through bash.
Thing is the script causes memory leaks after a long a period of time, so I would like to create an external cron job which calls the Python script. So the script would terminate and restart while retaking the lost memory.
Can someone point me in the right direction? I know quite little on the subject, and feel a bit lost.
|
[
"If you have an executable, say /home/bin/foobar, that restarts the script, and want to run it (say) every 10 minutes, the crontab entry needs to be:\n*/10 * * * * /home/bin/foobar\n\nwhich says to run it at every minute divisible by 10, every hour, every day.\nIf you save this (and any other periodic jobs you want to run) as, say, /home/bin/mycrontab, then just do crontab /home/bin/crontab and the system will do the rest (the script runs with your userid).\nTo see what periodic jobs you have already scheduled under the current userid, if any, do crontab -l.\n",
"Have you taken a look at custom management commands for your django app? They work like any other command from manage.py, except you can write them.\n\nApplications can register their own\n actions with manage.py. For example,\n you might want to add a manage.py\n action for a Django app that you’re\n distributing.\nTo do this, just add a\n management/commands directory to your\n application. Each Python module in\n that directory will be auto-discovered\n and registered as a command that can\n be executed as an action when you run\n manage.py.\n\n",
"The problem with a cron job is that it will start every so often regardless of whether the previous instance is finished. What I would recommend is to have your script start a new instance of itself after a certain amount of time, then exit.\n",
"i think http://code.google.com/p/django-cron/ should be interesting for you\nits a platform independand cron-lib for django, and works as well on windows servers\n"
] |
[
7,
2,
1,
1
] |
[] |
[] |
[
"django",
"linux",
"python",
"ubuntu"
] |
stackoverflow_0002339725_django_linux_python_ubuntu.txt
|
Q:
Python Regex to match a file in a list of files (getting error)
I'm trying to use a regex in Python to match a file (saved as a string, ie "/volumes/footage/foo/bar.mov") to a log file I create that contains a list of files. But when I run the script, it gives me this error: sre_constants.error: unbalanced parenthesis. The code I'm using is this:
To read the file:
theLogFile = The_Root_Path + ".processedlog"
if os.path.isfile(theLogFile):
the_file = open(theLogFile, "r")
else:
open(theLogFile, 'w').close()
the_file = open(theLogFile, "r")
the_log = the_file.read()
the_file.close()
Then inside a for loop I reassign (I didn't realize I was doing this until I posted this question) the the_file variable as a string from a list of files (obtained by running through a folder and it's subsets and grabbing all the filenames), then try to use regex to see if that filename is present in the log file:
for the_file in filenamelist:
p = re.compile(the_file, re.IGNORECASE)
m = p.search(the_log)
Every time it hits the re.compile() part of the code it spits out that error. And if I try to cut that out, and use re.search(the_file, the_log) it still spits out that error. I don't understand how I could be getting unbalanced parenthesis from this.
A:
Where is the regular expression pattern? Are you trying to use filenames contained in one file as patterns to search the other file? If so, you will want to step through the_file with someting like
for the_pattern in the_file:
p = re.compile(the_pattern, re.IGNORECASE)
m = p.search(the_log)
...
According to the Python re.compile documentation, the first argument to re.compile() should be the regular expression pattern as a string.
But the return value of open() is a file object, which you assign to the_file and pass to re.compile()....
A:
Gordon,
it would seem to me that the issue is in the data. You are compiling uninspected strings from the filelist into regexp, not heeding that they might contain meta characters relevant for the regexp engine.
In your for loop, add a print the_file before the call to re.compile (it is no problem that you are re-using a name as the loop iterator that referred to file object before), so you can see which strings are actually coming from the filelist. Or, better still, run all instances of the_file through re.escape before passing them to re.compile. This will turn all meta characters into their normal equivalent.
A:
What you're binding to name the_file in your first snippet is a file object, even though you say that's "saved as a string", the filename (i.e. the string) is actually named theLogFile but what you're trying t turn into a RE object is not theLogFile (the string), it's the_file (the now-closed file object). Given this, the error's somewhat quirky (one would expect a TypeError), but it's clear that you will get an error at re.compile.
A:
the_file should be a string. In the above code the_file is the return value of open, which is a file object.
|
Python Regex to match a file in a list of files (getting error)
|
I'm trying to use a regex in Python to match a file (saved as a string, ie "/volumes/footage/foo/bar.mov") to a log file I create that contains a list of files. But when I run the script, it gives me this error: sre_constants.error: unbalanced parenthesis. The code I'm using is this:
To read the file:
theLogFile = The_Root_Path + ".processedlog"
if os.path.isfile(theLogFile):
the_file = open(theLogFile, "r")
else:
open(theLogFile, 'w').close()
the_file = open(theLogFile, "r")
the_log = the_file.read()
the_file.close()
Then inside a for loop I reassign (I didn't realize I was doing this until I posted this question) the the_file variable as a string from a list of files (obtained by running through a folder and it's subsets and grabbing all the filenames), then try to use regex to see if that filename is present in the log file:
for the_file in filenamelist:
p = re.compile(the_file, re.IGNORECASE)
m = p.search(the_log)
Every time it hits the re.compile() part of the code it spits out that error. And if I try to cut that out, and use re.search(the_file, the_log) it still spits out that error. I don't understand how I could be getting unbalanced parenthesis from this.
|
[
"Where is the regular expression pattern? Are you trying to use filenames contained in one file as patterns to search the other file? If so, you will want to step through the_file with someting like \nfor the_pattern in the_file:\n p = re.compile(the_pattern, re.IGNORECASE)\n m = p.search(the_log)\n ...\n\nAccording to the Python re.compile documentation, the first argument to re.compile() should be the regular expression pattern as a string. \nBut the return value of open() is a file object, which you assign to the_file and pass to re.compile().... \n",
"Gordon,\nit would seem to me that the issue is in the data. You are compiling uninspected strings from the filelist into regexp, not heeding that they might contain meta characters relevant for the regexp engine.\nIn your for loop, add a print the_file before the call to re.compile (it is no problem that you are re-using a name as the loop iterator that referred to file object before), so you can see which strings are actually coming from the filelist. Or, better still, run all instances of the_file through re.escape before passing them to re.compile. This will turn all meta characters into their normal equivalent.\n",
"What you're binding to name the_file in your first snippet is a file object, even though you say that's \"saved as a string\", the filename (i.e. the string) is actually named theLogFile but what you're trying t turn into a RE object is not theLogFile (the string), it's the_file (the now-closed file object). Given this, the error's somewhat quirky (one would expect a TypeError), but it's clear that you will get an error at re.compile.\n",
"the_file should be a string. In the above code the_file is the return value of open, which is a file object.\n"
] |
[
3,
2,
1,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002344193_python_regex.txt
|
Q:
Python: group results by time intervals
I have a large data loaded from a pickled file. The data is a sorted list of tuples containing a datetime and an int like this
[ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L),
(datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L),
(datetime.datetime(2010, 2, 26, 12, 6, 4) , 5594807L),
etc
]
I want to get a population density based on some time intervals. For example, I want to grab the number of records within 5 minute / 1 minute / 30 second periods.
What is the best method to do this? I know I can just loop through every instance in the list but was looking for a better approach (if one exists).
Desired output would be something like:
2010-01-01 04:10:00 --- 5000
2010-02-04 10:05:00 --- 4000
2010-01-02 13:25:00 --- 3999
A:
Check out itertools.groupby. You can pass a function that calculates the proper bucket as the key. Then, you can run your aggregations (counts, averages, what-have-you) on the groups in the resulting iterable.
A:
bisect.bisect is another way to solve this problem:
import datetime
import bisect
import collections
data=[ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L),
(datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L),
(datetime.datetime(2010, 2, 26, 12, 6, 4) , 5594807L),
]
interval=datetime.timedelta(minutes=1,seconds=30)
start=datetime.datetime(2010, 2, 26, 12, 6, 4)
grid=[start+n*interval for n in range(10)]
bins=collections.defaultdict(list)
for date,num in data:
idx=bisect.bisect(grid,date)
bins[idx].append(num)
for idx,nums in bins.iteritems():
print('{0} --- {1}'.format(grid[idx],len(nums)))
|
Python: group results by time intervals
|
I have a large data loaded from a pickled file. The data is a sorted list of tuples containing a datetime and an int like this
[ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L),
(datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L),
(datetime.datetime(2010, 2, 26, 12, 6, 4) , 5594807L),
etc
]
I want to get a population density based on some time intervals. For example, I want to grab the number of records within 5 minute / 1 minute / 30 second periods.
What is the best method to do this? I know I can just loop through every instance in the list but was looking for a better approach (if one exists).
Desired output would be something like:
2010-01-01 04:10:00 --- 5000
2010-02-04 10:05:00 --- 4000
2010-01-02 13:25:00 --- 3999
|
[
"Check out itertools.groupby. You can pass a function that calculates the proper bucket as the key. Then, you can run your aggregations (counts, averages, what-have-you) on the groups in the resulting iterable.\n",
"bisect.bisect is another way to solve this problem:\nimport datetime\nimport bisect\nimport collections\n\ndata=[ (datetime.datetime(2010, 2, 26, 12, 8, 17), 5594813L), \n (datetime.datetime(2010, 2, 26, 12, 7, 31), 5594810L), \n (datetime.datetime(2010, 2, 26, 12, 6, 4) , 5594807L),\n]\ninterval=datetime.timedelta(minutes=1,seconds=30)\nstart=datetime.datetime(2010, 2, 26, 12, 6, 4)\ngrid=[start+n*interval for n in range(10)]\nbins=collections.defaultdict(list)\nfor date,num in data:\n idx=bisect.bisect(grid,date)\n bins[idx].append(num)\nfor idx,nums in bins.iteritems():\n print('{0} --- {1}'.format(grid[idx],len(nums)))\n\n"
] |
[
6,
6
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002344639_python.txt
|
Q:
PyUnit tearDown and setUp vs __init__ and __del__
Is there a difference between using tearDown and setUp versus __init__ and __del__ when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?
A:
setUp is called before every test, and tearDown is called after every test.
__init__ is called once when the class is instantiated -- but since a new
TestCase instance is created for each individual test method, __init__ is
also called once per test.
You generally do not need to define __init__ or __del__ when writing unit
tests, though you could use __init__ to define a constant used by many tests.
This code shows the order in which the methods are called:
import unittest
import sys
class TestTest(unittest.TestCase):
def __init__(self, methodName='runTest'):
# A new TestTest instance is created for each test method
# Thus, __init__ is called once for each test method
super(TestTest, self).__init__(methodName)
print('__init__')
def setUp(self):
#
# setUp is called once before each test
#
print('setUp')
def tearDown(self):
#
# tearDown is called once after each test
#
print('tearDown')
def test_A(self):
print('test_A')
def test_B(self):
print('test_B')
def test_C(self):
print('test_C')
if __name__ == '__main__':
sys.argv.insert(1, '--verbose')
unittest.main(argv=sys.argv)
prints
__init__
__init__
__init__
test_A (__main__.TestTest) ... setUp
test_A
tearDown
ok
test_B (__main__.TestTest) ... setUp
test_B
tearDown
ok
test_C (__main__.TestTest) ... setUp
test_C
tearDown
ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
|
PyUnit tearDown and setUp vs __init__ and __del__
|
Is there a difference between using tearDown and setUp versus __init__ and __del__ when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?
|
[
"setUp is called before every test, and tearDown is called after every test.\n__init__ is called once when the class is instantiated -- but since a new\nTestCase instance is created for each individual test method, __init__ is\nalso called once per test.\nYou generally do not need to define __init__ or __del__ when writing unit\ntests, though you could use __init__ to define a constant used by many tests.\n\nThis code shows the order in which the methods are called:\nimport unittest\nimport sys\n\nclass TestTest(unittest.TestCase):\n\n def __init__(self, methodName='runTest'):\n # A new TestTest instance is created for each test method\n # Thus, __init__ is called once for each test method\n super(TestTest, self).__init__(methodName)\n print('__init__')\n\n def setUp(self):\n #\n # setUp is called once before each test\n #\n print('setUp')\n\n def tearDown(self):\n #\n # tearDown is called once after each test\n #\n print('tearDown')\n\n def test_A(self):\n print('test_A')\n\n def test_B(self):\n print('test_B')\n\n def test_C(self):\n print('test_C')\n\n\n\nif __name__ == '__main__':\n sys.argv.insert(1, '--verbose')\n unittest.main(argv=sys.argv)\n\nprints\n__init__\n__init__\n__init__\ntest_A (__main__.TestTest) ... setUp\ntest_A\ntearDown\nok\ntest_B (__main__.TestTest) ... setUp\ntest_B\ntearDown\nok\ntest_C (__main__.TestTest) ... setUp\ntest_C\ntearDown\nok\n\n----------------------------------------------------------------------\nRan 3 tests in 0.000s\n\nOK\n\n"
] |
[
38
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0002344772_python_unit_testing.txt
|
Q:
Python script is running. I have a method name as a string. How do I call this method?
everyone. Please see example below. I'd like to supply a string to 'schedule_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea how to do it correctly. Please help
class Bot:
def work(self): pass
def fight(self): pass
class Scheduler:
def schedule_action(self,action):
bot = Bot()
bot.action()
scheduler = Scheduler()
scheduler.schedule_action('fight')
A:
Use getattr:
class Bot:
def fight(self):
print "fighting is fun!"
class Scheduler:
def schedule_action(self,action):
bot = Bot()
getattr(bot,action)()
scheduler = Scheduler()
scheduler.schedule_action('fight')
Note that getattr also takes an optional argument that allows you to return a default value in case the requested action doesn't exist.
A:
In short,
getattr(bot, action)()
getattr will look up an attribute on the object by name -- attributes can be data or member methods The extra () at the end calls the method.
You could get the method in a separate step, like this, as well:
method_to_call = getattr(bot, action)
method_to_call()
And you can pass arguments to the method in the usual way:
getattr(bot, action)(argument1, argument2)
or
method_to_call = getattr(bot, action)
method_to_call(argument1, argument2)
A:
I'm not sure if it applies in your situation, but you may consider using a function pointer instead of manipulating the strings.
class Bot:
def work(self):
print 'working'
def fight(self):
print 'fightin'
class Scheduler:
def schedule_action(self,action):
bot = Bot()
action(bot)
scheduler = Scheduler()
scheduler.schedule_action(Bot.fight)
scheduler.schedule_action(Bot.work)
Which prints:
fightin
working
If you can do this, it will give you an error about a misspelled function at compile-time when the code is interpreted instead of during run-time. This could shorten your debug cycle for stupid data-entry errors, especially if the actions are done over a span of time. Nothing sucks more than running something overnight and discovering that you had a syntax error in the morning.
A:
class Scheduler:
def schedule_action(self,action):
bot = Bot()
boundmethod = getattr(bot, action)
boundmethod()
A:
def schedule_action(self,action):
bot = Bot()
bot.__getattribute__(action)()
A:
You can also use a dictionary to map methods to actions. For instance:
ACTIONS = {"fight": Bot.fight,
"walk": Bot.walk,}
class Scheduler:
def schedule_action(self, action):
return ACTIONS[action](Bot())
|
Python script is running. I have a method name as a string. How do I call this method?
|
everyone. Please see example below. I'd like to supply a string to 'schedule_action' method which specifies, what Bot-class method should be called. In the example below I've represented it as 'bot.action()' but I have no idea how to do it correctly. Please help
class Bot:
def work(self): pass
def fight(self): pass
class Scheduler:
def schedule_action(self,action):
bot = Bot()
bot.action()
scheduler = Scheduler()
scheduler.schedule_action('fight')
|
[
"Use getattr:\nclass Bot:\n def fight(self):\n print \"fighting is fun!\"\n\nclass Scheduler: \n def schedule_action(self,action):\n bot = Bot()\n getattr(bot,action)()\n\nscheduler = Scheduler()\nscheduler.schedule_action('fight')\n\nNote that getattr also takes an optional argument that allows you to return a default value in case the requested action doesn't exist.\n",
"In short,\ngetattr(bot, action)()\n\ngetattr will look up an attribute on the object by name -- attributes can be data or member methods The extra () at the end calls the method.\nYou could get the method in a separate step, like this, as well:\nmethod_to_call = getattr(bot, action)\nmethod_to_call()\n\nAnd you can pass arguments to the method in the usual way:\ngetattr(bot, action)(argument1, argument2)\n\nor\nmethod_to_call = getattr(bot, action)\nmethod_to_call(argument1, argument2)\n\n",
"I'm not sure if it applies in your situation, but you may consider using a function pointer instead of manipulating the strings.\nclass Bot:\n def work(self): \n print 'working'\n def fight(self): \n print 'fightin'\n\nclass Scheduler:\n def schedule_action(self,action):\n bot = Bot()\n action(bot)\n\nscheduler = Scheduler()\nscheduler.schedule_action(Bot.fight)\nscheduler.schedule_action(Bot.work)\n\nWhich prints:\nfightin\nworking\n\nIf you can do this, it will give you an error about a misspelled function at compile-time when the code is interpreted instead of during run-time. This could shorten your debug cycle for stupid data-entry errors, especially if the actions are done over a span of time. Nothing sucks more than running something overnight and discovering that you had a syntax error in the morning.\n",
"class Scheduler:\n def schedule_action(self,action):\n bot = Bot()\n boundmethod = getattr(bot, action)\n boundmethod()\n\n",
"def schedule_action(self,action):\n bot = Bot()\n bot.__getattribute__(action)()\n\n",
"You can also use a dictionary to map methods to actions. For instance:\nACTIONS = {\"fight\": Bot.fight,\n \"walk\": Bot.walk,}\n\nclass Scheduler:\n def schedule_action(self, action):\n return ACTIONS[action](Bot())\n\n"
] |
[
12,
7,
6,
3,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002344212_python.txt
|
Q:
Extra parameter for Django models
With Django models, I want to achieve this:
class Foo(models.Model):
name = models.CharField(max_length=50)
#wrapping the save function, including extra tasks
def save(self, *args, **kwargs):
super(Foo, self).save(*args, **kwargs)
if extra_param:
...do task 1
else:
...do task 2
And while crating Foo I want to pass such as
Foo(name="Bill Gates",extra_param=True).save() # now triggers the task 1
Foo(name="Bill Gates").save() # now triggers the task 2
How can this be done? I am also open to any other suggestions :)
Thanks
A:
You can define non-persistent fields in your model.
class Foo(models.Model):
name = models.CharField(max_length=50)
extra_param = False
def save(self, *args, **kwargs):
...
print self.extra_param
Alternatively, you can do:
Foo(name="Bill Gates").save(extra_param=True)
def save(self, *args, **kwargs):
...
print kwargs["extra_param"]
|
Extra parameter for Django models
|
With Django models, I want to achieve this:
class Foo(models.Model):
name = models.CharField(max_length=50)
#wrapping the save function, including extra tasks
def save(self, *args, **kwargs):
super(Foo, self).save(*args, **kwargs)
if extra_param:
...do task 1
else:
...do task 2
And while crating Foo I want to pass such as
Foo(name="Bill Gates",extra_param=True).save() # now triggers the task 1
Foo(name="Bill Gates").save() # now triggers the task 2
How can this be done? I am also open to any other suggestions :)
Thanks
|
[
"You can define non-persistent fields in your model.\nclass Foo(models.Model):\n name = models.CharField(max_length=50)\n extra_param = False\n\ndef save(self, *args, **kwargs):\n ... \n print self.extra_param\n\nAlternatively, you can do:\nFoo(name=\"Bill Gates\").save(extra_param=True)\n\ndef save(self, *args, **kwargs):\n ... \n print kwargs[\"extra_param\"]\n\n"
] |
[
9
] |
[] |
[] |
[
"django",
"django_forms",
"python",
"wrapper"
] |
stackoverflow_0002344994_django_django_forms_python_wrapper.txt
|
Q:
Minimize python distribution size
The hindrance we have to ship python is the large size of the standard library.
Is there a minimal python distribution or an easy way to pick and choose what we want from
the standard library?
The platform is linux.
A:
If all you want is to get the minimum subset you need (rather than build an exe which would constrain you to Windows systems), use the standard library module modulefinder to list all modules your program requires (you'll get all dependencies, direct and indirect). Then you can zip all the relevant .pyo or .pyc files (depending on whether you run Python with or without the -O flag) and just use that zipfile as your sys.path (plus a directory for all the .pyd or .so native-code dynamic libraries you may need -- those need to live directly in the filesystem to let the OS load them in as needed, can't be loaded directly from a zipfile the way Python bytecode modules can, unfortunately).
A:
Have you looked at py2exe? It provides a way to ship Python programs without requiring a Python installation.
A:
Like Hank Gay and Alex Martelli suggest, you can use py2exe. In addition I would suggest looking into using something like IronPython. Depending on your application, you can use libraries that are built into the .NET framework (or MONO if for Linux). This reduces your shipping size, but adds minimum requirements to your program.
Further, if you are using functions from a library, you can use from module import x instead of doing a wildcard import. This reduces your ship size as well, but maybe not by too much
Hope this helps
|
Minimize python distribution size
|
The hindrance we have to ship python is the large size of the standard library.
Is there a minimal python distribution or an easy way to pick and choose what we want from
the standard library?
The platform is linux.
|
[
"If all you want is to get the minimum subset you need (rather than build an exe which would constrain you to Windows systems), use the standard library module modulefinder to list all modules your program requires (you'll get all dependencies, direct and indirect). Then you can zip all the relevant .pyo or .pyc files (depending on whether you run Python with or without the -O flag) and just use that zipfile as your sys.path (plus a directory for all the .pyd or .so native-code dynamic libraries you may need -- those need to live directly in the filesystem to let the OS load them in as needed, can't be loaded directly from a zipfile the way Python bytecode modules can, unfortunately).\n",
"Have you looked at py2exe? It provides a way to ship Python programs without requiring a Python installation.\n",
"Like Hank Gay and Alex Martelli suggest, you can use py2exe. In addition I would suggest looking into using something like IronPython. Depending on your application, you can use libraries that are built into the .NET framework (or MONO if for Linux). This reduces your shipping size, but adds minimum requirements to your program.\nFurther, if you are using functions from a library, you can use from module import x instead of doing a wildcard import. This reduces your ship size as well, but maybe not by too much\nHope this helps\n"
] |
[
9,
4,
1
] |
[] |
[] |
[
"minimize",
"python",
"size"
] |
stackoverflow_0002344712_minimize_python_size.txt
|
Q:
Python: Why is comparison between lists and tuples not supported?
When comparing a tuple with a list like ...
>>> [1,2,3] == (1,2,3)
False
>>> [1,2,3].__eq__((1,2,3))
NotImplemented
>>> (1,2,3).__eq__([1,2,3])
NotImplemented
... Python does not deep-compare them as done with (1,2,3) == (1,2,3).
So what is the reason for this? Is it because the mutable list can be changed at any time (thread-safety issues) or what?
(I know where this is implemented in CPython, so please don't answer where, but why it is implemented.)
A:
You can always "cast" it
>>> tuple([1, 2]) == (1, 2)
True
Keep in mind that Python, unlike for example Javascript, is strongly typed, and some (most?) of us prefer it that way.
A:
There's no technical reason for lists not being able to compare to tuples; it's entirely a design decision driven by semantics. For proof that it's not related to thread-safety, you can compare lists to other lists:
>>> l1 = [1, 2, 3]
>>> l2 = [1, 2, 3]
>>> l1 == l2
True
>>> id(l1) == id(l2)
False
It seems reasonable to allow users to directly compare lists and tuples, but then you end up with other questions: should the user be allowed to compare lists and queues? What about any two objects which provide iterators? What about the following?
>>> s = set([('x', 1), ('y', 2)])
>>> d = dict(s)
>>> s == d # This doesn't work
False
It can get complicated pretty quickly. The language designers recognized the issue, and avoided it by simply preventing different collection types from comparing directly with each other1.
Note that the simple solution (to create a new list from the tuple and compare them) is easy but inefficient. If you're working with large numbers of items, you're better off with something like:
def compare_sequences(iter1, iter2):
iter1, iter2 = iter(iter1), iter(iter2)
for i1 in iter1:
try:
i2 = next(iter2)
except StopIteration:
return False
if i1 != i2:
return False
try:
i2 = next(iter2)
except StopIteration:
return True
return False
This has the advantage of working on any two sequences, at an obvious cost in complexity.
1 I note there's an exception for sets and frozensets. And no doubt a few others I'm not aware of. The language designers are purists, except where it pays to be practical.
|
Python: Why is comparison between lists and tuples not supported?
|
When comparing a tuple with a list like ...
>>> [1,2,3] == (1,2,3)
False
>>> [1,2,3].__eq__((1,2,3))
NotImplemented
>>> (1,2,3).__eq__([1,2,3])
NotImplemented
... Python does not deep-compare them as done with (1,2,3) == (1,2,3).
So what is the reason for this? Is it because the mutable list can be changed at any time (thread-safety issues) or what?
(I know where this is implemented in CPython, so please don't answer where, but why it is implemented.)
|
[
"You can always \"cast\" it\n>>> tuple([1, 2]) == (1, 2)\nTrue\n\nKeep in mind that Python, unlike for example Javascript, is strongly typed, and some (most?) of us prefer it that way.\n",
"There's no technical reason for lists not being able to compare to tuples; it's entirely a design decision driven by semantics. For proof that it's not related to thread-safety, you can compare lists to other lists:\n>>> l1 = [1, 2, 3]\n>>> l2 = [1, 2, 3]\n>>> l1 == l2\nTrue\n>>> id(l1) == id(l2)\nFalse\n\nIt seems reasonable to allow users to directly compare lists and tuples, but then you end up with other questions: should the user be allowed to compare lists and queues? What about any two objects which provide iterators? What about the following?\n>>> s = set([('x', 1), ('y', 2)])\n>>> d = dict(s)\n>>> s == d # This doesn't work\nFalse\n\nIt can get complicated pretty quickly. The language designers recognized the issue, and avoided it by simply preventing different collection types from comparing directly with each other1.\nNote that the simple solution (to create a new list from the tuple and compare them) is easy but inefficient. If you're working with large numbers of items, you're better off with something like:\ndef compare_sequences(iter1, iter2):\n iter1, iter2 = iter(iter1), iter(iter2)\n for i1 in iter1:\n try:\n i2 = next(iter2)\n except StopIteration:\n return False\n\n if i1 != i2:\n return False\n\n try:\n i2 = next(iter2)\n except StopIteration:\n return True\n\n return False\n\nThis has the advantage of working on any two sequences, at an obvious cost in complexity.\n\n1 I note there's an exception for sets and frozensets. And no doubt a few others I'm not aware of. The language designers are purists, except where it pays to be practical.\n"
] |
[
35,
14
] |
[] |
[] |
[
"comparison",
"list",
"python",
"tuples"
] |
stackoverflow_0002345092_comparison_list_python_tuples.txt
|
Q:
How can I capture and print packets from the internet on Windows?
How can I capture them?
Is there any module/lib to do it?
Please if it do, post an example
A:
If you can install Wireshark, you can use it programaticaly from Python. (This isn't yet supported on Windows, as per bug 3500.)
You also have PyCap, a Python Packet Capture and Injection Library that seems to be platform independent.
Yet another packet sniffing module is Scapy, that I though didn't work on Windows, but was fortunately mistaken.
|
How can I capture and print packets from the internet on Windows?
|
How can I capture them?
Is there any module/lib to do it?
Please if it do, post an example
|
[
"If you can install Wireshark, you can use it programaticaly from Python. (This isn't yet supported on Windows, as per bug 3500.)\n\nYou also have PyCap, a Python Packet Capture and Injection Library that seems to be platform independent.\n\nYet another packet sniffing module is Scapy, that I though didn't work on Windows, but was fortunately mistaken.\n"
] |
[
1
] |
[] |
[] |
[
"packets",
"python",
"windows"
] |
stackoverflow_0002345217_packets_python_windows.txt
|
Q:
What is the Python code to split up a string so that it prints out normally in an 80-character window without wrapping?
When I run my program (which decrypts a paragraph from a certain document), I have:
W
E
T
H
E
P
E
O
P
L
E
O
F
T
H
E
U
N
I
T
E
D
S
T
A
T
E
S
I
N
O
R
D
E
R
T
O
F
O
R
M
A
M
O
R
E
P
E
R
F
E
C
T
U
N
I
O
N
E
S
T
A
B
L
I
S
H
J
U
S
T
I
C
E
I
N
S
U
R
E
D
O
M
E
S
T
I
C
T
R
A
N
Q
U
I
L
I
T
Y
P
R
O
V
I
D
E
F
O
R
T
H
E
C
O
M
M
O
N
D
E
F
E
N
S
E
P
R
O
M
O
T
E
T
H
E
G
E
N
E
R
A
L
W
E
L
F
A
R
E
A
N
D
S
E
C
U
R
E
T
H
E
B
L
E
S
S
I
N
G
S
O
F
L
I
B
E
R
T
Y
T
O
O
U
R
S
E
L
V
E
S
A
N
D
O
U
R
P
O
S
T
E
R
I
T
Y
D
O
O
R
D
A
I
N
A
N
D
E
S
T
A
B
L
I
S
H
T
H
I
S
C
O
N
S
T
I
T
U
T
I
O
N
F
O
R
T
H
E
U
N
I
T
E
D
S
T
A
T
E
S
O
F
A
M
E
R
I
C
A
You can't tell from here but basically it is one letter per line.
However, I want it to say:
WE THE PEOPLE OF THE UNITED STATES, IN ORDER TO FORM A MORE PERFECT UNION,
ESTABLISH JUSTICE, INSURE DOMESTIC TRANQUILITY, PROVIDE FOR THE COMMON DEFENSE,
PROMOTE THE GENERAL WELFARE, AND SECURE THE BLESSINGS OF LIBERTY TO OURSELVES
AND OUR POSTERITY, DO ORDAIN AND ESTABLISH THIS CONSTITUTION FOR THE UNITED
STATES OF AMERICA.
What is the code I must add to my program in order for this to happen?
A:
I don't know what that one-character-a-line is about because you didn't tell us the reason, but the textwrap module will give you what you want:
s="WE THE PEOPLE OF THE UNITED STATES, IN ORDER TO FORM A MORE PERFECT UNION, ESTABLISH JUSTICE, INSURE DOMESTIC TRANQUILITY, PROVIDE FOR THE COMMON DEFENSE, PROMOTE THE GENERAL WELFARE, AND SECURE THE BLESSINGS OF LIBERTY TO OURSELVES AND OUR POSTERITY, DO ORDAIN AND ESTABLISH THIS CONSTITUTION FOR THE UNITED STATES OF AMERICA."
import textwrap
print "\n".join(textwrap.wrap(s, 80))
I reconstructed your original code from your comment, and this is a corrected version:
# You don't even use this so why import it? --> import string
def main():
user_string = raw_input()
all_caps = user_string.upper() # guess you wanted to make it uppercase
output = [] # this will hold the decoded characters
for char in all_caps:
if char.isalpha():
value = ord(char)
if 70 <= value <= 90: # look at this, almost no other programming language supports that syntax
num = value - 5
elif 65 <= value <= 69:
num = value + 21
output.append(chr(num)) # add the decoded character to the output list
else:
output.append(char) # add the character verbatim to the output list (e.g. whitespace)
print "".join(output) # print out the list by putting it together into a string
main()
A:
Do you do something like this:
for char in string:
print char
? If yes, fix that to:
for char in string:
print char,
the comma(,) at the end of the line omits the newline print normally prints.
But even that is probably not what you want (since it prints a space after each char), the following code should fix that, too:
import sys
for char in string:
sys.stdout.write(char)
A:
print s[0],
i = 1
for char in s[1:]:
if i%80:
print "\bchar",
else:
print "\b\n"
i += 1
|
What is the Python code to split up a string so that it prints out normally in an 80-character window without wrapping?
|
When I run my program (which decrypts a paragraph from a certain document), I have:
W
E
T
H
E
P
E
O
P
L
E
O
F
T
H
E
U
N
I
T
E
D
S
T
A
T
E
S
I
N
O
R
D
E
R
T
O
F
O
R
M
A
M
O
R
E
P
E
R
F
E
C
T
U
N
I
O
N
E
S
T
A
B
L
I
S
H
J
U
S
T
I
C
E
I
N
S
U
R
E
D
O
M
E
S
T
I
C
T
R
A
N
Q
U
I
L
I
T
Y
P
R
O
V
I
D
E
F
O
R
T
H
E
C
O
M
M
O
N
D
E
F
E
N
S
E
P
R
O
M
O
T
E
T
H
E
G
E
N
E
R
A
L
W
E
L
F
A
R
E
A
N
D
S
E
C
U
R
E
T
H
E
B
L
E
S
S
I
N
G
S
O
F
L
I
B
E
R
T
Y
T
O
O
U
R
S
E
L
V
E
S
A
N
D
O
U
R
P
O
S
T
E
R
I
T
Y
D
O
O
R
D
A
I
N
A
N
D
E
S
T
A
B
L
I
S
H
T
H
I
S
C
O
N
S
T
I
T
U
T
I
O
N
F
O
R
T
H
E
U
N
I
T
E
D
S
T
A
T
E
S
O
F
A
M
E
R
I
C
A
You can't tell from here but basically it is one letter per line.
However, I want it to say:
WE THE PEOPLE OF THE UNITED STATES, IN ORDER TO FORM A MORE PERFECT UNION,
ESTABLISH JUSTICE, INSURE DOMESTIC TRANQUILITY, PROVIDE FOR THE COMMON DEFENSE,
PROMOTE THE GENERAL WELFARE, AND SECURE THE BLESSINGS OF LIBERTY TO OURSELVES
AND OUR POSTERITY, DO ORDAIN AND ESTABLISH THIS CONSTITUTION FOR THE UNITED
STATES OF AMERICA.
What is the code I must add to my program in order for this to happen?
|
[
"I don't know what that one-character-a-line is about because you didn't tell us the reason, but the textwrap module will give you what you want:\ns=\"WE THE PEOPLE OF THE UNITED STATES, IN ORDER TO FORM A MORE PERFECT UNION, ESTABLISH JUSTICE, INSURE DOMESTIC TRANQUILITY, PROVIDE FOR THE COMMON DEFENSE, PROMOTE THE GENERAL WELFARE, AND SECURE THE BLESSINGS OF LIBERTY TO OURSELVES AND OUR POSTERITY, DO ORDAIN AND ESTABLISH THIS CONSTITUTION FOR THE UNITED STATES OF AMERICA.\"\n\nimport textwrap\nprint \"\\n\".join(textwrap.wrap(s, 80))\n\nI reconstructed your original code from your comment, and this is a corrected version:\n# You don't even use this so why import it? --> import string\n\ndef main():\n user_string = raw_input()\n all_caps = user_string.upper() # guess you wanted to make it uppercase\n output = [] # this will hold the decoded characters\n\n for char in all_caps:\n if char.isalpha():\n value = ord(char)\n if 70 <= value <= 90: # look at this, almost no other programming language supports that syntax\n num = value - 5\n elif 65 <= value <= 69:\n num = value + 21\n output.append(chr(num)) # add the decoded character to the output list\n else:\n output.append(char) # add the character verbatim to the output list (e.g. whitespace)\n\n print \"\".join(output) # print out the list by putting it together into a string\n\nmain()\n\n",
"Do you do something like this:\nfor char in string:\n print char\n\n? If yes, fix that to:\nfor char in string:\n print char,\n\nthe comma(,) at the end of the line omits the newline print normally prints.\nBut even that is probably not what you want (since it prints a space after each char), the following code should fix that, too:\nimport sys\nfor char in string:\n sys.stdout.write(char)\n\n",
"print s[0],\ni = 1\nfor char in s[1:]:\n if i%80:\n print \"\\bchar\",\n else:\n print \"\\b\\n\"\n i += 1\n\n"
] |
[
6,
1,
0
] |
[] |
[] |
[
"character",
"python",
"string",
"word_wrap"
] |
stackoverflow_0002345384_character_python_string_word_wrap.txt
|
Q:
Pyunit: "Import Site"
Using pyUnit to do what is currently a very small and simple unit test I am getting the message:
'import site' failed; use -v for traceback
...
____________________________________________
Ran 3 tests in 0.094S
When I rerun the unit test with the -v parameter, it returns verbose information about each of the 3 tests and has no error or failure messages.
What does this message mean?
A:
The first thing to know is that the message you're seeing is from the Python interpreter, and has nothing to do with pyUnit. The -v in the message refers to "python -v".
As to why you can't import site, and why running pyUnit with -v makes the error go away, I don't know. Do you have your own site.py?
|
Pyunit: "Import Site"
|
Using pyUnit to do what is currently a very small and simple unit test I am getting the message:
'import site' failed; use -v for traceback
...
____________________________________________
Ran 3 tests in 0.094S
When I rerun the unit test with the -v parameter, it returns verbose information about each of the 3 tests and has no error or failure messages.
What does this message mean?
|
[
"The first thing to know is that the message you're seeing is from the Python interpreter, and has nothing to do with pyUnit. The -v in the message refers to \"python -v\".\nAs to why you can't import site, and why running pyUnit with -v makes the error go away, I don't know. Do you have your own site.py?\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_unittest",
"unit_testing"
] |
stackoverflow_0002345331_python_python_unittest_unit_testing.txt
|
Q:
using a key to rearrange string
Using Python I want to randomly rearrange sections of a string based on a given key. I also want to restore the original string with the same key:
def rearrange(key, data):
pass
def restore(key, rearranged_data):
pass
Efficiency is not important. Any ideas?
Edit:
can assume key is hashable, but may be multiple types
definition of section for ignacio
A:
Use random.shuffle with the key as a seed:
import random
def rearrange(key, data):
random.seed(key)
d = list(data)
random.shuffle(d)
return ''.join(d)
def restore(key, rearranged_data):
l = len(rearranged_data)
random.seed(key)
d = range(l)
random.shuffle(d)
s = [None] * l
for i in range(l):
s[d[i]] = rearranged_data[i]
return ''.join(s)
x = rearrange(42, 'Hello, world!')
print x
print restore(42, x)
Output:
oelwrd!, llHo
Hello, world!
A:
you can reinvent the wheel, but why not try an encryption library first, if possible.
A:
An implementation that reverses the shuffling with sort():
import random
def reorder_list(ls, key):
random.seed(key)
random.shuffle(ls)
def reorder(s, key):
data = list(s)
reorder_list(data, key)
return ''.join(data)
def restore(s, key):
indexes = range(len(s))
reorder_list(indexes, key)
restored = sorted(zip(indexes, list(s)))
return ''.join(c for _, c in restored)
|
using a key to rearrange string
|
Using Python I want to randomly rearrange sections of a string based on a given key. I also want to restore the original string with the same key:
def rearrange(key, data):
pass
def restore(key, rearranged_data):
pass
Efficiency is not important. Any ideas?
Edit:
can assume key is hashable, but may be multiple types
definition of section for ignacio
|
[
"Use random.shuffle with the key as a seed:\nimport random\n\ndef rearrange(key, data):\n random.seed(key)\n d = list(data)\n random.shuffle(d)\n return ''.join(d)\n\ndef restore(key, rearranged_data):\n l = len(rearranged_data)\n random.seed(key)\n d = range(l)\n random.shuffle(d)\n s = [None] * l\n for i in range(l):\n s[d[i]] = rearranged_data[i]\n return ''.join(s)\n\n\nx = rearrange(42, 'Hello, world!')\nprint x\nprint restore(42, x)\n\nOutput:\noelwrd!, llHo\nHello, world!\n\n",
"you can reinvent the wheel, but why not try an encryption library first, if possible.\n",
"An implementation that reverses the shuffling with sort():\nimport random\n\ndef reorder_list(ls, key):\n random.seed(key)\n random.shuffle(ls)\n\ndef reorder(s, key):\n data = list(s)\n reorder_list(data, key)\n return ''.join(data)\n\ndef restore(s, key):\n indexes = range(len(s))\n reorder_list(indexes, key)\n restored = sorted(zip(indexes, list(s)))\n return ''.join(c for _, c in restored)\n\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"algorithm",
"encryption",
"python",
"string"
] |
stackoverflow_0002345628_algorithm_encryption_python_string.txt
|
Q:
pygresql - insert and return serial
I'm using PyGreSQL to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field:
create table job_runners (
id SERIAL PRIMARY KEY,
hostname varchar(100) not null,
is_available boolean default FALSE
);
sql = "insert into job_runners (hostname) values ('localhost')"
When I used the db.insert(), which made the most sense, I received an "AttributeError". And when I tried db.query(sql) I get nothing but an OID.
Q: Using PyGreSQL what is the best way to insert records and return the value of the ID field without doing any additional reads or queries?
A:
INSERT INTO job_runners
(hostname,is_available) VALUES ('localhost',true)
RETURNING id
That said, I have no idea about pygresql, but by what you've already written, I guess it's db.query() that you want to use here.
A:
The documentation in PyGreSQL says that if you call dbconn.query() with and insert/update statement that it will return the OID. It goes on to say something about lists of OIDs when there are multiple rows involved.
First of all; I found that the OID features did not work. I suppose knowing the version numbers of the libs and tools would have helped, however, I was not trying to return the OID.
Finally; by appending "returning id", as suggested by @hacker, pygresql simply did the right thing and returned a record-set with the ID in the resulting dictionary (see code below).
sql = "insert into job_runners (hostname) values ('localhost') returning id"
rv = dbconn.query(sql)
id = rv.dictresult()[0]['id']
A:
Assuming you have a cursor object cur:
cur.execute("INSERT INTO job_runners (hostname) VALUES (%(hostname)s) RETURNING id",
{'hostname': 'localhost'})
id = cur.fetchone()[0]
This ensures PyGreSQL correctly escapes the input string, preventing SQL injection.
|
pygresql - insert and return serial
|
I'm using PyGreSQL to access my DB. In the use-case I'm currently working on; I am trying to insert a record into a table and return the last rowid... aka the value that the DB created for my ID field:
create table job_runners (
id SERIAL PRIMARY KEY,
hostname varchar(100) not null,
is_available boolean default FALSE
);
sql = "insert into job_runners (hostname) values ('localhost')"
When I used the db.insert(), which made the most sense, I received an "AttributeError". And when I tried db.query(sql) I get nothing but an OID.
Q: Using PyGreSQL what is the best way to insert records and return the value of the ID field without doing any additional reads or queries?
|
[
"INSERT INTO job_runners\n (hostname,is_available) VALUES ('localhost',true)\n RETURNING id\n\nThat said, I have no idea about pygresql, but by what you've already written, I guess it's db.query() that you want to use here.\n",
"The documentation in PyGreSQL says that if you call dbconn.query() with and insert/update statement that it will return the OID. It goes on to say something about lists of OIDs when there are multiple rows involved.\nFirst of all; I found that the OID features did not work. I suppose knowing the version numbers of the libs and tools would have helped, however, I was not trying to return the OID.\nFinally; by appending \"returning id\", as suggested by @hacker, pygresql simply did the right thing and returned a record-set with the ID in the resulting dictionary (see code below).\nsql = \"insert into job_runners (hostname) values ('localhost') returning id\"\nrv = dbconn.query(sql)\nid = rv.dictresult()[0]['id']\n\n",
"Assuming you have a cursor object cur:\ncur.execute(\"INSERT INTO job_runners (hostname) VALUES (%(hostname)s) RETURNING id\",\n {'hostname': 'localhost'})\nid = cur.fetchone()[0]\n\nThis ensures PyGreSQL correctly escapes the input string, preventing SQL injection.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"postgresql",
"pygresql",
"python"
] |
stackoverflow_0001438430_postgresql_pygresql_python.txt
|
Q:
Does turning a list into a set, then back again, cause problems in Python?
I'm turning a list into a set in Python, like so:
request.session['vote_set'] = set(request.session['vote_set'])
So I can easily do a if x in set lookup and eliminate duplicates. Then, when I'm done, I reconvert it:
request.session['vote_set'] = list(request.session['vote_set'])
Is there a better way to do this? Am I potentially doing something dangerous (or stupid)?
A:
You'll lose duplicates if you actually wanted them. If this is actually a list of "votes" as your naming suggests, you'd 'lose' some :)
why not just:
if x in set(request.session['vote_set'])
if you're worried.
Although I have to wonder if that would be slower than just plain:
if x in request.session['vote_set']
And ordering, as others have mentioned, would potentially (most likely) be lost.
A:
You'll lose ordering, if that's important to you.
A:
This is how you remove duplicates AND maintain the order (if you care): Algorithm - How to delete duplicate elements in a list efficiently?
The other answers showed how to turn a list into a set.
|
Does turning a list into a set, then back again, cause problems in Python?
|
I'm turning a list into a set in Python, like so:
request.session['vote_set'] = set(request.session['vote_set'])
So I can easily do a if x in set lookup and eliminate duplicates. Then, when I'm done, I reconvert it:
request.session['vote_set'] = list(request.session['vote_set'])
Is there a better way to do this? Am I potentially doing something dangerous (or stupid)?
|
[
"You'll lose duplicates if you actually wanted them. If this is actually a list of \"votes\" as your naming suggests, you'd 'lose' some :)\nwhy not just:\nif x in set(request.session['vote_set'])\n\nif you're worried.\nAlthough I have to wonder if that would be slower than just plain:\nif x in request.session['vote_set']\n\nAnd ordering, as others have mentioned, would potentially (most likely) be lost.\n",
"You'll lose ordering, if that's important to you. \n",
"This is how you remove duplicates AND maintain the order (if you care): Algorithm - How to delete duplicate elements in a list efficiently?\nThe other answers showed how to turn a list into a set.\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002345862_python.txt
|
Q:
Why is post_save being raised twice during the save of a Django model?
I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified.
The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it can't be right.
A quick example, just printing the model to the console (using the dev server):
from blog.models import Post
from django.db.models import signals
def purge_cache(sender, **kwargs):
print 'Purging %s' % sender
signals.post_save.connect(purge_cache, sender=Post)
This is using the stable 1.1.1 release of Django.
Updated Information:
With feedback from everyone's comments, I have modified my question because the issue is now discovering why the post_save is being triggered twice. My guess at the moment is that my models.py code is imported twice and that the post_save is getting connected multiple times.
What would be the best way to figure out why it is being imported/ran twice?
A:
Apparently, Python is sensitive to the way you import modules. In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED_APPS configuration, which I assume is used by Django to do an initial import.
Inside my blog application I was using imports such as:
from blog.models import *
My settings.py was configured as:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
...snip...
'sorl.thumbnail',
'mysite.blog',
)
The "mysite" prefix was added because I originally had import path issues when deploying the site. Later I fixed this issue (so it acted the same as the development server) by adding multiple paths in my WSGI script.
Removing the "mysite" prefix from the settings.py fixed the issue:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
...snip...
'sorl.thumbnail',
'blog',
)
A:
While looking for the root of this problem, you can use quick workaround to prevent registering signal twice:
signals.post_save.connect(my_handler, MyModel, dispatch_uid="path.to.this.module")
Source.
A:
Here is the ticket about this issue: Django's signal framework may register listeners more than once #3951. It is now fixed in SVN version of Django.
The problem is exactly as You said: Your module which registers signal, is loaded couple of times, in some cases by different import paths, thus each imported modules this way are wrongly interpreted by Django as different modules which registers the same signal.
|
Why is post_save being raised twice during the save of a Django model?
|
I am attaching a method to the post_save signal of my Django model. This way I can clear some cached items whenever the model is modified.
The problem I am having is that the signal is being triggered twice when the model is saved. It doesn't necessarily hurt anything (the code will just gracefully error out) but it can't be right.
A quick example, just printing the model to the console (using the dev server):
from blog.models import Post
from django.db.models import signals
def purge_cache(sender, **kwargs):
print 'Purging %s' % sender
signals.post_save.connect(purge_cache, sender=Post)
This is using the stable 1.1.1 release of Django.
Updated Information:
With feedback from everyone's comments, I have modified my question because the issue is now discovering why the post_save is being triggered twice. My guess at the moment is that my models.py code is imported twice and that the post_save is getting connected multiple times.
What would be the best way to figure out why it is being imported/ran twice?
|
[
"Apparently, Python is sensitive to the way you import modules. In my case, it wasn't an issue with any of import code inside my blog application but an issue with the INSTALLED_APPS configuration, which I assume is used by Django to do an initial import.\nInside my blog application I was using imports such as:\nfrom blog.models import *\n\nMy settings.py was configured as:\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n ...snip...\n 'sorl.thumbnail',\n 'mysite.blog',\n)\n\nThe \"mysite\" prefix was added because I originally had import path issues when deploying the site. Later I fixed this issue (so it acted the same as the development server) by adding multiple paths in my WSGI script.\nRemoving the \"mysite\" prefix from the settings.py fixed the issue:\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n ...snip...\n 'sorl.thumbnail',\n 'blog',\n)\n\n",
"While looking for the root of this problem, you can use quick workaround to prevent registering signal twice:\nsignals.post_save.connect(my_handler, MyModel, dispatch_uid=\"path.to.this.module\")\n\nSource.\n",
"Here is the ticket about this issue: Django's signal framework may register listeners more than once #3951. It is now fixed in SVN version of Django.\nThe problem is exactly as You said: Your module which registers signal, is loaded couple of times, in some cases by different import paths, thus each imported modules this way are wrongly interpreted by Django as different modules which registers the same signal.\n"
] |
[
13,
9,
1
] |
[] |
[] |
[
"django",
"django_models",
"python",
"signals"
] |
stackoverflow_0002345400_django_django_models_python_signals.txt
|
Q:
In python, I need to store one element of the source of an html page as a string. How can I do this?
So far I have managed to write some code that should print the source of the page. The problem is, it doesn't. I tried it with another web site, and it printed it out fine, so I used wget on the page "http://www.whitepages.com/carrier_lookup?carrier=other&number_0=2165138899&response=1" which should download the page for me. It gave " ERROR 403: Forbidden. ", so I'm not really sure how to access the html now.
The second part of the problem is that when I manage to download the html and save it as a string, I need to save as a different string the carrier that the search found. This is accessible as the line under the [div class="carrier_result"] line in the source code. In the previous sentence I replaced the < and > with brackets because sourceforge would not let me post the html.
So far the code I have is: http://pastebin.com/u4HUv3Rj
Thanks to anyone who helps me with this.
A:
For an explanation of what a 403 result from HTTP means, and how to deal with it, see here.
I have no idea what "I need to save as a different string the carrier that the search found" can possibly mean -- I can't even parse it as an English sentence, nor do I know what "the line under the line" means either. Please rephrase (if English isn't your native language, I can try grokking Italian, French, Spanish, German, or Latin -- in decreasing probability and with no guarantee of success, but it can't be worse than w/your current phrasing;-).
|
In python, I need to store one element of the source of an html page as a string. How can I do this?
|
So far I have managed to write some code that should print the source of the page. The problem is, it doesn't. I tried it with another web site, and it printed it out fine, so I used wget on the page "http://www.whitepages.com/carrier_lookup?carrier=other&number_0=2165138899&response=1" which should download the page for me. It gave " ERROR 403: Forbidden. ", so I'm not really sure how to access the html now.
The second part of the problem is that when I manage to download the html and save it as a string, I need to save as a different string the carrier that the search found. This is accessible as the line under the [div class="carrier_result"] line in the source code. In the previous sentence I replaced the < and > with brackets because sourceforge would not let me post the html.
So far the code I have is: http://pastebin.com/u4HUv3Rj
Thanks to anyone who helps me with this.
|
[
"For an explanation of what a 403 result from HTTP means, and how to deal with it, see here.\nI have no idea what \"I need to save as a different string the carrier that the search found\" can possibly mean -- I can't even parse it as an English sentence, nor do I know what \"the line under the line\" means either. Please rephrase (if English isn't your native language, I can try grokking Italian, French, Spanish, German, or Latin -- in decreasing probability and with no guarantee of success, but it can't be worse than w/your current phrasing;-).\n"
] |
[
1
] |
[] |
[] |
[
"html",
"parsing",
"python"
] |
stackoverflow_0002346154_html_parsing_python.txt
|
Q:
How can I remove part of an string on the re.search result?
text = urllib.urlopen('www.text.com').read()
frase = re.search("your text here(.*)", text).group()
With these code, I get the result as "your text here mister"...
How can I remove the your text here from the result, staying only with the "mister" part?
A:
Specify the number of the group (= thing between parenthesis in the regex) you want to receive in the call to group():
frase = re.search(...).group(1)
A:
don't need regex
text = urllib.urlopen('www.text.com').read()
print ''.join( text.split("your text here")[1:] )
|
How can I remove part of an string on the re.search result?
|
text = urllib.urlopen('www.text.com').read()
frase = re.search("your text here(.*)", text).group()
With these code, I get the result as "your text here mister"...
How can I remove the your text here from the result, staying only with the "mister" part?
|
[
"Specify the number of the group (= thing between parenthesis in the regex) you want to receive in the call to group():\nfrase = re.search(...).group(1)\n\n",
"don't need regex\ntext = urllib.urlopen('www.text.com').read()\nprint ''.join( text.split(\"your text here\")[1:] )\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002346215_python.txt
|
Q:
How can you draw a bezier curve given four points with wxPython?
It appears to me that the DC's only support for curves of any sort is with splines. Are there any libraries that add bezier functionality, or is there a way to convert a bezier curve into a spline?
A:
Given 4 control points, the formula for the associated cubic Bezier curve is not hard to compute. Once you calculate a set of points on the curve, you could use DC.DrawLines to draw it.
There is a python implementation for calculating points on generalized Bezier curves (shameless plug) here. It's generalized in the sense that it can accept an arbitrary number of control points (>2) as input to make_bezier. If you want only the 4-control point version, you can cut out pascal_row entirely and replace
combinations=pascal_row(n-1)
with
combinations=(1,3,3,1)
A:
After a little googling, I think I'll go with wx.GraphicsContext, which supports wx.GraphicsPath. It appears to have exactly what I need, in addition to anti-aliasing (according to this page)
|
How can you draw a bezier curve given four points with wxPython?
|
It appears to me that the DC's only support for curves of any sort is with splines. Are there any libraries that add bezier functionality, or is there a way to convert a bezier curve into a spline?
|
[
"Given 4 control points, the formula for the associated cubic Bezier curve is not hard to compute. Once you calculate a set of points on the curve, you could use DC.DrawLines to draw it.\nThere is a python implementation for calculating points on generalized Bezier curves (shameless plug) here. It's generalized in the sense that it can accept an arbitrary number of control points (>2) as input to make_bezier. If you want only the 4-control point version, you can cut out pascal_row entirely and replace \ncombinations=pascal_row(n-1)\n\nwith\ncombinations=(1,3,3,1)\n\n",
"After a little googling, I think I'll go with wx.GraphicsContext, which supports wx.GraphicsPath. It appears to have exactly what I need, in addition to anti-aliasing (according to this page)\n"
] |
[
2,
1
] |
[] |
[] |
[
"bezier",
"python",
"spline",
"wxpython"
] |
stackoverflow_0002346054_bezier_python_spline_wxpython.txt
|
Q:
Is it OK to do 302s for architecture in my web applciation?
For example, in my index(request):
def index(request):
if logged_in:
return HttpResponseRedirect("/home_profile")
else:
return HttpResponseRedirect("/login")
This way, when the user hits my home page...he is redirected appropriately. Is this a good architecture? Or will this cause caching problems, etc?
A:
Redirection is ok(302 shouldn't cause any caching problem, as 302's are temporary), but why you need to have redirection in both if and else. Better way is to redirect to login page if not logged-in, view should otherwise return the response, instead of unnecessarily redirecting e.g.
def home(request):
if not logged_in:
return HttpResponseRedirect("/login?next=%s"%reverse("home"))
return HttpResponse(...)
you can do same thing in each view where user needs to be logged in, else make a login decorator, djago auth already has login_required or make a login middleware which will do it for every request.
Also note I am passing the next url to visit after login, because usually I would like to land where i was heading.
|
Is it OK to do 302s for architecture in my web applciation?
|
For example, in my index(request):
def index(request):
if logged_in:
return HttpResponseRedirect("/home_profile")
else:
return HttpResponseRedirect("/login")
This way, when the user hits my home page...he is redirected appropriately. Is this a good architecture? Or will this cause caching problems, etc?
|
[
"Redirection is ok(302 shouldn't cause any caching problem, as 302's are temporary), but why you need to have redirection in both if and else. Better way is to redirect to login page if not logged-in, view should otherwise return the response, instead of unnecessarily redirecting e.g.\ndef home(request):\n if not logged_in:\n return HttpResponseRedirect(\"/login?next=%s\"%reverse(\"home\"))\n\n return HttpResponse(...)\n\nyou can do same thing in each view where user needs to be logged in, else make a login decorator, djago auth already has login_required or make a login middleware which will do it for every request.\nAlso note I am passing the next url to visit after login, because usually I would like to land where i was heading.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python",
"redirect"
] |
stackoverflow_0002347074_django_python_redirect.txt
|
Q:
Regular expression to ignore a certain number of character repetitions
I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string.
Given a string like:
This | is || token || some ||| text
I would like to end up with:
This \| is || token || some \|\|\| text
where all of the | are escaped unless there are two of them together.
Is there a regular expression that will allow me to escape every | that isn't in a pair?
A:
No need regex. You are using Python after all. :)
>>> s="This | is || token || some ||| text"
>>> items=s.split()
>>> items
['This', '|', 'is', '||', 'token', '||', 'some', '|||', 'text']
>>> for n,i in enumerate(items):
... if "|" in i and i.count("|")!=2:
... items[n]=i.replace("|","\|")
...
>>> print ' '.join(items)
This \| is || token || some \|\|\| text
A:
I don't see why you would need to regex-escape the tokens, but why not split up the string first and then escape them? This regex splits on two pipes that aren't preceded or followed by more pipes:
re.split('(?<!\|)\|\|(?!\|)', 'This | is || token || some ||| text')
>>> ['This | is ', ' token ', ' some ||| text']
By the way, there are testers for all of the more common regex flavors out there for the Googling. Here's one for Python: http://re.dabase.com/
A:
Here's a way to do it with regular expressions in perl, if anyone's interested. I used two separate regular expressions, one for the single match and one for the 3 or more match. I'm sure it's possible to combine them, but regular expressions are already difficult enough to read without adding needless complexity.
#!/usr/bin/perl
#$s = "This | is || token || some ||| text";
$s = "| This |||| is || more | evil |";
$s =~ s/([^|]|^)(\|)([^|]|$)/\1\\\2\3/g;
$s =~ s{(\|{3,})}
{
$a = $1;
$a =~ s{\|} {\\\|}g;
$a;
}eg;
print $s . "\n";
Outputs:
\| This \|\|\|\| is || more \| evil \|
|
Regular expression to ignore a certain number of character repetitions
|
I'm trying to write a parser that uses two characters as token boundaries, but I can't figure out the regular expression that will allow me to ignore them when I'm regex-escaping the whole string.
Given a string like:
This | is || token || some ||| text
I would like to end up with:
This \| is || token || some \|\|\| text
where all of the | are escaped unless there are two of them together.
Is there a regular expression that will allow me to escape every | that isn't in a pair?
|
[
"No need regex. You are using Python after all. :)\n>>> s=\"This | is || token || some ||| text\"\n>>> items=s.split()\n>>> items\n['This', '|', 'is', '||', 'token', '||', 'some', '|||', 'text']\n>>> for n,i in enumerate(items):\n... if \"|\" in i and i.count(\"|\")!=2:\n... items[n]=i.replace(\"|\",\"\\|\")\n...\n>>> print ' '.join(items)\nThis \\| is || token || some \\|\\|\\| text\n\n",
"I don't see why you would need to regex-escape the tokens, but why not split up the string first and then escape them? This regex splits on two pipes that aren't preceded or followed by more pipes:\nre.split('(?<!\\|)\\|\\|(?!\\|)', 'This | is || token || some ||| text')\n>>> ['This | is ', ' token ', ' some ||| text']\n\nBy the way, there are testers for all of the more common regex flavors out there for the Googling. Here's one for Python: http://re.dabase.com/\n",
"Here's a way to do it with regular expressions in perl, if anyone's interested. I used two separate regular expressions, one for the single match and one for the 3 or more match. I'm sure it's possible to combine them, but regular expressions are already difficult enough to read without adding needless complexity.\n#!/usr/bin/perl\n\n#$s = \"This | is || token || some ||| text\";\n$s = \"| This |||| is || more | evil |\";\n\n$s =~ s/([^|]|^)(\\|)([^|]|$)/\\1\\\\\\2\\3/g;\n$s =~ s{(\\|{3,})}\n{\n $a = $1;\n $a =~ s{\\|} {\\\\\\|}g;\n $a;\n}eg;\n\nprint $s . \"\\n\";\n\nOutputs: \n\\| This \\|\\|\\|\\| is || more \\| evil \\|\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"python",
"regex",
"regex_negation"
] |
stackoverflow_0002346917_python_regex_regex_negation.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.