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:
Python GIL and globals
In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism?
A:
The GIL only requires that the interpreter completely executes a single bytecode instruction before another thread can take over. However, there is no reason to assume that an increment operation is a single instruction. For example:
>>> import dis
>>> dis.dis(compile("x=753","","exec"))
1 0 LOAD_CONST 0 (753)
3 STORE_NAME 0 (x)
6 LOAD_CONST 1 (None)
9 RETURN_VALUE
>>> dis.dis(compile("x+=1","","exec"))
1 0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (1)
6 INPLACE_ADD
7 STORE_NAME 0 (x)
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
As you can see, even these simple operations are more than a single bytecode instruction. Therefore, whenever sharing data between threads, you must use a separate locking mechanism (eg, threading.lock) in order to maintain data consistency.
A:
Yes, multithreading without locking almost always causes problems, with or without a GIL.
|
Python GIL and globals
|
In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism?
|
[
"The GIL only requires that the interpreter completely executes a single bytecode instruction before another thread can take over. However, there is no reason to assume that an increment operation is a single instruction. For example:\n>>> import dis\n>>> dis.dis(compile(\"x=753\",\"\",\"exec\"))\n 1 0 LOAD_CONST 0 (753)\n 3 STORE_NAME 0 (x)\n 6 LOAD_CONST 1 (None)\n 9 RETURN_VALUE\n>>> dis.dis(compile(\"x+=1\",\"\",\"exec\"))\n 1 0 LOAD_NAME 0 (x)\n 3 LOAD_CONST 0 (1)\n 6 INPLACE_ADD\n 7 STORE_NAME 0 (x)\n 10 LOAD_CONST 1 (None)\n 13 RETURN_VALUE\n\nAs you can see, even these simple operations are more than a single bytecode instruction. Therefore, whenever sharing data between threads, you must use a separate locking mechanism (eg, threading.lock) in order to maintain data consistency.\n",
"Yes, multithreading without locking almost always causes problems, with or without a GIL.\n"
] |
[
6,
3
] |
[] |
[] |
[
"gil",
"python"
] |
stackoverflow_0002157208_gil_python.txt
|
Q:
Calling An Inherited Class Method From Java
In Python, class methods can be inherited. e.g.
>>> class A:
... @classmethod
... def main(cls):
... return cls()
...
>>> class B(A): pass
...
>>> b=B.main()
>>> b
<__main__.B instance at 0x00A6FA58>
How would you do the equivalent in Java? I currently have:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
@Override
public void show(){
System.out.println("B");
}
}
I'd like to call B.main() and have it print "B", but clearly it will print "A" instead, since "new A()" is hardcoded.
How would you change "new A()" so that it's parameterized to use the class it's in when called, and not the hard-coded class A?
A:
Your class B does not have a main method and static methods are not inherited.
A:
The only way I can see this happening is to find whatever is calling A.main( String[] arg ) and change it to call B.main instead.
B.main:
public static void main( String[] arg ) {
new B().run();
}
How is your program started? Is there a batch file, shortcut, etc? Something you can change? Where does A.main get called?
A:
Static methods in java are not classmethods they are staticmethods. In general it is not possible to know which class reference the static method was called from.
A:
I think this isn't possible. Here's why:
In Java, the implementation of a method is determined by the instance's run-time type. So, to execute B.show(), you need to have an instance of B. The only way I could see to do this, if the method that constructs the instance is supposed to be inherited, is to use Class.newInstance() to construct an instance of a type that's not known at runtime.
The problem with that is that within a static method, you have no reference to the containing class, so you don't know whose newInstance method to call.
Why do you want to do this, though? There may be some better way to achieve whatever it is you want to achieve.
A:
In your example I wouldn't put your main method inside of A. This is setup as the entry point into the system (you can't be in B if you are specifically entering into A).
In the example below I created class A, B, and C. Class C instantiates A and B and runs them. Notice that in C I created an A, a B, and another A that I instantiate as a B. My output is:
A
B
B
Hopefully this makes sense.
public class A {
public void show(){
System.out.println("A");
}
public void run(){
show();
}
}
public class B extends A {
@Override
public void show(){
System.out.println("B");
}
}
public class C {
public static void main(String[] args) {
A a = new A();
B b = new B();
A anothera = new B();
a.show();
b.show();
anothera.show();
}
}
|
Calling An Inherited Class Method From Java
|
In Python, class methods can be inherited. e.g.
>>> class A:
... @classmethod
... def main(cls):
... return cls()
...
>>> class B(A): pass
...
>>> b=B.main()
>>> b
<__main__.B instance at 0x00A6FA58>
How would you do the equivalent in Java? I currently have:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
@Override
public void show(){
System.out.println("B");
}
}
I'd like to call B.main() and have it print "B", but clearly it will print "A" instead, since "new A()" is hardcoded.
How would you change "new A()" so that it's parameterized to use the class it's in when called, and not the hard-coded class A?
|
[
"Your class B does not have a main method and static methods are not inherited.\n",
"The only way I can see this happening is to find whatever is calling A.main( String[] arg ) and change it to call B.main instead.\nB.main:\n public static void main( String[] arg ) {\n new B().run();\n }\n\nHow is your program started? Is there a batch file, shortcut, etc? Something you can change? Where does A.main get called?\n",
"Static methods in java are not classmethods they are staticmethods. In general it is not possible to know which class reference the static method was called from.\n",
"I think this isn't possible. Here's why:\nIn Java, the implementation of a method is determined by the instance's run-time type. So, to execute B.show(), you need to have an instance of B. The only way I could see to do this, if the method that constructs the instance is supposed to be inherited, is to use Class.newInstance() to construct an instance of a type that's not known at runtime.\nThe problem with that is that within a static method, you have no reference to the containing class, so you don't know whose newInstance method to call.\nWhy do you want to do this, though? There may be some better way to achieve whatever it is you want to achieve.\n",
"In your example I wouldn't put your main method inside of A. This is setup as the entry point into the system (you can't be in B if you are specifically entering into A).\nIn the example below I created class A, B, and C. Class C instantiates A and B and runs them. Notice that in C I created an A, a B, and another A that I instantiate as a B. My output is:\nA\nB\nB\nHopefully this makes sense.\npublic class A { \npublic void show(){ \n System.out.println(\"A\"); \n } \n\npublic void run(){ \n show(); \n } \n} \n\npublic class B extends A { \n @Override \n public void show(){ \n System.out.println(\"B\"); \n } \n } \n\npublic class C {\npublic static void main(String[] args) {\n A a = new A();\n B b = new B();\n A anothera = new B();\n\n a.show();\n b.show();\n anothera.show();\n }\n}\n\n"
] |
[
1,
1,
1,
0,
0
] |
[] |
[] |
[
"class_method",
"inheritance",
"java",
"python"
] |
stackoverflow_0002157159_class_method_inheritance_java_python.txt
|
Q:
exe generated with py2exe can't find pywinauto
I've been trying to pack my app with py2exe. The application works fine but it keeps failing to find/use pywinauto. I been googling but I get nothing, I'm now I'm totally lost...
Here's the packing script:
from distutils.core import setup
setup(
windows = ["mainForm.py"],
data_files=[
('', ['mainForm.ui']),
('', ['osk.sqlite'])
],
options = {
"py2exe":{
"optimize": 2,
"includes": [
'sip', 'pyttsx.drivers.sapi5', 'win32com', 'xml.etree.ElementTree', 'sqlite3',
'pywinauto', 'pywinauto.application', 'pywinauto.controls', 'pywinauto.tests', 'SendKeys'
],
"typelibs": [('{C866CA3A-32F7-11D2-9602-00C04F8EE628}', 0, 5, 0)]
}
}
)
And here's the ouput when running the exe
Traceback (most recent call last):
File "mainForm.py", line 129, in changeState
File "mainForm.py", line 230, in setWriteMode
File "mainForm.py", line 105, in FillApps
File "WindowHandler.pyo", line 26, in getWindowList
NameError: global name 'pywinauto' is not defined
I hope anyone could point me into the right direct.
Thanks in advance
A:
From my experience, py2exe handles imports in a weird way. Sometimes it has trouble finding linked-imports (like you import WindowHandler, which imports pywinauto).
I would start with this in mainForm.py:
import sys
import WordOps
import Voice
import WindowHandler
from PyQt import QtCore, QtGui, uic
And in setup.py, start with this:
options={'py2exe':{
'includes': ['sip'],
'bundle_files': 1
}
}
Make sure your program works before compiling to an exe, then try running setup.py.
When you start getting errors when running setup.py (like the one you posted), add more imports to mainForm.py. So for that error, your new header will look like:
import sys
import WordOps
import Voice
import WindowHandler
from PyQt import QtCore, QtGui, uic
# imports for py2exe
import pywinauto
It will not break your code because it will just be an "unused" import.
Keep doing that until setup.py works.
|
exe generated with py2exe can't find pywinauto
|
I've been trying to pack my app with py2exe. The application works fine but it keeps failing to find/use pywinauto. I been googling but I get nothing, I'm now I'm totally lost...
Here's the packing script:
from distutils.core import setup
setup(
windows = ["mainForm.py"],
data_files=[
('', ['mainForm.ui']),
('', ['osk.sqlite'])
],
options = {
"py2exe":{
"optimize": 2,
"includes": [
'sip', 'pyttsx.drivers.sapi5', 'win32com', 'xml.etree.ElementTree', 'sqlite3',
'pywinauto', 'pywinauto.application', 'pywinauto.controls', 'pywinauto.tests', 'SendKeys'
],
"typelibs": [('{C866CA3A-32F7-11D2-9602-00C04F8EE628}', 0, 5, 0)]
}
}
)
And here's the ouput when running the exe
Traceback (most recent call last):
File "mainForm.py", line 129, in changeState
File "mainForm.py", line 230, in setWriteMode
File "mainForm.py", line 105, in FillApps
File "WindowHandler.pyo", line 26, in getWindowList
NameError: global name 'pywinauto' is not defined
I hope anyone could point me into the right direct.
Thanks in advance
|
[
"From my experience, py2exe handles imports in a weird way. Sometimes it has trouble finding linked-imports (like you import WindowHandler, which imports pywinauto).\nI would start with this in mainForm.py:\nimport sys\nimport WordOps \nimport Voice \nimport WindowHandler\nfrom PyQt import QtCore, QtGui, uic\n\nAnd in setup.py, start with this:\noptions={'py2exe':{\n 'includes': ['sip'],\n 'bundle_files': 1\n }\n }\n\nMake sure your program works before compiling to an exe, then try running setup.py.\nWhen you start getting errors when running setup.py (like the one you posted), add more imports to mainForm.py. So for that error, your new header will look like:\nimport sys\nimport WordOps \nimport Voice \nimport WindowHandler\nfrom PyQt import QtCore, QtGui, uic\n# imports for py2exe\nimport pywinauto\n\nIt will not break your code because it will just be an \"unused\" import.\nKeep doing that until setup.py works.\n"
] |
[
1
] |
[] |
[] |
[
"py2exe",
"python"
] |
stackoverflow_0002156875_py2exe_python.txt
|
Q:
Python: Finding average of a nested list
I have a list
a = [[1,2,3],[4,5,6],[7,8,9]]
Now I want to find the average of these inner list so that
a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3]
'a' should not be a nested list in the end. Kindly provide an answer for the generic case
A:
a = [sum(x)/len(x) for x in zip(*a)]
# a is now [4, 5, 6] for your example
In Python 2.x, if you don't want integer division, replace sum(x)/len(x) by 1.0*sum(x)/len(x) above.
Documentation for zip.
A:
If you have numpy installed:
>>> import numpy as np
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> arr = np.array(a)
>>> arr
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.mean(arr)
5.0
>>> np.mean(arr,axis=0)
array([ 4., 5., 6.])
>>> np.mean(arr,axis=1)
array([ 2., 5., 8.])
A:
>>> import itertools
>>> [sum(x)/len(x) for x in itertools.izip(*a)]
[4, 5, 6]
|
Python: Finding average of a nested list
|
I have a list
a = [[1,2,3],[4,5,6],[7,8,9]]
Now I want to find the average of these inner list so that
a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3]
'a' should not be a nested list in the end. Kindly provide an answer for the generic case
|
[
"a = [sum(x)/len(x) for x in zip(*a)]\n# a is now [4, 5, 6] for your example\n\nIn Python 2.x, if you don't want integer division, replace sum(x)/len(x) by 1.0*sum(x)/len(x) above.\nDocumentation for zip.\n",
"If you have numpy installed:\n>>> import numpy as np\n>>> a = [[1,2,3],[4,5,6],[7,8,9]]\n>>> arr = np.array(a)\n>>> arr\narray([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n>>> np.mean(arr)\n5.0\n>>> np.mean(arr,axis=0)\narray([ 4., 5., 6.])\n>>> np.mean(arr,axis=1)\narray([ 2., 5., 8.])\n\n",
">>> import itertools\n>>> [sum(x)/len(x) for x in itertools.izip(*a)]\n[4, 5, 6]\n\n"
] |
[
12,
6,
5
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002153444_python.txt
|
Q:
Using namedtuple._replace with a variable as a fieldname
Can I reference a namedtuple fieldame using a variable?
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right"])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
#retrieve the value of "left" or "right" depending on the choice
print "You won", getattr(this_prize,choice)
#replace the value of "left" or "right" depending on the choice
this_prize._replace(choice = "Yay") #this doesn't work
print this_prize
A:
Tuples are immutable, and so are NamedTuples. They are not supposed to be changed!
this_prize._replace(choice = "Yay") calls _replace with the keyword argument "choice". It doesn't use choice as a variable and tries to replace a field by the name of choice.
this_prize._replace(**{choice : "Yay"} ) would use whatever choice is as the fieldname
_replace returns a new NamedTuple. You need to reasign it: this_prize = this_prize._replace(**{choice : "Yay"} )
Simply use a dict or write a normal class instead!
A:
>>> choice = 'left'
>>> this_prize._replace(**{choice: 'Yay'}) # you need to assign this to this_prize if you want
Prize(left='Yay', right='SecondPrize')
>>> this_prize
Prize(left='FirstPrize', right='SecondPrize') # doesn't modify this_prize in place
|
Using namedtuple._replace with a variable as a fieldname
|
Can I reference a namedtuple fieldame using a variable?
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right"])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
#retrieve the value of "left" or "right" depending on the choice
print "You won", getattr(this_prize,choice)
#replace the value of "left" or "right" depending on the choice
this_prize._replace(choice = "Yay") #this doesn't work
print this_prize
|
[
"Tuples are immutable, and so are NamedTuples. They are not supposed to be changed!\nthis_prize._replace(choice = \"Yay\") calls _replace with the keyword argument \"choice\". It doesn't use choice as a variable and tries to replace a field by the name of choice. \nthis_prize._replace(**{choice : \"Yay\"} ) would use whatever choice is as the fieldname\n_replace returns a new NamedTuple. You need to reasign it: this_prize = this_prize._replace(**{choice : \"Yay\"} )\nSimply use a dict or write a normal class instead!\n",
">>> choice = 'left'\n>>> this_prize._replace(**{choice: 'Yay'}) # you need to assign this to this_prize if you want\nPrize(left='Yay', right='SecondPrize')\n>>> this_prize\nPrize(left='FirstPrize', right='SecondPrize') # doesn't modify this_prize in place\n\n"
] |
[
16,
2
] |
[] |
[] |
[
"namedtuple",
"python"
] |
stackoverflow_0002157561_namedtuple_python.txt
|
Q:
RPX, OpenID - How to write a proper SignIn Handler for AppEngine
Ive spent days searching the web and im drawing a blank -im new to python too! I simply want to integrate RPX (janrain) into Appengine - loads of code for the script inserts and the return of the openid token - that's all great - but other than that no-one seems to take it any further as in actually creating an openid login that works - why? i assume no session management?
Here is a simple class handler that gets the TOKEN for the open id and then makes a fetch to grab the users profile. All very simple using RPX.
simple handler to get the response from RPX
class RPXHandler(webapp.RequestHandler):
def get(self):
token = self.request.get('token')
url = 'https://rpxnow.com/api/v2/auth_info'
args = {
'format': 'json',
'apiKey': '#YOUR KEY#',
'token': token
}
r = urlfetch.fetch(url=url,
payload=urllib.urlencode(args),
method=urlfetch.POST,
headers={'Content-Type':'application/x-www-form-urlencoded'}
)
json = simplejson.loads(r.content)
logging.info(json)
if json['stat'] == 'ok':
unique_identifier = json['profile']['identifier']
nickname = json['profile']['preferredUsername']
email = json['profile']['email']
# log the user in using the unique_identifier
# this should your cookies or session you already have implemented
self.redirect('static/loggedin.html')
else:
self.redirect('static/error.html')
Now # here is where the problem starts - ideally we could be lazy and just log them into Google accounts - but their is no method to log a user in ie;
user.login(email)
so that abandons any hope of using google accounts - and to fair if we have open id - why bother!
SO...
What i need is my own user datastore - thats simple - and some means of identifying if the user is logged in - sessions? But in AppEngine their is no support for sessions.
I have found a few class libarys which say they deal with this but it all looks badly documented and without good code examples
Can anyone help?
A:
GAE gives you access to a database, right? Generate a secure token and store it with the user URL returned by RPX in the database. Set the secure token as a cookie so that you get it on every request - look the token up in the database and then do the rest from there.
While I'm worried about performance it actually works pretty well fro me.
A:
there is a GAE recipe that should help
http://appengine-cookbook.appspot.com/recipe/accept-google-aol-yahoo-myspace-facebook-and-openid-logins/
|
RPX, OpenID - How to write a proper SignIn Handler for AppEngine
|
Ive spent days searching the web and im drawing a blank -im new to python too! I simply want to integrate RPX (janrain) into Appengine - loads of code for the script inserts and the return of the openid token - that's all great - but other than that no-one seems to take it any further as in actually creating an openid login that works - why? i assume no session management?
Here is a simple class handler that gets the TOKEN for the open id and then makes a fetch to grab the users profile. All very simple using RPX.
simple handler to get the response from RPX
class RPXHandler(webapp.RequestHandler):
def get(self):
token = self.request.get('token')
url = 'https://rpxnow.com/api/v2/auth_info'
args = {
'format': 'json',
'apiKey': '#YOUR KEY#',
'token': token
}
r = urlfetch.fetch(url=url,
payload=urllib.urlencode(args),
method=urlfetch.POST,
headers={'Content-Type':'application/x-www-form-urlencoded'}
)
json = simplejson.loads(r.content)
logging.info(json)
if json['stat'] == 'ok':
unique_identifier = json['profile']['identifier']
nickname = json['profile']['preferredUsername']
email = json['profile']['email']
# log the user in using the unique_identifier
# this should your cookies or session you already have implemented
self.redirect('static/loggedin.html')
else:
self.redirect('static/error.html')
Now # here is where the problem starts - ideally we could be lazy and just log them into Google accounts - but their is no method to log a user in ie;
user.login(email)
so that abandons any hope of using google accounts - and to fair if we have open id - why bother!
SO...
What i need is my own user datastore - thats simple - and some means of identifying if the user is logged in - sessions? But in AppEngine their is no support for sessions.
I have found a few class libarys which say they deal with this but it all looks badly documented and without good code examples
Can anyone help?
|
[
"GAE gives you access to a database, right? Generate a secure token and store it with the user URL returned by RPX in the database. Set the secure token as a cookie so that you get it on every request - look the token up in the database and then do the rest from there.\nWhile I'm worried about performance it actually works pretty well fro me.\n",
"there is a GAE recipe that should help\nhttp://appengine-cookbook.appspot.com/recipe/accept-google-aol-yahoo-myspace-facebook-and-openid-logins/\n"
] |
[
1,
0
] |
[] |
[] |
[
"google_app_engine",
"openid",
"python",
"rpx"
] |
stackoverflow_0002149240_google_app_engine_openid_python_rpx.txt
|
Q:
How do I change which version of python mod_python uses
I'm doing some introductory work with django which seems really easy (and fun) so far but I have been doing all this from Python 2.6 which I installed in /opt/local (RedHat 5.3) because the python that came with redhat was 2.4. I set up a symlink:
/usr/bin/python2.6 -> /opt/local/bin/python
and I have been using that for all the django stuff so far; i.e.
> python2.6 manage.py runserver
However, when I try to move on to production mode, mod_python isn't using the right version of python:
Mod_python error: "PythonHandler django.core.handlers.modpython"
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch
log=debug)
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 461, in import_module
f, p, d = imp.find_module(parts[i], path)
ImportError: No module named django
I have this in my /etc/httpd/conf/httpd.conf:
<Location "/chat">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE chat.settings
PythonDebug On
PythonPath "['/www/django/chat', '/opt/local/lib/python2.6/site-packages/django/'] + sys.path"
</Location>
So my question is, how do I make mod_python look for python2.6 instead of python?
A:
You would have to rebuild mod_python against your python2.6 installation. Since mod_python loads python as a library the version is fixed at compile time.
A:
Don't use mod_python any more. mod_wsgi is the recommended way to deploy Django appliations now.
A:
You can rebuild mod_python to link against libpython dynamically so that you can pick up version updates to your libpython but it takes some chicanery.
You will need to edit the configure script for mod_python as follows (remove -L${PyLIBPL}):
$ diff configure.orig configure
< LDFLAGS="${LDFLAGS} -L${PyLIBPL}"
---
> LDFLAGS="${LDFLAGS}"
Then do
configure --with-python=/path/to/bin/python ; make; make install dance.
When you run:
ldd mod_python.so
you should see a line that looks like:
libpython2.6.so.1.0 => /usr/lib/libpython2.6.so.1.0
|
How do I change which version of python mod_python uses
|
I'm doing some introductory work with django which seems really easy (and fun) so far but I have been doing all this from Python 2.6 which I installed in /opt/local (RedHat 5.3) because the python that came with redhat was 2.4. I set up a symlink:
/usr/bin/python2.6 -> /opt/local/bin/python
and I have been using that for all the django stuff so far; i.e.
> python2.6 manage.py runserver
However, when I try to move on to production mode, mod_python isn't using the right version of python:
Mod_python error: "PythonHandler django.core.handlers.modpython"
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch
log=debug)
File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 461, in import_module
f, p, d = imp.find_module(parts[i], path)
ImportError: No module named django
I have this in my /etc/httpd/conf/httpd.conf:
<Location "/chat">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE chat.settings
PythonDebug On
PythonPath "['/www/django/chat', '/opt/local/lib/python2.6/site-packages/django/'] + sys.path"
</Location>
So my question is, how do I make mod_python look for python2.6 instead of python?
|
[
"You would have to rebuild mod_python against your python2.6 installation. Since mod_python loads python as a library the version is fixed at compile time.\n",
"Don't use mod_python any more. mod_wsgi is the recommended way to deploy Django appliations now.\n",
"You can rebuild mod_python to link against libpython dynamically so that you can pick up version updates to your libpython but it takes some chicanery.\nYou will need to edit the configure script for mod_python as follows (remove -L${PyLIBPL}):\n$ diff configure.orig configure \n< LDFLAGS=\"${LDFLAGS} -L${PyLIBPL}\"\n---\n> LDFLAGS=\"${LDFLAGS}\"\n\nThen do \nconfigure --with-python=/path/to/bin/python ; make; make install dance.\nWhen you run:\nldd mod_python.so \nyou should see a line that looks like:\nlibpython2.6.so.1.0 => /usr/lib/libpython2.6.so.1.0 \n"
] |
[
4,
3,
2
] |
[] |
[] |
[
"apache",
"django",
"mod_python",
"python"
] |
stackoverflow_0002147695_apache_django_mod_python_python.txt
|
Q:
Is this a memory leak ( a program in python with sqlalchemy/sqlite)
I have the following code runs over a large set of data (2M). It eats up all my 4G mem before finishing.
for sample in session.query(CodeSample).yield_per(100):
for proj in projects:
if sample.filename.startswith(proj.abs_source):
sample.filename = "some other path"
session.add(sample)
Then I ran it though a reduced set of data and analyzed heap with heapy. get_rp() gave me the folloing hint
0: _ --- [-] 47821 (0x9163aec | 0x9165fec | 0x916d6cc | 0x9251414 | 0x925704...
1: a [-] 8244 tuple: 0x903ec8c*37, 0x903fcfc*13, 0x9052ecc*46...
2: aa ---- [S] 3446 types.CodeType: parseresult.py:73:src_path...
3: ab [S] 364 type: __builtin__.Struct, _random.Random, sqlite3.Cache...
4: ac ---- [-] 90 sqlalchemy.sql.visitors.VisitableType: 0x9162f2c...
5: aca [S] 11 dict of module: ..sql..., codemodel, sqlalchemy
6: acb ---- [-] 48 sqlalchemy.sql.visitors.VisitableType: 0x9162f2c...
7: acba [S] 9 dict of module: ..sql..., codemodel, sqlalchemy
8: acbb ---- [-] 45 sqlalchemy.sql.visitors.VisitableType: 0x9165fec...
9: acbba [S] 8 dict of module: ..sql..., codemodel, sqlalchemy
I'm new to sqlalchemy. Is this a memory leak? Thanks.
A:
Most DBAPIs, including psycopg2 and mysql-python, fully load all results into memory before releasing them to the client. SQLA's yield_per() option doesn't work around this, with one exception below, which is why its generally not a very useful option(edit: useful in the sense that it begins streaming results before the actual rows are fully fetched).
The exceptions to this behavior are:
Using a DBAPI that doesn't buffer rows. cx_oracle is one, as a result of the natural way OCI works. Not sure about pg8000's behavior, and there's also a new MySQL DBAPI called OurSQL which I am told by its creator does not buffer rows. pg8000 and OurSQL are supported by SQLAlchemy 0.6.
With psycopg2, a "server side cursor" may be used. SQLAlchemy supports a create_engine() flag "server_side_cursors=True" which uses server side cursors for all row-selecting operations. However, because server side cursors are generally expensive and thus will reduce performance for smaller queries, SQLAlchemy 0.6 now supports psycopg2's server side cursor on a per-statement or per-query basis using .execution_options(stream_results=True), where execution_options is available on Query, select(), text(), and Connection. The Query object calls this option when yield_per() is used, so in 0.6 yield_per() in conjunction with psycopg2 is actually useful.
A:
The session will keep track of all the CodeSample objects that you retrieve. So after iterating over 2M objects, the session keeps a reference to all of them. The session needs these references so it can write the correct changes to the database on flush. So I believe what you're seeing is to be expected.
To only keep N objects in memory at a time, you could do something like the code below (inspired by this answer, disclaimer: I have not tested it).
offset = 0
N = 10000
got_rows = True
while got_rows:
got_rows = False
for sample in session.query(CodeSample).limit(N).offset(offset):
got_rows = True
for proj in projects:
if sample.filename.startswith(proj.abs_source):
sample.filename = "some other path"
offset += N
session.flush() # writes changes to DB
session.expunge_all() # removes objects from session
But the above is a bit clunky, perhaps some SQLAlchemy gurus knows how to better do this.
BTW, you should not need the session.add(), the session tracks changes to the objects. Why do you use yield_per (EDIT: I guess this is to fetch the rows in chunks from the DB, is that correct? The session will keep track of all of them anyway.)
EDIT:
Hmm, looks like there is something I have misunderstood. From the docs:
weak_identity_map:
When set to the default value of True, a weak-referencing map is used;
instances which are not externally
referenced will be garbage collected
immediately. For dereferenced
instances which have pending changes
present, the attribute management
system will create a temporary
strong-reference to the object which
lasts until the changes are flushed to
the database, at which point it’s
again dereferenced. Alternatively,
when using the value False, the
identity map uses a regular Python
dictionary to store instances. The
session will maintain all instances
present until they are removed using
expunge(), clear(), or purge().
and
prune(): Remove unreferenced instances cached in the identity map.
Note that this method is only meaningful if “weak_identity_map” is set to False. The default weak identity map is self-pruning.
Removes any object in this Session’s identity map that is not referenced in user code, modified, new or scheduled for deletion. Returns the number of objects pruned.
|
Is this a memory leak ( a program in python with sqlalchemy/sqlite)
|
I have the following code runs over a large set of data (2M). It eats up all my 4G mem before finishing.
for sample in session.query(CodeSample).yield_per(100):
for proj in projects:
if sample.filename.startswith(proj.abs_source):
sample.filename = "some other path"
session.add(sample)
Then I ran it though a reduced set of data and analyzed heap with heapy. get_rp() gave me the folloing hint
0: _ --- [-] 47821 (0x9163aec | 0x9165fec | 0x916d6cc | 0x9251414 | 0x925704...
1: a [-] 8244 tuple: 0x903ec8c*37, 0x903fcfc*13, 0x9052ecc*46...
2: aa ---- [S] 3446 types.CodeType: parseresult.py:73:src_path...
3: ab [S] 364 type: __builtin__.Struct, _random.Random, sqlite3.Cache...
4: ac ---- [-] 90 sqlalchemy.sql.visitors.VisitableType: 0x9162f2c...
5: aca [S] 11 dict of module: ..sql..., codemodel, sqlalchemy
6: acb ---- [-] 48 sqlalchemy.sql.visitors.VisitableType: 0x9162f2c...
7: acba [S] 9 dict of module: ..sql..., codemodel, sqlalchemy
8: acbb ---- [-] 45 sqlalchemy.sql.visitors.VisitableType: 0x9165fec...
9: acbba [S] 8 dict of module: ..sql..., codemodel, sqlalchemy
I'm new to sqlalchemy. Is this a memory leak? Thanks.
|
[
"Most DBAPIs, including psycopg2 and mysql-python, fully load all results into memory before releasing them to the client. SQLA's yield_per() option doesn't work around this, with one exception below, which is why its generally not a very useful option(edit: useful in the sense that it begins streaming results before the actual rows are fully fetched).\nThe exceptions to this behavior are:\n\nUsing a DBAPI that doesn't buffer rows. cx_oracle is one, as a result of the natural way OCI works. Not sure about pg8000's behavior, and there's also a new MySQL DBAPI called OurSQL which I am told by its creator does not buffer rows. pg8000 and OurSQL are supported by SQLAlchemy 0.6.\nWith psycopg2, a \"server side cursor\" may be used. SQLAlchemy supports a create_engine() flag \"server_side_cursors=True\" which uses server side cursors for all row-selecting operations. However, because server side cursors are generally expensive and thus will reduce performance for smaller queries, SQLAlchemy 0.6 now supports psycopg2's server side cursor on a per-statement or per-query basis using .execution_options(stream_results=True), where execution_options is available on Query, select(), text(), and Connection. The Query object calls this option when yield_per() is used, so in 0.6 yield_per() in conjunction with psycopg2 is actually useful.\n\n",
"The session will keep track of all the CodeSample objects that you retrieve. So after iterating over 2M objects, the session keeps a reference to all of them. The session needs these references so it can write the correct changes to the database on flush. So I believe what you're seeing is to be expected.\nTo only keep N objects in memory at a time, you could do something like the code below (inspired by this answer, disclaimer: I have not tested it).\noffset = 0\nN = 10000\ngot_rows = True\nwhile got_rows:\n got_rows = False\n for sample in session.query(CodeSample).limit(N).offset(offset):\n got_rows = True\n for proj in projects:\n if sample.filename.startswith(proj.abs_source):\n sample.filename = \"some other path\"\n offset += N\n session.flush() # writes changes to DB\n session.expunge_all() # removes objects from session\n\nBut the above is a bit clunky, perhaps some SQLAlchemy gurus knows how to better do this.\nBTW, you should not need the session.add(), the session tracks changes to the objects. Why do you use yield_per (EDIT: I guess this is to fetch the rows in chunks from the DB, is that correct? The session will keep track of all of them anyway.)\nEDIT:\nHmm, looks like there is something I have misunderstood. From the docs:\n\nweak_identity_map:\n When set to the default value of True, a weak-referencing map is used;\n instances which are not externally\n referenced will be garbage collected\n immediately. For dereferenced\n instances which have pending changes\n present, the attribute management\n system will create a temporary\n strong-reference to the object which\n lasts until the changes are flushed to\n the database, at which point it’s\n again dereferenced. Alternatively,\n when using the value False, the\n identity map uses a regular Python\n dictionary to store instances. The\n session will maintain all instances\n present until they are removed using\n expunge(), clear(), or purge().\n\nand\n\nprune(): Remove unreferenced instances cached in the identity map.\nNote that this method is only meaningful if “weak_identity_map” is set to False. The default weak identity map is self-pruning.\nRemoves any object in this Session’s identity map that is not referenced in user code, modified, new or scheduled for deletion. Returns the number of objects pruned.\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"memory",
"memory_leaks",
"python",
"sqlalchemy"
] |
stackoverflow_0002145177_memory_memory_leaks_python_sqlalchemy.txt
|
Q:
Change the color of a node or an edge
I want to redraw a Graph g with only the color of a node or edge changed.
How do I do that?
A:
Your version of networkx is too old.
try
$ easy_install networkx
to get the current version
|
Change the color of a node or an edge
|
I want to redraw a Graph g with only the color of a node or edge changed.
How do I do that?
|
[
"Your version of networkx is too old.\ntry\n$ easy_install networkx\n\nto get the current version\n"
] |
[
1
] |
[] |
[] |
[
"networkx",
"python"
] |
stackoverflow_0002157530_networkx_python.txt
|
Q:
Python regex split, integer of arbitrary length
I'm trying to do a simple regex split in Python. The string is in the form of FooX where Foo is some string and X is an arbitrary integer. I have a feeling this should be really simple, but I can't quite get it to work.
On that note, can anyone recommend some good Regex reading materials?
A:
You can't use split() since that has to consume some characters, but you can use normal matching to do it.
>>> import re
>>> r = re.compile(r'(\D+)(\d+)')
>>> r.match('abc444').groups()
('abc', '444')
A:
Using groups:
import re
m=re.match('^(?P<first>[A-Za-z]+)(?P<second>[0-9]+)$',"Foo9")
print m.group('first')
print m.group('second')
Using search:
import re
s='Foo9'
m=re.search('(?<=\D)(?=\d)',s)
first=s[:m.start()]
second=s[m.end():]
print first, second
A:
Keeping it simple:
>>> import re
>>> a = "Foo1String12345"
>>> re.split(r'(\d+)$', a)[0:2]
['Foo1String', '12345']
A:
Assuming you want to split between the "Foo" and the number, you'd want something like:
r/(?<=\D)(?=\d)/
Which will match at a point between a nondigit and a digit, without consuming any characters in the split.
A:
>>> import re
>>> s="gnibbler1234"
>>> re.findall(r'(\D+)(\d+)',s)[0]
('gnibbler', '1234')
In the regex, \D means anything that is not a digit, so \D+ matches one or more things that are not digits.
Likewise \d means anything that is a digit, so \d+ matches one or more digits
|
Python regex split, integer of arbitrary length
|
I'm trying to do a simple regex split in Python. The string is in the form of FooX where Foo is some string and X is an arbitrary integer. I have a feeling this should be really simple, but I can't quite get it to work.
On that note, can anyone recommend some good Regex reading materials?
|
[
"You can't use split() since that has to consume some characters, but you can use normal matching to do it.\n>>> import re\n>>> r = re.compile(r'(\\D+)(\\d+)')\n>>> r.match('abc444').groups()\n('abc', '444')\n\n",
"Using groups:\nimport re\n\nm=re.match('^(?P<first>[A-Za-z]+)(?P<second>[0-9]+)$',\"Foo9\")\nprint m.group('first')\nprint m.group('second')\n\nUsing search:\nimport re\n\ns='Foo9'\nm=re.search('(?<=\\D)(?=\\d)',s)\nfirst=s[:m.start()]\nsecond=s[m.end():]\n\nprint first, second\n\n",
"Keeping it simple:\n>>> import re\n>>> a = \"Foo1String12345\"\n>>> re.split(r'(\\d+)$', a)[0:2]\n['Foo1String', '12345']\n\n",
"Assuming you want to split between the \"Foo\" and the number, you'd want something like:\nr/(?<=\\D)(?=\\d)/\n\nWhich will match at a point between a nondigit and a digit, without consuming any characters in the split.\n",
">>> import re\n>>> s=\"gnibbler1234\"\n>>> re.findall(r'(\\D+)(\\d+)',s)[0]\n('gnibbler', '1234')\n\nIn the regex, \\D means anything that is not a digit, so \\D+ matches one or more things that are not digits.\nLikewise \\d means anything that is a digit, so \\d+ matches one or more digits\n"
] |
[
6,
1,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002157894_python_regex.txt
|
Q:
Python code for determining which normal form tabular data is in
I'm looking for Python code that can take tabular data and establish which normal form(s) it is in (if any) and show any functional dependencies, etc.
A:
There are logical tests for "normalization". However, they're not trivial exercises in programming; they're relationships in the metadata that are imposed on the data. They require "thinking".
1NF -- no repeating groups. How does one identify a "repeating group"? It would be an array structure imposed on the columns of a table. How is that done? SQL doesn't provide a mechanism, so you'd have to look at the column names to check for a "pattern". COL_1, COL_2, COL_3, for example.
1NF -- consistent layout of rows. Duh. SQL imposes this by the very nature of table definition.
2NF -- data in a row depends on the key. You'd have to do a procedure something like this.
For each non-key column:
Query distinct pairs (Key and the non-key column)
Do all non-key values depend in a consistent way on a key value?
Can you build a simple dict mapping non-key to key?
The full algorithm is here: http://en.wikipedia.org/wiki/Relational_model#Set-theoretic_formulation
3NF -- data in a row depends ONLY on the key. This is worse, because you have to compare all combinations of non-key columns against all combinations of non-key columns to be sure that there were no non-key dependencies among the values.
4NF and 5NF confuse me, so I'll stop here.
My point is that -- theoretically -- you can do it. Practically, it's a lot of complex permutations of data to assert that the normal form relationships actually hold.
It's much, much easier to have a hypothesis about a specific violation and probe just that issue with some SQL queries and some thinking.
The formal math is here:
http://en.wikipedia.org/wiki/Relational_model
|
Python code for determining which normal form tabular data is in
|
I'm looking for Python code that can take tabular data and establish which normal form(s) it is in (if any) and show any functional dependencies, etc.
|
[
"There are logical tests for \"normalization\". However, they're not trivial exercises in programming; they're relationships in the metadata that are imposed on the data. They require \"thinking\".\n1NF -- no repeating groups. How does one identify a \"repeating group\"? It would be an array structure imposed on the columns of a table. How is that done? SQL doesn't provide a mechanism, so you'd have to look at the column names to check for a \"pattern\". COL_1, COL_2, COL_3, for example. \n1NF -- consistent layout of rows. Duh. SQL imposes this by the very nature of table definition.\n2NF -- data in a row depends on the key. You'd have to do a procedure something like this. \nFor each non-key column:\n Query distinct pairs (Key and the non-key column)\n Do all non-key values depend in a consistent way on a key value?\n Can you build a simple dict mapping non-key to key?\n\nThe full algorithm is here: http://en.wikipedia.org/wiki/Relational_model#Set-theoretic_formulation\n3NF -- data in a row depends ONLY on the key. This is worse, because you have to compare all combinations of non-key columns against all combinations of non-key columns to be sure that there were no non-key dependencies among the values.\n4NF and 5NF confuse me, so I'll stop here. \nMy point is that -- theoretically -- you can do it. Practically, it's a lot of complex permutations of data to assert that the normal form relationships actually hold.\nIt's much, much easier to have a hypothesis about a specific violation and probe just that issue with some SQL queries and some thinking.\nThe formal math is here:\nhttp://en.wikipedia.org/wiki/Relational_model\n"
] |
[
2
] |
[] |
[] |
[
"database_normalization",
"normalization",
"python",
"relational_algebra"
] |
stackoverflow_0002157531_database_normalization_normalization_python_relational_algebra.txt
|
Q:
How to create a django model field that has a default value if ever set to null
Given a model
class Template(models.Model):
colour = models.CharField(default="red", blank = True, null=True)
How can I arrange it so that any access to colour either returns the value stored in the field, or if the field is blank/null then it returns red?
The default=red will put "red" in the field when it's first created, but if it's then edited to blank I'd like access to it to return "red", not ""
Updated: I tried the properties solution suggested below, but I'm using JSON serialisation to implement a REST API and the properties (e.g. colour) don't get serialised, and serialising the _colour breaks the API
A:
You can create a separate method instead:
def get_colour(self):
if not self.colour:
return 'red'
else:
return self.colour
An alternative is to use property.
http://www.djangoproject.com/documentation/models/properties/
A:
Use the save method to implement this.
def save( self, *args, **kw ):
if self.colour is None:
self.colour= 'red'
super( ThisModel, self ).save( *args, **kw )
A:
Here's how I ended up solving this problem.
First some preconditions: I have existing code that accesses these field names (e.g. 'colour') and the field is also serialised (by django-rest-interface) as part of an API. Neither of these things can be changed.
Trying the properties method worked fine, except that colour was no longer a field so didn't get serialised. Result: broken API
Then moved to the save() solution, along with a custom attribute on each field which should behave like this:
class ColourChoices(models.Model):
colour1 = models.CharField()
colour1.colour_default = "red"
colour2 = models.CharField()
colour2.colour_default = "blue"
def save(self, *args, **kwargs):
# force colour fields to default values
for f in [ x for x in self._meta.fields if hasattr(x, 'colour_default') ]:
if self.__getattribute__(f.attname) == "":
self.__setattr__(f.attname, f.colour_default)
super(ColourChoices, self).save(*args,**kwargs)
Now all works fine and as required.
The only problem with this solution is that if the default values change it's impossible to tell which database fields should have updated defaults, and which are just accidentally the same colour as the old default. However for my application I can live with this.
|
How to create a django model field that has a default value if ever set to null
|
Given a model
class Template(models.Model):
colour = models.CharField(default="red", blank = True, null=True)
How can I arrange it so that any access to colour either returns the value stored in the field, or if the field is blank/null then it returns red?
The default=red will put "red" in the field when it's first created, but if it's then edited to blank I'd like access to it to return "red", not ""
Updated: I tried the properties solution suggested below, but I'm using JSON serialisation to implement a REST API and the properties (e.g. colour) don't get serialised, and serialising the _colour breaks the API
|
[
"You can create a separate method instead:\ndef get_colour(self):\n if not self.colour:\n return 'red'\n else:\n return self.colour\n\nAn alternative is to use property.\nhttp://www.djangoproject.com/documentation/models/properties/\n",
"Use the save method to implement this.\ndef save( self, *args, **kw ):\n if self.colour is None:\n self.colour= 'red'\n super( ThisModel, self ).save( *args, **kw )\n\n",
"Here's how I ended up solving this problem.\nFirst some preconditions: I have existing code that accesses these field names (e.g. 'colour') and the field is also serialised (by django-rest-interface) as part of an API. Neither of these things can be changed.\nTrying the properties method worked fine, except that colour was no longer a field so didn't get serialised. Result: broken API\nThen moved to the save() solution, along with a custom attribute on each field which should behave like this:\nclass ColourChoices(models.Model):\n colour1 = models.CharField()\n colour1.colour_default = \"red\"\n colour2 = models.CharField()\n colour2.colour_default = \"blue\"\n\n def save(self, *args, **kwargs):\n # force colour fields to default values\n for f in [ x for x in self._meta.fields if hasattr(x, 'colour_default') ]:\n if self.__getattribute__(f.attname) == \"\":\n self.__setattr__(f.attname, f.colour_default)\n super(ColourChoices, self).save(*args,**kwargs)\n\nNow all works fine and as required.\nThe only problem with this solution is that if the default values change it's impossible to tell which database fields should have updated defaults, and which are just accidentally the same colour as the old default. However for my application I can live with this.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002156585_django_django_models_python.txt
|
Q:
How do I access a python list from a django templatetag?
I have created a templatetag that loads a yaml document into a python list. In my template I have {% get_content_set %}, this dumps the raw list data. What I want to be able to do is something like
{% for items in get_content_list %}
<h2>{{items.title}}</h2>
{% endfor %}`
A:
If the list is in a python variable X, then add it to the template context context['X'] = X and then you can do
{% for items in X %}
{{ items.title }}
{% endfor %}
A template tag is designed to render output, so won't provide an iterable list for you to use. But you don't need that as the normal context + for loop are fine.
A:
Since writing complex templatetags is not an easy task (well documented though) i would take {% with %} tag source and adapt it for my needs, so it looks like
{% get_content_list as content %
{% for items in content %}
<h2>{{items.title}}</h2>
{% endfor %}`
|
How do I access a python list from a django templatetag?
|
I have created a templatetag that loads a yaml document into a python list. In my template I have {% get_content_set %}, this dumps the raw list data. What I want to be able to do is something like
{% for items in get_content_list %}
<h2>{{items.title}}</h2>
{% endfor %}`
|
[
"If the list is in a python variable X, then add it to the template context context['X'] = X and then you can do\n{% for items in X %}\n {{ items.title }}\n{% endfor %}\n\nA template tag is designed to render output, so won't provide an iterable list for you to use. But you don't need that as the normal context + for loop are fine.\n",
"Since writing complex templatetags is not an easy task (well documented though) i would take {% with %} tag source and adapt it for my needs, so it looks like \n{% get_content_list as content %\n{% for items in content %} \n <h2>{{items.title}}</h2> \n{% endfor %}`\n\n"
] |
[
3,
-1
] |
[] |
[] |
[
"django",
"django_templates",
"python",
"templates",
"yaml"
] |
stackoverflow_0002157665_django_django_templates_python_templates_yaml.txt
|
Q:
How to extend the Turbogears 2.1 login functionality
I'm using Turbogears 2.1 and repoze.who/what and am having trouble figuring out how to extend the basic authentication functionality. I am essentially attempting to require users to activate their account via an emailed link before they can login. If they try to login without activating their account, I want to display an appropriate error message. The default Turbogears functionality simply displays one message for all errors.
I created my own authentication plugin which works fine. It won't allow users to login if they have not activated their account. However, the problem comes when I try to create the form and display custom error messages. How can I go about doing this?
Thanks
A:
It's impossible to give a really good answer without seeing your actual code, but here's one idea:
Create a repoze.who metadata provider plugin that "scribbles" something that indicates whether the user has activated their account.
Create a "challenger decider" plugin that looks at both whether the user has authenticated, and also whether they have activated their account (by checking the metadata you set with the metadata plugin).
Create a challenger plugin to send back the actual challenge. If the user is not authenticated, send back a login form/prompt. If user is authenticated (your authenticator plugin succeeded), but they have not activated their account, send back a custom error page asking the user to activate their account.
In any case, read this page carefully.
You could also maybe use repoze.what with a custom predicate, but you'd probably have to sprinkle decorators all through your code, checking whether their account has been activated on every controller/method. Ugly.
Hope this helps!
|
How to extend the Turbogears 2.1 login functionality
|
I'm using Turbogears 2.1 and repoze.who/what and am having trouble figuring out how to extend the basic authentication functionality. I am essentially attempting to require users to activate their account via an emailed link before they can login. If they try to login without activating their account, I want to display an appropriate error message. The default Turbogears functionality simply displays one message for all errors.
I created my own authentication plugin which works fine. It won't allow users to login if they have not activated their account. However, the problem comes when I try to create the form and display custom error messages. How can I go about doing this?
Thanks
|
[
"It's impossible to give a really good answer without seeing your actual code, but here's one idea:\n\nCreate a repoze.who metadata provider plugin that \"scribbles\" something that indicates whether the user has activated their account.\nCreate a \"challenger decider\" plugin that looks at both whether the user has authenticated, and also whether they have activated their account (by checking the metadata you set with the metadata plugin). \nCreate a challenger plugin to send back the actual challenge. If the user is not authenticated, send back a login form/prompt. If user is authenticated (your authenticator plugin succeeded), but they have not activated their account, send back a custom error page asking the user to activate their account.\n\nIn any case, read this page carefully.\nYou could also maybe use repoze.what with a custom predicate, but you'd probably have to sprinkle decorators all through your code, checking whether their account has been activated on every controller/method. Ugly.\nHope this helps!\n"
] |
[
4
] |
[] |
[] |
[
"python",
"turbogears",
"turbogears2"
] |
stackoverflow_0001960747_python_turbogears_turbogears2.txt
|
Q:
Easy way to upload files to S3 via HTTP Form
I have written a tiny web appication in python that allows me to browse my S3 buckets.
The web appication runs inside the Google App Engine.
Now, I want to create a html form for this web appication that allows me to upload a file into the bucket.
These information are already inside the form: AWSAccessKeyId and the name of the bucket.
I want that the keyname is the name of the file that is selected by the user via <input name="file" type="file">
Another problem is: Can I create the content of the (hidden) input tags policy and signature before a file is choosen?
I want to solve this problem only with HTML and Python. No JavaScript.
Is this possible?
A:
Read the developer documentation from Amazon: Browser Uploads to S3 using HTML POST Forms
There is Python examples in there to get you started.
|
Easy way to upload files to S3 via HTTP Form
|
I have written a tiny web appication in python that allows me to browse my S3 buckets.
The web appication runs inside the Google App Engine.
Now, I want to create a html form for this web appication that allows me to upload a file into the bucket.
These information are already inside the form: AWSAccessKeyId and the name of the bucket.
I want that the keyname is the name of the file that is selected by the user via <input name="file" type="file">
Another problem is: Can I create the content of the (hidden) input tags policy and signature before a file is choosen?
I want to solve this problem only with HTML and Python. No JavaScript.
Is this possible?
|
[
"Read the developer documentation from Amazon: Browser Uploads to S3 using HTML POST Forms\nThere is Python examples in there to get you started.\n"
] |
[
4
] |
[] |
[] |
[
"amazon_s3",
"google_app_engine",
"html",
"python"
] |
stackoverflow_0002158871_amazon_s3_google_app_engine_html_python.txt
|
Q:
How to append a file's creation date to its filename?
I would like to create a python script that
appends the file created date to the end of the filename while retaining the oringinal file name (Report) for a batch of pdf documents.
directory = T:\WISAARD_Web Portal Projects\PortalLogging\WebLogExpert
filenames = Report.pdf
A:
import os,time
root="/home"
path=os.path.join(root,"dir1")
os.chdir(path)
for files in os.listdir("."):
if files.endswith(".pdf"):
f,ext = os.path.splitext(files)
d=time.ctime(os.path.getmtime(files)).split() #here is just example. you can use strftime, strptime etc to format your date as desired
filedate = d[-1]+"-"+d[-2]+"-"+d[-3]
newname = f+filedate+ext
try:
os.rename(files,newname)
except Exception,e:
print e
else:
print "ok: renamed %s to %s " %(files,newname)
|
How to append a file's creation date to its filename?
|
I would like to create a python script that
appends the file created date to the end of the filename while retaining the oringinal file name (Report) for a batch of pdf documents.
directory = T:\WISAARD_Web Portal Projects\PortalLogging\WebLogExpert
filenames = Report.pdf
|
[
"import os,time\nroot=\"/home\"\npath=os.path.join(root,\"dir1\")\nos.chdir(path)\nfor files in os.listdir(\".\"):\n if files.endswith(\".pdf\"):\n f,ext = os.path.splitext(files) \n d=time.ctime(os.path.getmtime(files)).split() #here is just example. you can use strftime, strptime etc to format your date as desired\n filedate = d[-1]+\"-\"+d[-2]+\"-\"+d[-3]\n newname = f+filedate+ext\n try: \n os.rename(files,newname)\n except Exception,e:\n print e\n else:\n print \"ok: renamed %s to %s \" %(files,newname)\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002158961_python.txt
|
Q:
Strange Python set and hash behaviour - how does this work?
I have a class called GraphEdge which I would like to be uniquely defined within a set (the built-in set type) by its tail and head members, which are set via __init__.
If I do not define __hash__, I see the following behaviour:
>>> E = GraphEdge('A', 'B')
>>> H = GraphEdge('A', 'B')
>>> hash(E)
139731804758160
>>> hash(H)
139731804760784
>>> S = set()
>>> S.add(E)
>>> S.add(H)
>>> S
set([('A', 'B'), ('A', 'B')])
The set has no way to know that E and H are the same by my definition, since they have differing hashes (which is what the set type uses to determine uniqueness, to my knowledge), so it adds both as distinct elements. So I define a rather naive hash function for GraphEdge like so:
def __hash__( self ):
return hash( self.tail ) ^ hash( self.head )
Now the above works as expected:
>>> E = GraphEdge('A', 'B')
>>> H = GraphEdge('A', 'B')
>>> hash(E)
409150083
>>> hash(H)
409150083
>>> S = set()
>>> S.add(E)
>>> S.add(H)
>>> S
set([('A', 'B')])
But clearly, ('A', 'B') and ('B', 'A') in this case will return the same hash, so I would expect that I could not add ('B', 'A') to a set already containing ('A', 'B'). But this is not what happens:
>>> E = GraphEdge('A', 'B')
>>> H = GraphEdge('B', 'A')
>>> hash(E)
409150083
>>> hash(H)
409150083
>>> S = set()
>>> S.add(E)
>>> S.add(H)
>>> S
set([('A', 'B'), ('B', 'A')])
So is the set type using the hash or not? If so, how is the last scenario possible? If not, why doesn't the first scenario (no __hash__ defined) work? Am I missing something?
Edit: For reference for future readers, I already had __eq__ defined (also based on tail and head).
A:
You have a hash collision. On hash collision, the set uses the == operator to check on whether or not they are truly equal to each other.
A:
It's important to understand how hash and == work together, because both are used by sets. For two values x and y, the important rule is that:
x == y ==> hash(x) == hash(y)
(x equals y implies that x and y's hashes are equal). But, the inverse is not true: two unequal values can have the same hash.
Sets (and dicts) will use the hash to get an approximation to equality, but will use the real equality operation to figure out if two values are the same or not.
A:
You should always define both __eq__() and __hash__() if you need at least one of them. If the hashes of two objects are equal, an extra __eq__() check is done to verify uniqueness.
|
Strange Python set and hash behaviour - how does this work?
|
I have a class called GraphEdge which I would like to be uniquely defined within a set (the built-in set type) by its tail and head members, which are set via __init__.
If I do not define __hash__, I see the following behaviour:
>>> E = GraphEdge('A', 'B')
>>> H = GraphEdge('A', 'B')
>>> hash(E)
139731804758160
>>> hash(H)
139731804760784
>>> S = set()
>>> S.add(E)
>>> S.add(H)
>>> S
set([('A', 'B'), ('A', 'B')])
The set has no way to know that E and H are the same by my definition, since they have differing hashes (which is what the set type uses to determine uniqueness, to my knowledge), so it adds both as distinct elements. So I define a rather naive hash function for GraphEdge like so:
def __hash__( self ):
return hash( self.tail ) ^ hash( self.head )
Now the above works as expected:
>>> E = GraphEdge('A', 'B')
>>> H = GraphEdge('A', 'B')
>>> hash(E)
409150083
>>> hash(H)
409150083
>>> S = set()
>>> S.add(E)
>>> S.add(H)
>>> S
set([('A', 'B')])
But clearly, ('A', 'B') and ('B', 'A') in this case will return the same hash, so I would expect that I could not add ('B', 'A') to a set already containing ('A', 'B'). But this is not what happens:
>>> E = GraphEdge('A', 'B')
>>> H = GraphEdge('B', 'A')
>>> hash(E)
409150083
>>> hash(H)
409150083
>>> S = set()
>>> S.add(E)
>>> S.add(H)
>>> S
set([('A', 'B'), ('B', 'A')])
So is the set type using the hash or not? If so, how is the last scenario possible? If not, why doesn't the first scenario (no __hash__ defined) work? Am I missing something?
Edit: For reference for future readers, I already had __eq__ defined (also based on tail and head).
|
[
"You have a hash collision. On hash collision, the set uses the == operator to check on whether or not they are truly equal to each other.\n",
"It's important to understand how hash and == work together, because both are used by sets. For two values x and y, the important rule is that:\nx == y ==> hash(x) == hash(y)\n\n(x equals y implies that x and y's hashes are equal). But, the inverse is not true: two unequal values can have the same hash.\nSets (and dicts) will use the hash to get an approximation to equality, but will use the real equality operation to figure out if two values are the same or not.\n",
"You should always define both __eq__() and __hash__() if you need at least one of them. If the hashes of two objects are equal, an extra __eq__() check is done to verify uniqueness.\n"
] |
[
15,
7,
6
] |
[] |
[] |
[
"hash",
"python",
"set"
] |
stackoverflow_0002159232_hash_python_set.txt
|
Q:
Python 3.0 urllib.parse error "Type str doesn't support the buffer API"
File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
self.read_urlencoded()
File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
self.strict_parsing):
File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
Can anybody direct me on how to avoid this? I'm getting it through feeding data into the cgi.Fieldstorage and I can't seem to do it any other way.
A:
urllib is trying to do:
b'a,b'.split(',')
Which doesn't work. byte strings and unicode strings mix even less smoothly in Py3k than they used to — deliberately, to make encoding problems go wrong sooner rather than later.
So the error is rather opaquely telling you ‘you can't pass a byte string to urllib.parse’. Presumably you are doing a POST request, where the form-encoded string is coming into cgi as a content body; the content body is still a byte string/stream so it now clashes with the new urllib.
So yeah, it's a bug in cgi.py, yet another victim of 2to3 conversion that hasn't been fixed properly for the new string model. It should be converting the incoming byte stream to characters before passing them to urllib.
Did I mention Python 3.0's libraries (especially web-related ones) still being rather shonky? :-)
A:
From the python tutorial ( http://www.python.org/doc/3.0/tutorial/stdlib.html ) there is an example of using urlopen method. It raises the same error.
for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
if 'EST' in line or 'EDT' in line: # look for Eastern Time
print(line)
You'll need to use the str function to convert the byte thingo to a string with the correct encoding. As follows:
for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
lineStr = str( line, encoding='utf8' )
if 'EST' in lineStr or 'EDT' in lineStr: # look for Eastern Time
print(lineStr)
|
Python 3.0 urllib.parse error "Type str doesn't support the buffer API"
|
File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
self.read_urlencoded()
File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
self.strict_parsing):
File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
Can anybody direct me on how to avoid this? I'm getting it through feeding data into the cgi.Fieldstorage and I can't seem to do it any other way.
|
[
"urllib is trying to do:\nb'a,b'.split(',')\n\nWhich doesn't work. byte strings and unicode strings mix even less smoothly in Py3k than they used to — deliberately, to make encoding problems go wrong sooner rather than later.\nSo the error is rather opaquely telling you ‘you can't pass a byte string to urllib.parse’. Presumably you are doing a POST request, where the form-encoded string is coming into cgi as a content body; the content body is still a byte string/stream so it now clashes with the new urllib.\nSo yeah, it's a bug in cgi.py, yet another victim of 2to3 conversion that hasn't been fixed properly for the new string model. It should be converting the incoming byte stream to characters before passing them to urllib.\nDid I mention Python 3.0's libraries (especially web-related ones) still being rather shonky? :-)\n",
"From the python tutorial ( http://www.python.org/doc/3.0/tutorial/stdlib.html ) there is an example of using urlopen method. It raises the same error.\nfor line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):\n if 'EST' in line or 'EDT' in line: # look for Eastern Time\n print(line)\n\nYou'll need to use the str function to convert the byte thingo to a string with the correct encoding. As follows:\nfor line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):\n lineStr = str( line, encoding='utf8' )\n if 'EST' in lineStr or 'EDT' in lineStr: # look for Eastern Time\n print(lineStr)\n\n"
] |
[
28,
13
] |
[] |
[] |
[
"cgi",
"python",
"python_3.x",
"urllib"
] |
stackoverflow_0000540342_cgi_python_python_3.x_urllib.txt
|
Q:
javax.script.ScriptEngine fails at runtime
Any ideas?
public class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
engine.put("hello_str", "");
engine.eval("for i in range(10):");
engine.eval(" hello_str += str(i)");
Object x = engine.get("hello_str");
System.out.println("x: " + x);
}
}
error is
Exception in thread "main" javax.script.ScriptException: SyntaxError: mismatched input '' expecting INDENT in at line number 1 at column number 18
at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:170)
at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:76)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:33)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
at javaapplication2.Main.main(Main.java:23)
Caused by: File "", line 1
for i in range(10):
^
SyntaxError: mismatched input '' expecting INDENT
A:
Looks like you are trying to evaluate an incomplete statement in the lines:
engine.eval("for i in range(10):");
engine.eval(" hello_str += str(i)");
Here, I assume eval() is trying to evaluate these one-by-one, and finding nothing after the for is erroring out since that is an incomplete statement. Try this:
engine.eval("for i in range(10):\n hello_str += str(i)");
The newline is not necessary in this case, but it would be if you want to include several statements in the loop body, eg:
engine.eval("for i in range(10):\n hello_str += str(i)\n print i");
Also note that in the example above the amount of spacing after each new line should be equal. In fact, I would suggest assembling the script string completely before evaluating it. Or better yet, read it from a separate .py file.
|
javax.script.ScriptEngine fails at runtime
|
Any ideas?
public class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
engine.put("hello_str", "");
engine.eval("for i in range(10):");
engine.eval(" hello_str += str(i)");
Object x = engine.get("hello_str");
System.out.println("x: " + x);
}
}
error is
Exception in thread "main" javax.script.ScriptException: SyntaxError: mismatched input '' expecting INDENT in at line number 1 at column number 18
at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:170)
at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:76)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:33)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
at javaapplication2.Main.main(Main.java:23)
Caused by: File "", line 1
for i in range(10):
^
SyntaxError: mismatched input '' expecting INDENT
|
[
"Looks like you are trying to evaluate an incomplete statement in the lines:\nengine.eval(\"for i in range(10):\");\nengine.eval(\" hello_str += str(i)\");\n\nHere, I assume eval() is trying to evaluate these one-by-one, and finding nothing after the for is erroring out since that is an incomplete statement. Try this:\nengine.eval(\"for i in range(10):\\n hello_str += str(i)\");\n\nThe newline is not necessary in this case, but it would be if you want to include several statements in the loop body, eg:\nengine.eval(\"for i in range(10):\\n hello_str += str(i)\\n print i\");\n\nAlso note that in the example above the amount of spacing after each new line should be equal. In fact, I would suggest assembling the script string completely before evaluating it. Or better yet, read it from a separate .py file.\n"
] |
[
2
] |
[] |
[] |
[
"java",
"python",
"scriptengine"
] |
stackoverflow_0002159273_java_python_scriptengine.txt
|
Q:
lxml has essentially nothing
The lxml package for Python seems to absolutely broken on my system. I am not sure of the problem, as all of the files are in place, it seems. My suspicion is that the problem is in __init__.py, but I don't have enough practice with the system to make an accurate diagnosis or fix the problem.
Here is some code that I think will help diagnose the problem:
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
>>> dir(lxml)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> print lxml.__path__
['/usr/lib/python2.6/dist-packages/lxml']
>>> c = open("/usr/lib/python2.6/dist-packages/lxml/__init__.py", "r")
>>> for line in c:
... print line
...
# this is a package
>>> c.close()
>>> import os
>>> os.system("ls /usr/lib/python2.6/dist-packages/lxml/")
builder.py ElementInclude.py __init__.py sax.pyc
builder.pyc ElementInclude.pyc __init__.pyc usedoctest.py
cssselect.py _elementpath.py objectify.so usedoctest.pyc
cssselect.pyc _elementpath.pyc pyclasslookup.py
doctestcompare.py etree.so pyclasslookup.pyc
doctestcompare.pyc html sax.py
0
>>>
Like I said, my suspicion is that __init__.py contains the problem, but I'm not 100% sure.
Also, I'm using Linux Mint 8 - the rough equivalent of Ubuntu 9.10.
Thanks in advance.
A:
No, you're just doing it wrong! Try, e.g., from lxml import etree, and you should be able to use etree fully. import lxml -- importing the package! -- does not give you implicit access to any of the package's modules!-)
A:
I think all the lxml code is in subpackages. Try
from lxml import etree
A:
It's perfectly normal for a __init__.py file to have nothing in it: http://docs.python.org/tutorial/modules.html#packages
The file is just there to let Python know that it's a package and not just a directory with a bunch of modules in it.
You just need to import the modules inside the package directly.
from lxml import etree, html
etc...
|
lxml has essentially nothing
|
The lxml package for Python seems to absolutely broken on my system. I am not sure of the problem, as all of the files are in place, it seems. My suspicion is that the problem is in __init__.py, but I don't have enough practice with the system to make an accurate diagnosis or fix the problem.
Here is some code that I think will help diagnose the problem:
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
>>> dir(lxml)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> print lxml.__path__
['/usr/lib/python2.6/dist-packages/lxml']
>>> c = open("/usr/lib/python2.6/dist-packages/lxml/__init__.py", "r")
>>> for line in c:
... print line
...
# this is a package
>>> c.close()
>>> import os
>>> os.system("ls /usr/lib/python2.6/dist-packages/lxml/")
builder.py ElementInclude.py __init__.py sax.pyc
builder.pyc ElementInclude.pyc __init__.pyc usedoctest.py
cssselect.py _elementpath.py objectify.so usedoctest.pyc
cssselect.pyc _elementpath.pyc pyclasslookup.py
doctestcompare.py etree.so pyclasslookup.pyc
doctestcompare.pyc html sax.py
0
>>>
Like I said, my suspicion is that __init__.py contains the problem, but I'm not 100% sure.
Also, I'm using Linux Mint 8 - the rough equivalent of Ubuntu 9.10.
Thanks in advance.
|
[
"No, you're just doing it wrong! Try, e.g., from lxml import etree, and you should be able to use etree fully. import lxml -- importing the package! -- does not give you implicit access to any of the package's modules!-)\n",
"I think all the lxml code is in subpackages. Try\nfrom lxml import etree\n\n",
"It's perfectly normal for a __init__.py file to have nothing in it: http://docs.python.org/tutorial/modules.html#packages\nThe file is just there to let Python know that it's a package and not just a directory with a bunch of modules in it.\nYou just need to import the modules inside the package directly.\nfrom lxml import etree, html\n\netc...\n"
] |
[
10,
1,
1
] |
[] |
[] |
[
"lxml",
"package",
"python"
] |
stackoverflow_0002159690_lxml_package_python.txt
|
Q:
Why Python on Windows can't read an image in binary mode?
I want to read a image in binary mode so that I could save it into my database, like this:
img = open("Last_Dawn.jpg")
t = img.read()
save_to_db(t)
This is working on Mac. But on Windows, what img.read() is incorrect. It's just a little out of the whole set.
So my first question is: why code above doesn't work in Windows?
And second is: is there any other way to do this?
Thanks a lot!
A:
You need to open in binary mode:
img = open("Last_Dawn.jpg", 'rb')
A:
You need to tell Python to open the file in binary mode:
img = open('whatever.whatever', 'rb')
See the documentation for the open function here: http://docs.python.org/library/functions.html#open
A:
open(filename, 'rb')
A:
Can't say for sure but I do know that the ISO C standard doesn't distinguish between the binary and non-binary modes when calling fopen and yet Windows does.
It's likely that the Python code just uses fopen("Last_Dawn.jpg","r") under the covers (since it's written in C) and this is being opened in Windows in non-binary mode.
This will most likely convert line end characters (LF -> CRLF) and possibly others.
If you yourself specify the mode as 'rb' on your open statement, that should fix it:
img = open("Last_Dawn.jpg", "rb")
|
Why Python on Windows can't read an image in binary mode?
|
I want to read a image in binary mode so that I could save it into my database, like this:
img = open("Last_Dawn.jpg")
t = img.read()
save_to_db(t)
This is working on Mac. But on Windows, what img.read() is incorrect. It's just a little out of the whole set.
So my first question is: why code above doesn't work in Windows?
And second is: is there any other way to do this?
Thanks a lot!
|
[
"You need to open in binary mode:\nimg = open(\"Last_Dawn.jpg\", 'rb')\n\n",
"You need to tell Python to open the file in binary mode:\nimg = open('whatever.whatever', 'rb')\n\nSee the documentation for the open function here: http://docs.python.org/library/functions.html#open\n",
"open(filename, 'rb')\n\n",
"Can't say for sure but I do know that the ISO C standard doesn't distinguish between the binary and non-binary modes when calling fopen and yet Windows does.\nIt's likely that the Python code just uses fopen(\"Last_Dawn.jpg\",\"r\") under the covers (since it's written in C) and this is being opened in Windows in non-binary mode.\nThis will most likely convert line end characters (LF -> CRLF) and possibly others.\nIf you yourself specify the mode as 'rb' on your open statement, that should fix it:\nimg = open(\"Last_Dawn.jpg\", \"rb\")\n\n"
] |
[
6,
4,
2,
2
] |
[] |
[] |
[
"binary",
"image",
"python"
] |
stackoverflow_0002159794_binary_image_python.txt
|
Q:
Signing requests in Python for OAuth
currently I'm interfacing the Twitter API using the OAuth protocol and writing the code in Python. As most of the users out there, I think the toughest part of the specs is dealing with signatures.
After wandering around the web in search for a solution, I decided to go for my custom code, so as to have a better understanding of what is going on.
For the sake of other users, I'm posting here a very simple and short implementation of the SHA1 signature specs in Python:
import hmac
from hashlib import sha1
from urllib import quote, urlencode
from base64 import b64encode
from urlparse import urlparse
def sign_request_sha1(url,method,data,secret=""):
pu = urlparse(urlparse(url).geturl())
normUrl = "%s://%s%s%s" % (
pu.scheme,
pu.hostname,
"" if not pu.port or {"http":80,"https":443}[pu.scheme] == pu.port else ":%d" % pu.port,
pu.path,
)
names = data.keys()
names.sort()
sig = "%s&%s&%s" % (
method.upper(),
quote(normUrl,''),
quote("&".join(["%s=%s" % (k,quote(data[k].encode('utf-8'),'')) for k in names]),''),
)
key = "%s&%s" % (quote(CONSUMER_SECRET.encode('utf-8'),''),secret)
return b64encode(hmac.new(key,sig,sha1).digest())
The input parameters to the function are:
url: the url you are going to call for the specific OAuth request.
method: this must be "GET" or "POST" depending on how you're going to issue your request.
data: a dictionary containing all the parameters of the requests, including any custom argument but excluding the "oauth_signature" one (for obvious reasons).
secret: a secret token you received in the initial phase of the protocol.
I tested it with Twitter and it seems to work but I'd like to receive some comments about mistakes, improvements and so on.
Lastly, here you find a piece of code calling the code for the initial "request token" phase:
from random import getrandbits
from base64 import b64encode
from time import time
def twitter_request_token(req,callback,errback):
req_url="http://twitter.com:80/oauth/request_token"
data = { \
"oauth_consumer_key" : CONSUMER_KEY,
"oauth_nonce" : b64encode("%0x" % getrandbits(256))[:32],
"oauth_timestamp" : str(int(time())),
"oauth_signature_method" : "HMAC-SHA1",
"oauth_version" : "1.0",
"oauth_callback" : "http://localhost:8080/",
}
data["oauth_signature"] = sign_request_sha1(req_url,"GET",data)
Thank you.
A:
My knee-jerk reaction to this is If You're Typing The Letters A-E-S Into Your Code, You're Doing It Wrong. Or, as redditor khafra recently reminded us of the Sicilian's version:
Haha.. you fool! You fell victim to one of the classic blunders. The most famous is: Never get involved in a land war in Asia. But only slightly less famous is this: Never attempt to roll your own crypto when there's a well-tested library that'll do it better!
I mean, I get it. The first time I looked at it, oauth.py didn't impress me either. There's been a lot of work on it since and it's looking better, but there still appear to be no tests, so I don't know. Anyway, tests or no tests, it's been reviewed and used by more people than your code has.
But that's just me being uptight on the subject of crypto code reuse and doesn't really help you in figuring out the protocol machinery. It looks okay to me, but I haven't had my head in the OAuth spec too much lately.
Just use some more lines for that pu.port business; having a conditional if expression, an or expression, and the {}[] construct all in one line is really hard to read.
If you really want code review by people who are familiar with the protocol, you're probably better off asking the mailing list. And if you can offer them an alternate API that will make the code in their repository more appealing to new users, that'll be good for everyone.
|
Signing requests in Python for OAuth
|
currently I'm interfacing the Twitter API using the OAuth protocol and writing the code in Python. As most of the users out there, I think the toughest part of the specs is dealing with signatures.
After wandering around the web in search for a solution, I decided to go for my custom code, so as to have a better understanding of what is going on.
For the sake of other users, I'm posting here a very simple and short implementation of the SHA1 signature specs in Python:
import hmac
from hashlib import sha1
from urllib import quote, urlencode
from base64 import b64encode
from urlparse import urlparse
def sign_request_sha1(url,method,data,secret=""):
pu = urlparse(urlparse(url).geturl())
normUrl = "%s://%s%s%s" % (
pu.scheme,
pu.hostname,
"" if not pu.port or {"http":80,"https":443}[pu.scheme] == pu.port else ":%d" % pu.port,
pu.path,
)
names = data.keys()
names.sort()
sig = "%s&%s&%s" % (
method.upper(),
quote(normUrl,''),
quote("&".join(["%s=%s" % (k,quote(data[k].encode('utf-8'),'')) for k in names]),''),
)
key = "%s&%s" % (quote(CONSUMER_SECRET.encode('utf-8'),''),secret)
return b64encode(hmac.new(key,sig,sha1).digest())
The input parameters to the function are:
url: the url you are going to call for the specific OAuth request.
method: this must be "GET" or "POST" depending on how you're going to issue your request.
data: a dictionary containing all the parameters of the requests, including any custom argument but excluding the "oauth_signature" one (for obvious reasons).
secret: a secret token you received in the initial phase of the protocol.
I tested it with Twitter and it seems to work but I'd like to receive some comments about mistakes, improvements and so on.
Lastly, here you find a piece of code calling the code for the initial "request token" phase:
from random import getrandbits
from base64 import b64encode
from time import time
def twitter_request_token(req,callback,errback):
req_url="http://twitter.com:80/oauth/request_token"
data = { \
"oauth_consumer_key" : CONSUMER_KEY,
"oauth_nonce" : b64encode("%0x" % getrandbits(256))[:32],
"oauth_timestamp" : str(int(time())),
"oauth_signature_method" : "HMAC-SHA1",
"oauth_version" : "1.0",
"oauth_callback" : "http://localhost:8080/",
}
data["oauth_signature"] = sign_request_sha1(req_url,"GET",data)
Thank you.
|
[
"My knee-jerk reaction to this is If You're Typing The Letters A-E-S Into Your Code, You're Doing It Wrong. Or, as redditor khafra recently reminded us of the Sicilian's version:\n\nHaha.. you fool! You fell victim to one of the classic blunders. The most famous is: Never get involved in a land war in Asia. But only slightly less famous is this: Never attempt to roll your own crypto when there's a well-tested library that'll do it better!\n\nI mean, I get it. The first time I looked at it, oauth.py didn't impress me either. There's been a lot of work on it since and it's looking better, but there still appear to be no tests, so I don't know. Anyway, tests or no tests, it's been reviewed and used by more people than your code has.\nBut that's just me being uptight on the subject of crypto code reuse and doesn't really help you in figuring out the protocol machinery. It looks okay to me, but I haven't had my head in the OAuth spec too much lately.\nJust use some more lines for that pu.port business; having a conditional if expression, an or expression, and the {}[] construct all in one line is really hard to read.\nIf you really want code review by people who are familiar with the protocol, you're probably better off asking the mailing list. And if you can offer them an alternate API that will make the code in their repository more appealing to new users, that'll be good for everyone.\n"
] |
[
2
] |
[] |
[] |
[
"oauth",
"python",
"signature"
] |
stackoverflow_0002138656_oauth_python_signature.txt
|
Q:
Boost::Python, static factories, and inheritance
So I may have a rather unique use case here, but I'm thinking it should work- But it's not working correctly.
Basically, I have a class that uses a static factory method ( create ) that returns a shared_ptr to the newly created
instance of the class. This class also has a virtual function that I'd like to override from python and call from C++.
Maybe my code can express the thought more clearly than my words:
#include <string>
#include <iostream>
#include <boost/python.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::python;
using namespace boost;
//~ Base Class ClassA
class ClassA
: public enable_shared_from_this<ClassA>
{
protected:
ClassA(){}
public:
static shared_ptr<ClassA> create(){ return shared_ptr<ClassA>( new ClassA() ); }
virtual void quack(){ std::cout<<"quacks like a ClassA Base"<<std::endl; }
};
//~ Wrapper for ClassA
struct WrapClassA : public ClassA, wrapper<WrapClassA>
{
static shared_ptr<WrapClassA> create(){ return shared_ptr<WrapClassA>( new WrapClassA() ); }
void quack()
{
std::cout<<"quacking like a Wrapper..."<<std::endl;
if (override f = this->get_override("quack"))
{
std::cout<<"... override found!"<<std::endl;
f();
}
else
{
std::cout<<"... no override found!"<<std::endl;
ClassA::quack();
}
}
void default_quack(){ this->ClassA::quack(); }
};
//~ C++ Call Test
void quack( shared_ptr<ClassA> ptr )
{
ptr->quack();
}
//~ Exposing
BOOST_PYTHON_MODULE(TestCase)
{
def( "quack", &quack );
class_<ClassA, shared_ptr<WrapClassA>, noncopyable>( "ClassA", no_init )
.def( "__init__", make_constructor(&WrapClassA::create) )
.def( "quack", &ClassA::quack, &WrapClassA::default_quack )
;
}
//~ Main
int main()
{
PyImport_AppendInittab( "TestCase", &initTestCase );
Py_Initialize();
boost::python::object main_module((boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__")))));
boost::python::object main_namespace = main_module.attr("__dict__");
boost::python::object testcase_module( (boost::python::handle<>(PyImport_ImportModule("TestCase"))) );
main_namespace["TestCase"] = testcase_module;
FILE* test_file = fopen("test.py", "r");
PyRun_SimpleFile(test_file, "test.py");
fclose( test_file );
std::cin.get();
return 0;
}
And here's the contents of test.py:
print "Testing.."
class Derived( TestCase.ClassA ):
def __init__( self ):
TestCase.ClassA.__init__( self )
def quack( self ):
print( "Quacks like a derived class!" )
Ainst = TestCase.ClassA()
TestCase.quack( Ainst ) #Should print 'Quacks like ClassA Base'
Dinst = Derived()
TestCase.quack( Dinst ) #Should print 'Quacks like a derived class!', but doesn't!
And the output:
Testing... quacking like a Wrapper...
... no override found! quacks like a
ClassA Base quacking like a Wrapper...
... no override found! quacks like a
ClassA Base
So both the base and the class derived in python are acting the same. It looks like it's not finding the override for some reason. I'm not sure but this may have something to do with the create() function. Any ideas would be greatly appreciated!
EDIT:
Added pythonquack to the py script - This works as expect:
def pythonquack( Inst ):
print Inst
Inst.quack()
Calling it for Ainst and Dinst says 'Quacks like a Base', and 'Quacks like a Derived', as I would expect. So for some reason the overrides aren't getting passed back to C++.
A:
I ended up rethinking my design using intrusive_ptrs. There was a little more work to be done with the wrappers than using shared_ptr, but it worked out fairly well. Thanks to everyone for their time.
|
Boost::Python, static factories, and inheritance
|
So I may have a rather unique use case here, but I'm thinking it should work- But it's not working correctly.
Basically, I have a class that uses a static factory method ( create ) that returns a shared_ptr to the newly created
instance of the class. This class also has a virtual function that I'd like to override from python and call from C++.
Maybe my code can express the thought more clearly than my words:
#include <string>
#include <iostream>
#include <boost/python.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::python;
using namespace boost;
//~ Base Class ClassA
class ClassA
: public enable_shared_from_this<ClassA>
{
protected:
ClassA(){}
public:
static shared_ptr<ClassA> create(){ return shared_ptr<ClassA>( new ClassA() ); }
virtual void quack(){ std::cout<<"quacks like a ClassA Base"<<std::endl; }
};
//~ Wrapper for ClassA
struct WrapClassA : public ClassA, wrapper<WrapClassA>
{
static shared_ptr<WrapClassA> create(){ return shared_ptr<WrapClassA>( new WrapClassA() ); }
void quack()
{
std::cout<<"quacking like a Wrapper..."<<std::endl;
if (override f = this->get_override("quack"))
{
std::cout<<"... override found!"<<std::endl;
f();
}
else
{
std::cout<<"... no override found!"<<std::endl;
ClassA::quack();
}
}
void default_quack(){ this->ClassA::quack(); }
};
//~ C++ Call Test
void quack( shared_ptr<ClassA> ptr )
{
ptr->quack();
}
//~ Exposing
BOOST_PYTHON_MODULE(TestCase)
{
def( "quack", &quack );
class_<ClassA, shared_ptr<WrapClassA>, noncopyable>( "ClassA", no_init )
.def( "__init__", make_constructor(&WrapClassA::create) )
.def( "quack", &ClassA::quack, &WrapClassA::default_quack )
;
}
//~ Main
int main()
{
PyImport_AppendInittab( "TestCase", &initTestCase );
Py_Initialize();
boost::python::object main_module((boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__")))));
boost::python::object main_namespace = main_module.attr("__dict__");
boost::python::object testcase_module( (boost::python::handle<>(PyImport_ImportModule("TestCase"))) );
main_namespace["TestCase"] = testcase_module;
FILE* test_file = fopen("test.py", "r");
PyRun_SimpleFile(test_file, "test.py");
fclose( test_file );
std::cin.get();
return 0;
}
And here's the contents of test.py:
print "Testing.."
class Derived( TestCase.ClassA ):
def __init__( self ):
TestCase.ClassA.__init__( self )
def quack( self ):
print( "Quacks like a derived class!" )
Ainst = TestCase.ClassA()
TestCase.quack( Ainst ) #Should print 'Quacks like ClassA Base'
Dinst = Derived()
TestCase.quack( Dinst ) #Should print 'Quacks like a derived class!', but doesn't!
And the output:
Testing... quacking like a Wrapper...
... no override found! quacks like a
ClassA Base quacking like a Wrapper...
... no override found! quacks like a
ClassA Base
So both the base and the class derived in python are acting the same. It looks like it's not finding the override for some reason. I'm not sure but this may have something to do with the create() function. Any ideas would be greatly appreciated!
EDIT:
Added pythonquack to the py script - This works as expect:
def pythonquack( Inst ):
print Inst
Inst.quack()
Calling it for Ainst and Dinst says 'Quacks like a Base', and 'Quacks like a Derived', as I would expect. So for some reason the overrides aren't getting passed back to C++.
|
[
"I ended up rethinking my design using intrusive_ptrs. There was a little more work to be done with the wrappers than using shared_ptr, but it worked out fairly well. Thanks to everyone for their time.\n"
] |
[
1
] |
[] |
[] |
[
"boost",
"c++",
"python"
] |
stackoverflow_0002148777_boost_c++_python.txt
|
Q:
Suggestions on manipulating an SVG map
I'm working on a map of the native languages of California for Wikipedia. The map contains areas that each correspond to a language. The original looks like this (click it to see the SVG):
I want to make "locator maps" for each of those individual languages by hand (in Inkscape), like this one, for a language called Cahuilla (which has the language code cah):
Needless to say, doing this would be a pain in the neck if I generated all 60-some by hand in Inkscape.
Worse, whenever I find a mistake in the original, I'd have to redo the whole set of locator maps. (And in fact I recently realized that my original is missing one language entirely. Sorry Cupeño.)
So my goal is to automate this process. I don't have much experience processing SVG or even XML, so I'm looking for recommendations as to which libraries would be most helpful. I'd prefer solutions in Python, sincely I'm not hopeless in that language.
To summarize, I need to:
Get a list of references to all the language shapes in the original SVG file.
For each language in this list:
change the background color of the shape for the current language
put a box around the language
duplicate the box and scale it to a given size (I recognize that in this step it might be difficult to actually "crop" the surrounding shapes as I did in my example -- just creating a box with the language shape on a white background would be sufficient.)
place the duplicate in the upper right corner
save all this stuff in code.svg
The final product will then be 60 SVG files named cah.svg, etc. Better yet, it would be possible to re-generate the whole shebang if it became necessary to edit the original map (which is quite likely).
A:
I would recommend using Python and specifically creating extensions for Inkscape. I don't think you really need 60 SVG unless you really want to because the source map will have everything you need.
What I would do is use Inkscape to rename the various regions to the same language code you will be using. For example, Cahuilla or cah is currently path13882 in your SVG file. I would rename it to cah or Cahuilla and repeat the process for each of the language regions. Use the Edit\XML Editor to help make sure you update all of the paths.
After you have updated the names/IDs, then you might look into SVG scripting. I would just create a javascript/ecmascript map or dictionary that has the relevant information for the language:
var langaugeMap = {};
languageMap["cah"] = { name: "Cahuilla", color: "rgb(255, 0, 0)" };
languageMap["cup"] = { name: "Cupeño", color: "rgb(255, 64, 0)" };
// and so on -- this could even be generated from a CSV file or Excel, etc.
// if the highlighted color is always the same, then you don't need it in the map
// or use style sheets for an activeshape and inactiveshape
// Put any information that is specific to a language in the map
Then you just need to add a mouseover function that would add and position the bounding box and change the path color. Here is one example of events and scripting although it is quite dated. Carto.net has an interactive map example as well.
The SVG would look something like:
<path
style="fill:#800000;fill-opacity:1;display:inline"
d="m 422.43078,517.40746 c 0.52151,0.006 1.10755,0.0374 1.75925,0.0825 3.82011,0.26462 5.01088,0.75501 5.75001,2.37491 0.51312,1.12355 2.4121,3.0097 4.22213,4.1946 3.906,2.55656 7.38824,2.07964 9.61517,-1.3194 2.12996,-3.25075 9.13451,-3.19196 13.61739,0.11545 1.77185,1.30707 4.04994,2.38037 5.06319,2.38041 1.01325,0 3.34593,0.92548 5.18421,2.06155 2.52816,1.56236 4.9918,2.09869 10.09889,2.19902 3.71359,0.0729 7.68145,0.64349 8.82374,1.26442 2.81717,1.53202 5.67633,1.42382 10.7693,-0.40133 4.97461,-1.78261 6.31161,-1.36525 17.10267,5.31063 3.39862,2.10239 6.90491,4.08094 7.7956,4.39801 2.46593,0.8776 4.55428,4.66976 3.95259,7.17971 -0.29359,1.22605 -0.75898,3.51121 -1.03349,5.07968 -0.27411,1.56855 -0.88382,3.33952 -1.35761,3.93621 -1.50842,1.89871 -20.98501,7.77151 -27.8945,8.41122 -3.66014,0.33879 -8.3091,1.04337 -10.32987,1.56676 -3.50666,0.90799 -3.81743,0.79746 -6.78388,-2.44089 -3.3486,-3.65594 -6.11308,-4.2716 -8.48815,-1.89661 -2.14408,2.14401 -1.85126,3.96434 1.0667,6.66846 1.40725,1.30409 1.85699,2.10446 1.00027,1.77571 -0.85672,-0.32883 -6.3937,-0.12213 -12.3033,0.46176 -5.9096,0.58386 -12.56062,1.27336 -14.78297,1.53381 -4.17058,0.4888 -5.09869,-0.37014 -2.61673,-2.42989 2.1563,-1.78956 1.74245,-2.63318 -1.65999,-3.36449 -1.69931,-0.36525 -4.94789,-1.90738 -7.213,-3.42496 -2.26473,-1.51754 -5.89662,-3.66823 -8.07583,-4.77731 -2.17921,-1.10923 -6.21922,-3.94186 -8.97721,-6.29463 -4.75318,-4.05478 -4.93682,-4.36681 -3.43604,-6.02527 0.96935,-1.07117 2.36209,-1.56397 3.5899,-1.26992 1.62639,0.38937 2.49494,-0.41237 4.59588,-4.24958 1.42481,-2.60257 2.23686,-4.95457 1.80316,-5.22266 -0.4337,-0.26805 -1.06784,-3.14557 -1.40725,-6.39358 -0.33978,-3.24797 -1.19001,-6.79064 -1.89134,-7.87242 -1.74322,-2.68957 -1.2114,-3.65437 2.44111,-3.61188 l 0,0 z"
id="cah"
inkscape:label="#cah"
onmouseover="highlightRegion(evt);"
onmouseout="restoreRegion(evt);" />
For any automation with the SVG file, I would use Inkscape extensions. Look at the Inkscape wiki under the Developer Tutorials / Extensions. Otherwise, SVG is still XML so if you have named your language regions in the source file with a distinguishing name, you could use Python to parse the XML and save each path/language region to a separate file.
A:
Here's an example using your map. You can click any element to get the boundingbox, this can be used for the miniview viewBox (with some tweaking). As you see it's not adding much code to the map, just a couple of elements. When you have all the viewBoxes you can update the miniview 'viewBox' attribute on the fly using javascript.
For the coloring of the selected shape, I'd suggest adding a <use> element inside the miniview <svg> that has a fill that overrides any fill used in the main map (you may have to use a stylesheet rule for this to make sure it's got high specificity, e.g adding #miniview .activeshape { fill: red !important }. Let the <use> point to the selected shape, and make sure you add class="activeshape" on the shape you point to.
This should be a start at least, hope it helps :)
|
Suggestions on manipulating an SVG map
|
I'm working on a map of the native languages of California for Wikipedia. The map contains areas that each correspond to a language. The original looks like this (click it to see the SVG):
I want to make "locator maps" for each of those individual languages by hand (in Inkscape), like this one, for a language called Cahuilla (which has the language code cah):
Needless to say, doing this would be a pain in the neck if I generated all 60-some by hand in Inkscape.
Worse, whenever I find a mistake in the original, I'd have to redo the whole set of locator maps. (And in fact I recently realized that my original is missing one language entirely. Sorry Cupeño.)
So my goal is to automate this process. I don't have much experience processing SVG or even XML, so I'm looking for recommendations as to which libraries would be most helpful. I'd prefer solutions in Python, sincely I'm not hopeless in that language.
To summarize, I need to:
Get a list of references to all the language shapes in the original SVG file.
For each language in this list:
change the background color of the shape for the current language
put a box around the language
duplicate the box and scale it to a given size (I recognize that in this step it might be difficult to actually "crop" the surrounding shapes as I did in my example -- just creating a box with the language shape on a white background would be sufficient.)
place the duplicate in the upper right corner
save all this stuff in code.svg
The final product will then be 60 SVG files named cah.svg, etc. Better yet, it would be possible to re-generate the whole shebang if it became necessary to edit the original map (which is quite likely).
|
[
"I would recommend using Python and specifically creating extensions for Inkscape. I don't think you really need 60 SVG unless you really want to because the source map will have everything you need.\nWhat I would do is use Inkscape to rename the various regions to the same language code you will be using. For example, Cahuilla or cah is currently path13882 in your SVG file. I would rename it to cah or Cahuilla and repeat the process for each of the language regions. Use the Edit\\XML Editor to help make sure you update all of the paths.\nAfter you have updated the names/IDs, then you might look into SVG scripting. I would just create a javascript/ecmascript map or dictionary that has the relevant information for the language:\nvar langaugeMap = {};\nlanguageMap[\"cah\"] = { name: \"Cahuilla\", color: \"rgb(255, 0, 0)\" };\nlanguageMap[\"cup\"] = { name: \"Cupeño\", color: \"rgb(255, 64, 0)\" };\n// and so on -- this could even be generated from a CSV file or Excel, etc.\n// if the highlighted color is always the same, then you don't need it in the map\n// or use style sheets for an activeshape and inactiveshape\n// Put any information that is specific to a language in the map\n\nThen you just need to add a mouseover function that would add and position the bounding box and change the path color. Here is one example of events and scripting although it is quite dated. Carto.net has an interactive map example as well.\nThe SVG would look something like:\n<path\n style=\"fill:#800000;fill-opacity:1;display:inline\"\n d=\"m 422.43078,517.40746 c 0.52151,0.006 1.10755,0.0374 1.75925,0.0825 3.82011,0.26462 5.01088,0.75501 5.75001,2.37491 0.51312,1.12355 2.4121,3.0097 4.22213,4.1946 3.906,2.55656 7.38824,2.07964 9.61517,-1.3194 2.12996,-3.25075 9.13451,-3.19196 13.61739,0.11545 1.77185,1.30707 4.04994,2.38037 5.06319,2.38041 1.01325,0 3.34593,0.92548 5.18421,2.06155 2.52816,1.56236 4.9918,2.09869 10.09889,2.19902 3.71359,0.0729 7.68145,0.64349 8.82374,1.26442 2.81717,1.53202 5.67633,1.42382 10.7693,-0.40133 4.97461,-1.78261 6.31161,-1.36525 17.10267,5.31063 3.39862,2.10239 6.90491,4.08094 7.7956,4.39801 2.46593,0.8776 4.55428,4.66976 3.95259,7.17971 -0.29359,1.22605 -0.75898,3.51121 -1.03349,5.07968 -0.27411,1.56855 -0.88382,3.33952 -1.35761,3.93621 -1.50842,1.89871 -20.98501,7.77151 -27.8945,8.41122 -3.66014,0.33879 -8.3091,1.04337 -10.32987,1.56676 -3.50666,0.90799 -3.81743,0.79746 -6.78388,-2.44089 -3.3486,-3.65594 -6.11308,-4.2716 -8.48815,-1.89661 -2.14408,2.14401 -1.85126,3.96434 1.0667,6.66846 1.40725,1.30409 1.85699,2.10446 1.00027,1.77571 -0.85672,-0.32883 -6.3937,-0.12213 -12.3033,0.46176 -5.9096,0.58386 -12.56062,1.27336 -14.78297,1.53381 -4.17058,0.4888 -5.09869,-0.37014 -2.61673,-2.42989 2.1563,-1.78956 1.74245,-2.63318 -1.65999,-3.36449 -1.69931,-0.36525 -4.94789,-1.90738 -7.213,-3.42496 -2.26473,-1.51754 -5.89662,-3.66823 -8.07583,-4.77731 -2.17921,-1.10923 -6.21922,-3.94186 -8.97721,-6.29463 -4.75318,-4.05478 -4.93682,-4.36681 -3.43604,-6.02527 0.96935,-1.07117 2.36209,-1.56397 3.5899,-1.26992 1.62639,0.38937 2.49494,-0.41237 4.59588,-4.24958 1.42481,-2.60257 2.23686,-4.95457 1.80316,-5.22266 -0.4337,-0.26805 -1.06784,-3.14557 -1.40725,-6.39358 -0.33978,-3.24797 -1.19001,-6.79064 -1.89134,-7.87242 -1.74322,-2.68957 -1.2114,-3.65437 2.44111,-3.61188 l 0,0 z\"\n id=\"cah\"\n inkscape:label=\"#cah\"\n onmouseover=\"highlightRegion(evt);\"\n onmouseout=\"restoreRegion(evt);\" />\n\nFor any automation with the SVG file, I would use Inkscape extensions. Look at the Inkscape wiki under the Developer Tutorials / Extensions. Otherwise, SVG is still XML so if you have named your language regions in the source file with a distinguishing name, you could use Python to parse the XML and save each path/language region to a separate file.\n",
"Here's an example using your map. You can click any element to get the boundingbox, this can be used for the miniview viewBox (with some tweaking). As you see it's not adding much code to the map, just a couple of elements. When you have all the viewBoxes you can update the miniview 'viewBox' attribute on the fly using javascript.\nFor the coloring of the selected shape, I'd suggest adding a <use> element inside the miniview <svg> that has a fill that overrides any fill used in the main map (you may have to use a stylesheet rule for this to make sure it's got high specificity, e.g adding #miniview .activeshape { fill: red !important }. Let the <use> point to the selected shape, and make sure you add class=\"activeshape\" on the shape you point to.\nThis should be a start at least, hope it helps :)\n"
] |
[
8,
4
] |
[] |
[] |
[
"cartography",
"python",
"svg"
] |
stackoverflow_0002054438_cartography_python_svg.txt
|
Q:
Blogger (Python) API: How do I retrieve a post by post ID?
Having previously obtained a post ID from a call to gdata.blogger.client.add_post()...
post = client.add_post(...)
post_id = post.get_post_id()
...how do I use that post id to retrieve the post in the future? I thought maybe gdata.blogger.client.Query would be the way to go, but this doesn't support post id as a query term. The example code distributed with the Python gdata module doesn't have an example of this use case, and after poking around gdata.blogger.client.* for a while I'm not making much progress.
I could obviously iterate through all the posts in the blog until find the one with the corresponding id, but that would be a terrible, terrible idea.
A:
Continue my theme of answering my own questions...
After lots of fiddling, it looks like this is one solution. Given:
client -- a gdata.blogger.client.BloggerClient instance, and
blog -- a gdata.blogger.data.Blog instance
post_id -- a post id as returned by gdata.blogger.data.BlogPost.get_post_id
You can do this:
post = client.get_feed(
blog.get_post_link().href + '/%s' % post_id,
auth_token=client.auth_token,
desired_class=gdata.blogger.data.BlogPost)
|
Blogger (Python) API: How do I retrieve a post by post ID?
|
Having previously obtained a post ID from a call to gdata.blogger.client.add_post()...
post = client.add_post(...)
post_id = post.get_post_id()
...how do I use that post id to retrieve the post in the future? I thought maybe gdata.blogger.client.Query would be the way to go, but this doesn't support post id as a query term. The example code distributed with the Python gdata module doesn't have an example of this use case, and after poking around gdata.blogger.client.* for a while I'm not making much progress.
I could obviously iterate through all the posts in the blog until find the one with the corresponding id, but that would be a terrible, terrible idea.
|
[
"Continue my theme of answering my own questions...\nAfter lots of fiddling, it looks like this is one solution. Given:\n\nclient -- a gdata.blogger.client.BloggerClient instance, and\nblog -- a gdata.blogger.data.Blog instance\npost_id -- a post id as returned by gdata.blogger.data.BlogPost.get_post_id\n\nYou can do this:\npost = client.get_feed(\n blog.get_post_link().href + '/%s' % post_id,\n auth_token=client.auth_token,\n desired_class=gdata.blogger.data.BlogPost)\n\n"
] |
[
1
] |
[] |
[] |
[
"blogger",
"gdata",
"python"
] |
stackoverflow_0002152112_blogger_gdata_python.txt
|
Q:
Has anybody tried html2pdf in django?
Ok when im gonna make reports with Java I use iReport for JasperReports Template designs.
But with python the alternative is html2pdf - pisa.
It would be great to see an example of this.
Any hint would be appreciated.
A:
The accounting software we are developing uses pisa to generate pdf reports. The process is like this:
Render a HTML template
Convert the rendered string to pdf. You can directly use the HttpResponse object you will return as output file, or a StringIO object to store the pdf and send its content via HttpResponse.
The mimetype of HttpResponse object should be set to application/pdf and use Content-Disposition header if you want to trigger download instead of displaying in the browser.
Pisa uses some unique CSS properties to specify pdf related formatting (page-size, page-break etc). Their docs provide sufficient examples on this.
Pisa's rendering of HTML/CSS can be quite a bit different from what we usually see in browser. For example, setting border="1" on a <table> will give all cells of the table border, borders are always collapsed (border-collapse css attribute has no effect) etc.
A:
And yes, http://www.xhtml2pdf.com comes with a djangoproject example :)
A:
This is written by me, but answers the exact same questions, so linking it here. http://uswaretech.com/blog/2008/10/generating-pdfs-with-django/
|
Has anybody tried html2pdf in django?
|
Ok when im gonna make reports with Java I use iReport for JasperReports Template designs.
But with python the alternative is html2pdf - pisa.
It would be great to see an example of this.
Any hint would be appreciated.
|
[
"The accounting software we are developing uses pisa to generate pdf reports. The process is like this:\n\nRender a HTML template\nConvert the rendered string to pdf. You can directly use the HttpResponse object you will return as output file, or a StringIO object to store the pdf and send its content via HttpResponse.\nThe mimetype of HttpResponse object should be set to application/pdf and use Content-Disposition header if you want to trigger download instead of displaying in the browser.\n\nPisa uses some unique CSS properties to specify pdf related formatting (page-size, page-break etc). Their docs provide sufficient examples on this.\nPisa's rendering of HTML/CSS can be quite a bit different from what we usually see in browser. For example, setting border=\"1\" on a <table> will give all cells of the table border, borders are always collapsed (border-collapse css attribute has no effect) etc.\n",
"And yes, http://www.xhtml2pdf.com comes with a djangoproject example :)\n",
"This is written by me, but answers the exact same questions, so linking it here. http://uswaretech.com/blog/2008/10/generating-pdfs-with-django/\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"django",
"pdf",
"pdf_generation",
"python"
] |
stackoverflow_0001301442_django_pdf_pdf_generation_python.txt
|
Q:
Adding an edge/node with a color attribute
I a using the networkx package of Python. The documentation says we can do H.add_edge(1,2,color='blue') but the output shows an edge with the default (black) color. When I do H.add_node(12,color='green') I get a new node with same default red color.
A:
Peter, according to the documentation, to change the color with which nodes/edges are drawn, you have to provide the node_color argument to the drawing function. I.e. from this example, to draw a graph like this (note different colors of nodes):
The code is:
#!/usr/bin/env python
"""
Draw a graph with matplotlib.
You must have matplotlib for this to work.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
try:
import matplotlib.pyplot as plt
except:
raise
import networkx as nx
G=nx.house_graph()
# explicitly set positions
pos={0:(0,0),
1:(1,0),
2:(0,1),
3:(1,1),
4:(0.5,2.0)}
nx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4])
nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b')
nx.draw_networkx_edges(G,pos,alpha=0.5,width=6)
plt.axis('off')
plt.savefig("house_with_colors.png") # save as png
plt.show() # display
Note the node_color argument to the second call to draw_networkx_nodes. Does this help?
|
Adding an edge/node with a color attribute
|
I a using the networkx package of Python. The documentation says we can do H.add_edge(1,2,color='blue') but the output shows an edge with the default (black) color. When I do H.add_node(12,color='green') I get a new node with same default red color.
|
[
"Peter, according to the documentation, to change the color with which nodes/edges are drawn, you have to provide the node_color argument to the drawing function. I.e. from this example, to draw a graph like this (note different colors of nodes):\n\nThe code is:\n#!/usr/bin/env python\n\"\"\"\nDraw a graph with matplotlib.\nYou must have matplotlib for this to work.\n\"\"\"\n__author__ = \"\"\"Aric Hagberg (hagberg@lanl.gov)\"\"\"\ntry:\n import matplotlib.pyplot as plt\nexcept:\n raise\n\nimport networkx as nx\n\nG=nx.house_graph()\n# explicitly set positions\npos={0:(0,0),\n 1:(1,0),\n 2:(0,1),\n 3:(1,1),\n 4:(0.5,2.0)}\n\nnx.draw_networkx_nodes(G,pos,node_size=2000,nodelist=[4])\nnx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color='b')\nnx.draw_networkx_edges(G,pos,alpha=0.5,width=6)\nplt.axis('off')\nplt.savefig(\"house_with_colors.png\") # save as png\nplt.show() # display\n\nNote the node_color argument to the second call to draw_networkx_nodes. Does this help?\n"
] |
[
4
] |
[] |
[] |
[
"networkx",
"python"
] |
stackoverflow_0002160161_networkx_python.txt
|
Q:
imports while starting an interactive shell
When I start the interactive django shell through manage.py, by executing
python -v manage.py shell
from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in the shell.
The same happens when I just run the Python shell (with the -v argument). For example I see this in the verbose output,
import os # precompiled from /usr/local/gdp/lib/python2.4/os.pyc
but still i have to do import os to import and use the os module. What is being imported that am seeing in the verbose output and why I have to import them explicitly again to use them in the shell? Does Python load some essential modules while starting the shell or is it some kind of behind-the-scene magic?
A:
-v traces the first import of a module -- the one that actually loads the module (executes its code, and so may take a bit of time) and sticks it into sys.modules.
That has nothing to do whether your interactive session (module __main__) gets the module injected into its namespace, of course. To ensure module 'goo' does get into the namespace of module 'X' (for any X, so of course including __main__... among many, many others), module 'X' just needs to import goo itself (a very fast operation indeed, if sys.modules['goo'] is already defined!-).
A:
Python loads the site module implicitly when starting up, which may in turn import other modules for its own use. You can pass -S to disable this behavior.
A:
They are getting imported (look at sys.modules) and references to the module are created in whichever modules have imported it.
When you do an import in your shell, if the module has already been imported, you will just get a copy of the reference to it in sys.modules
|
imports while starting an interactive shell
|
When I start the interactive django shell through manage.py, by executing
python -v manage.py shell
from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in the shell.
The same happens when I just run the Python shell (with the -v argument). For example I see this in the verbose output,
import os # precompiled from /usr/local/gdp/lib/python2.4/os.pyc
but still i have to do import os to import and use the os module. What is being imported that am seeing in the verbose output and why I have to import them explicitly again to use them in the shell? Does Python load some essential modules while starting the shell or is it some kind of behind-the-scene magic?
|
[
"-v traces the first import of a module -- the one that actually loads the module (executes its code, and so may take a bit of time) and sticks it into sys.modules.\nThat has nothing to do whether your interactive session (module __main__) gets the module injected into its namespace, of course. To ensure module 'goo' does get into the namespace of module 'X' (for any X, so of course including __main__... among many, many others), module 'X' just needs to import goo itself (a very fast operation indeed, if sys.modules['goo'] is already defined!-).\n",
"Python loads the site module implicitly when starting up, which may in turn import other modules for its own use. You can pass -S to disable this behavior.\n",
"They are getting imported (look at sys.modules) and references to the module are created in whichever modules have imported it.\nWhen you do an import in your shell, if the module has already been imported, you will just get a copy of the reference to it in sys.modules \n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"import",
"python",
"shell"
] |
stackoverflow_0002160190_django_import_python_shell.txt
|
Q:
Problem In Running easy_install.exe under Windows
I am running Python under windows.
I face no problem in installing pysqlite package.
C:\>c:\Python26\Scripts\easy_install.exe pysqlite
Searching for pysqlite
Reading http://pypi.python.org/simple/pysqlite/
........
Download error: [Errno 11001] getaddrinfo failed -- Some packages may not be found!
Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads
........
Best match: pysqlite 2.5.6
Downloading http://pysqlite.googlecode.com/files/pysqlite-2.5.6.win32-py2.6.exe
Processing pysqlite-2.5.6.win32-py2.6.exe
WARNING: can't process DATA/pysqlite2-doc/default.css
WARNING: can't process DATA/pysqlite2-doc/docutils.css
WARNING: can't process DATA/pysqlite2-doc/install-source.txt
creating 'c:\docume~1\yan-ch~1.che\locals~1\temp\easy_install-5wz15q\pysqlite-2.5.6-py2.6-win32.egg' and adding 'c:\docume~1\ya
n-ch~1.che\locals~1\temp\easy_install-5wz15q\pysqlite-2.5.6-py2.6-win32.egg.tmp' to it
Moving pysqlite-2.5.6-py2.6-win32.egg to c:\python26\lib\site-packages
Adding pysqlite 2.5.6 to easy-install.pth file
Installed c:\python26\lib\site-packages\pysqlite-2.5.6-py2.6-win32.egg
Processing dependencies for pysqlite
Finished processing dependencies for pysqlite
However, I fail to install psycopg
C:\>c:\Python26\Scripts\easy_install.exe psycopg
Searching for psycopg
Reading http://pypi.python.org/simple/psycopg/
Reading http://initd.org/projects/psycopg1
Best match: psycopg 1.1.21
Downloading http://initd.org/pub/software/psycopg/psycopg-1.1.21.tar.gz
Processing psycopg-1.1.21.tar.gz
error: Couldn't find a setup script in c:\docume~1\yan-ch~1.che\locals~1\temp\easy_install-recnw8\psycopg-1.1.21.tar.gz
Is there other alternative?
Thanks!
A:
The psycopg PyPi posting does not contain a pre-built w32 installer that easy_install can use nor could it find a way to build from source.
Here are some pre-built versions of the psycopg module.
A:
easy_install only knows how to install modules distributed with the Python standard distribution and packaging solution called distutils. Psycopg is not. Psycopg is instead installed with the so called CMMI dance: configure/make/make install. Doing that on Windows is tricky, hence, you need to download a precompiled version, see Christians answer.
|
Problem In Running easy_install.exe under Windows
|
I am running Python under windows.
I face no problem in installing pysqlite package.
C:\>c:\Python26\Scripts\easy_install.exe pysqlite
Searching for pysqlite
Reading http://pypi.python.org/simple/pysqlite/
........
Download error: [Errno 11001] getaddrinfo failed -- Some packages may not be found!
Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads
........
Best match: pysqlite 2.5.6
Downloading http://pysqlite.googlecode.com/files/pysqlite-2.5.6.win32-py2.6.exe
Processing pysqlite-2.5.6.win32-py2.6.exe
WARNING: can't process DATA/pysqlite2-doc/default.css
WARNING: can't process DATA/pysqlite2-doc/docutils.css
WARNING: can't process DATA/pysqlite2-doc/install-source.txt
creating 'c:\docume~1\yan-ch~1.che\locals~1\temp\easy_install-5wz15q\pysqlite-2.5.6-py2.6-win32.egg' and adding 'c:\docume~1\ya
n-ch~1.che\locals~1\temp\easy_install-5wz15q\pysqlite-2.5.6-py2.6-win32.egg.tmp' to it
Moving pysqlite-2.5.6-py2.6-win32.egg to c:\python26\lib\site-packages
Adding pysqlite 2.5.6 to easy-install.pth file
Installed c:\python26\lib\site-packages\pysqlite-2.5.6-py2.6-win32.egg
Processing dependencies for pysqlite
Finished processing dependencies for pysqlite
However, I fail to install psycopg
C:\>c:\Python26\Scripts\easy_install.exe psycopg
Searching for psycopg
Reading http://pypi.python.org/simple/psycopg/
Reading http://initd.org/projects/psycopg1
Best match: psycopg 1.1.21
Downloading http://initd.org/pub/software/psycopg/psycopg-1.1.21.tar.gz
Processing psycopg-1.1.21.tar.gz
error: Couldn't find a setup script in c:\docume~1\yan-ch~1.che\locals~1\temp\easy_install-recnw8\psycopg-1.1.21.tar.gz
Is there other alternative?
Thanks!
|
[
"The psycopg PyPi posting does not contain a pre-built w32 installer that easy_install can use nor could it find a way to build from source.\nHere are some pre-built versions of the psycopg module.\n",
"easy_install only knows how to install modules distributed with the Python standard distribution and packaging solution called distutils. Psycopg is not. Psycopg is instead installed with the so called CMMI dance: configure/make/make install. Doing that on Windows is tricky, hence, you need to download a precompiled version, see Christians answer.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002159809_python.txt
|
Q:
Addressing instance name string in __init__(self) in Python
I am doing something like this:
class Class(object):
def __init__(self):
self.var=#new instance name string#
How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:
c=Class()
I want c.var equal to 'c'.
Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:
c=Class()
Then, suppose:
del c
Later on:
c=Class()
sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.
Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:
c=Class()
Then, suppose:
del c
Later on:
c=Class()
sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.
A:
Python doesn't have variables, it has objects and names. When you do
c = Class()
you're doing two things:
Creating a new object of type Class
Binding the object to the name c in the current scope.
The object you created doesn't have any concept of a "variable name" -- If later you do
a = c
then the same object is accessible in exactly the same way using the names a and c. You can delete the name a, and the object would still exist.
If the objects you create need to have a name, the best way is to pass it to them explicitly,
class Class(object):
def __init__(self, name):
self.name = name
var = Class('var')
A:
You can't do this. The reason for this is that the object of the class is created first, and only afterwards is this object bound to the name of the instance.
A:
You can't (short of incredible hacks like examining the stack frame and inspecting the bytecode). There may not even be a name, or there could be multiple such names. What should be given for the following code fragments for instance:
l = [Class(), Class()]
a=b=c=d=Class()
A:
I don't think this would be possible because the assignment to the variable of your new instance occours after the object is fully constructed and initialized and so you don't know the variable name it will be assigned to within init method
A:
I am unaware of a way to access a variable's name programmatically without using deep reflection and a debugger. I do not think the information is available at runtime.
If you want to give instances a (unique?) name, you should probably make the initializer accept an extra argument.
def __init__(self, name):
self.name = name
And the caller should pass in the appropriate name:
c = Class("c")
A:
This is a scope issue, you can't do what you're asking. Because c would be declared outside your class' scope, your instance is unaware of what its been named in code.
Perhaps if you can provide a broader explanation of what you're trying to accomplish a better solution can be suggested.
A:
To persist data objects you need to use the database record's unique ID.
pesudo code because I don't know what database module you're using
import db # assume this is your db module
class Class(object):
def __init__(self):
self.id = None
self.name = None
def get_by_id(self, id):
records = db.execute('select * from table where id=%s' % str(id))
if records:
self.id = records[0]['id']
self.name = records[0]['name']
def save(self):
db.execute('update table set name=%s where id=%s' % (self.name, str(self.id)))
Again, this is pseudo code, the string injection technique I'm using is NOT advised as its fairly insecure, its just there to illustrate how to persist using classes with a db.
A:
That isn't possible. You seem to be confusing variables and objects.
In any case there may well not be a variable:
e.g.
foo(Class())
Class().arbitraryMethod()
Or multiple:
a = b = Class()
A:
I have the same thought several years ago. This is somekind of neat feature, but the language creator doesn't provide it. And I thought they are all fool to not discover this great feature.
But then come to think about that. I think the logic is impossible. say:
class Class(object):
def __init__(self):
self.instance_name.move() # self.instance_name refer to var
def move(self):
print "move"
var = Class()
now if the var is an array is that possible too ?
var[0] = Class() # i think it will get confused a bit
that's what i think of, i don't think that assigning the instance into itself is possible. and in some language I just sent the instance string into the object then using eval to execute the function
|
Addressing instance name string in __init__(self) in Python
|
I am doing something like this:
class Class(object):
def __init__(self):
self.var=#new instance name string#
How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:
c=Class()
I want c.var equal to 'c'.
Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:
c=Class()
Then, suppose:
del c
Later on:
c=Class()
sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.
Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:
c=Class()
Then, suppose:
del c
Later on:
c=Class()
sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.
|
[
"Python doesn't have variables, it has objects and names. When you do \nc = Class()\n\nyou're doing two things:\n\nCreating a new object of type Class\nBinding the object to the name c in the current scope.\n\nThe object you created doesn't have any concept of a \"variable name\" -- If later you do\na = c\n\nthen the same object is accessible in exactly the same way using the names a and c. You can delete the name a, and the object would still exist.\nIf the objects you create need to have a name, the best way is to pass it to them explicitly, \nclass Class(object):\n def __init__(self, name):\n self.name = name\n\nvar = Class('var')\n\n",
"You can't do this. The reason for this is that the object of the class is created first, and only afterwards is this object bound to the name of the instance.\n",
"You can't (short of incredible hacks like examining the stack frame and inspecting the bytecode). There may not even be a name, or there could be multiple such names. What should be given for the following code fragments for instance:\nl = [Class(), Class()]\na=b=c=d=Class()\n\n",
"I don't think this would be possible because the assignment to the variable of your new instance occours after the object is fully constructed and initialized and so you don't know the variable name it will be assigned to within init method\n",
"I am unaware of a way to access a variable's name programmatically without using deep reflection and a debugger. I do not think the information is available at runtime.\nIf you want to give instances a (unique?) name, you should probably make the initializer accept an extra argument.\ndef __init__(self, name):\n self.name = name\n\nAnd the caller should pass in the appropriate name:\nc = Class(\"c\")\n\n",
"This is a scope issue, you can't do what you're asking. Because c would be declared outside your class' scope, your instance is unaware of what its been named in code.\nPerhaps if you can provide a broader explanation of what you're trying to accomplish a better solution can be suggested.\n",
"To persist data objects you need to use the database record's unique ID.\npesudo code because I don't know what database module you're using\nimport db # assume this is your db module\n\nclass Class(object):\n def __init__(self):\n self.id = None\n self.name = None\n\n def get_by_id(self, id):\n records = db.execute('select * from table where id=%s' % str(id))\n if records:\n self.id = records[0]['id']\n self.name = records[0]['name']\n\n def save(self):\n db.execute('update table set name=%s where id=%s' % (self.name, str(self.id)))\n\nAgain, this is pseudo code, the string injection technique I'm using is NOT advised as its fairly insecure, its just there to illustrate how to persist using classes with a db.\n",
"That isn't possible. You seem to be confusing variables and objects.\nIn any case there may well not be a variable:\ne.g.\nfoo(Class())\n\nClass().arbitraryMethod()\n\nOr multiple:\na = b = Class()\n\n",
"I have the same thought several years ago. This is somekind of neat feature, but the language creator doesn't provide it. And I thought they are all fool to not discover this great feature.\nBut then come to think about that. I think the logic is impossible. say:\nclass Class(object):\n def __init__(self):\n self.instance_name.move() # self.instance_name refer to var\n def move(self):\n print \"move\"\n\nvar = Class()\n\nnow if the var is an array is that possible too ?\nvar[0] = Class() # i think it will get confused a bit\n\nthat's what i think of, i don't think that assigning the instance into itself is possible. and in some language I just sent the instance string into the object then using eval to execute the function\n"
] |
[
7,
3,
2,
2,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"instance",
"instantiation",
"python"
] |
stackoverflow_0000443775_instance_instantiation_python.txt
|
Q:
Problem Install and Run psycopg2 + Windows + Apache2 + mod_wsgi
1) I try to setup a new web environment to host python + psycopg2 code. Here are my steps :
2) Download http://modwsgi.googlecode.com/files/mod_wsgi-win32-ap22py26-3.0.so
3) Copy mod_wsgi-win32-ap22py26-3.0.so to C:\Program Files\Apache Software Foundation\Apache2.2\modules,
and rename it as mod_wsgi.so
Add the following new lines into C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /wsgi/ "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/wsgi/"
4) Save a file named C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\wsgi\myapp.py with the following content :
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
5) Access using http://localhost/wsgi/myapp.py
6) Install http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.13.win32-py2.6-pg8.4.1-release.exe
7) If I modify the file content to
import psycopg2
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
I will get
ImportError: No module named psycopg2
How can I tell apache, I had install the psycopg2 module in C:\Python26
8) I run the following standalone script to show psycopg2 had been installed.
import psycopg2
print "Hello, World!"
I run it using
C:\Documents and Settings\yan-cheng.cheok\Desktop>mypython.py
Hello, World!
Seem my python environment is OK.
A:
I am able to solve the problem, by moving python script outside htdocs
WSGIScriptAlias /wsgi "C:/wsgi/"
<Directory "C:/wsgi">
AllowOverride None
Options None
Order deny,allow
Allow from all
</Directory>
|
Problem Install and Run psycopg2 + Windows + Apache2 + mod_wsgi
|
1) I try to setup a new web environment to host python + psycopg2 code. Here are my steps :
2) Download http://modwsgi.googlecode.com/files/mod_wsgi-win32-ap22py26-3.0.so
3) Copy mod_wsgi-win32-ap22py26-3.0.so to C:\Program Files\Apache Software Foundation\Apache2.2\modules,
and rename it as mod_wsgi.so
Add the following new lines into C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias /wsgi/ "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/wsgi/"
4) Save a file named C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\wsgi\myapp.py with the following content :
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
5) Access using http://localhost/wsgi/myapp.py
6) Install http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.0.13.win32-py2.6-pg8.4.1-release.exe
7) If I modify the file content to
import psycopg2
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
I will get
ImportError: No module named psycopg2
How can I tell apache, I had install the psycopg2 module in C:\Python26
8) I run the following standalone script to show psycopg2 had been installed.
import psycopg2
print "Hello, World!"
I run it using
C:\Documents and Settings\yan-cheng.cheok\Desktop>mypython.py
Hello, World!
Seem my python environment is OK.
|
[
"I am able to solve the problem, by moving python script outside htdocs\nWSGIScriptAlias /wsgi \"C:/wsgi/\"\n\n<Directory \"C:/wsgi\">\n AllowOverride None\n Options None\n Order deny,allow\n Allow from all\n</Directory>\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002160256_python.txt
|
Q:
Python GTK+: create custom signals?
Is it possible to create new signals in Python GTK+ ?
I'd like a skeleton code example, please.
A:
An excerpt:
Creating your own signals
The other thing you probably want to
use when subclassing GObject is define
custom signals. You can create your
own signals that can be emitted so
users of your class can connect to
them.
When a signal is emitted a set of
closures will be executed. A closure
is an abstraction of the callback
concept. A closure is the callback
itself (a function pointer), the user
data (it will be the last parameter to
the callback) and another function for
cleanup issues, which will not be
discussed in this document.
For the sake of this article you don't
really need to know the difference
between a callback and a closure so
both terms will be used. But be
advised that this is not totally
correct.
As we said before, when a signal is
emitted, a set of closures will be
executed. One of them is the same one
for all the instances of this class
and hence its name: the class closure,
and the other ones are custom user
callbacks. Note that not all the
signals need to have a class closure
because it is optional.
From, http://www.pygtk.org/articles/subclassing-gobject/sub-classing-gobject-in-python.htm, hope that helps. There is example code on the site and here , a snippet:
import pygtk
pygtk.require('2.0')
import gobject
class Car(gobject.GObject):
__gproperties__ = {
'fuel' : (gobject.TYPE_FLOAT, 'fuel of the car',
'amount of fuel that remains in the tank',
0, 60, 50, gobject.PARAM_READWRITE)
}
__gsignals__ = {
'engine-started' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
(gobject.TYPE_FLOAT,))
}
def __init__(self):
gobject.GObject.__init__(self)
self.fuel = 50
def do_get_property(self, property):
if property.name == 'fuel':
return self.fuel
else:
raise AttributeError, 'unknown property %s' % property.name
def do_set_property(self, property, value):
if property.name == 'fuel':
self.fuel = value
else:
raise AttributeError, 'unknown property %s' % property.name
def do_engine_started(self, remaining_fuel):
print '***** Beginning of class closure *****'
print 'The engine is ready and we still have %f of fuel' % self.fuel
print '***** End of class closure *****'
def start(self):
self.emit('engine-started', self.get_property('fuel'))
gobject.type_register(Car)
A:
The answers are correct of course, but using libraries is less prone to pains:
import gobject
from pygtkhelpers.utils import gsignal
class Car(gobject.GObject):
gsignal('engine-started', float) # yeah baby
|
Python GTK+: create custom signals?
|
Is it possible to create new signals in Python GTK+ ?
I'd like a skeleton code example, please.
|
[
"An excerpt:\n\nCreating your own signals\nThe other thing you probably want to\n use when subclassing GObject is define\n custom signals. You can create your\n own signals that can be emitted so\n users of your class can connect to\n them.\nWhen a signal is emitted a set of\n closures will be executed. A closure\n is an abstraction of the callback\n concept. A closure is the callback\n itself (a function pointer), the user\n data (it will be the last parameter to\n the callback) and another function for\n cleanup issues, which will not be\n discussed in this document.\nFor the sake of this article you don't\n really need to know the difference\n between a callback and a closure so\n both terms will be used. But be\n advised that this is not totally\n correct.\nAs we said before, when a signal is\n emitted, a set of closures will be\n executed. One of them is the same one\n for all the instances of this class\n and hence its name: the class closure,\n and the other ones are custom user\n callbacks. Note that not all the\n signals need to have a class closure\n because it is optional.\n\nFrom, http://www.pygtk.org/articles/subclassing-gobject/sub-classing-gobject-in-python.htm, hope that helps. There is example code on the site and here , a snippet:\nimport pygtk\npygtk.require('2.0')\nimport gobject\n\nclass Car(gobject.GObject):\n __gproperties__ = {\n 'fuel' : (gobject.TYPE_FLOAT, 'fuel of the car',\n 'amount of fuel that remains in the tank',\n 0, 60, 50, gobject.PARAM_READWRITE)\n }\n\n __gsignals__ = {\n 'engine-started' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,\n (gobject.TYPE_FLOAT,))\n }\n\n def __init__(self):\n gobject.GObject.__init__(self)\n self.fuel = 50\n\n def do_get_property(self, property):\n if property.name == 'fuel':\n return self.fuel\n else:\n raise AttributeError, 'unknown property %s' % property.name\n\n def do_set_property(self, property, value):\n if property.name == 'fuel':\n self.fuel = value\n else:\n raise AttributeError, 'unknown property %s' % property.name\n\n def do_engine_started(self, remaining_fuel):\n print '***** Beginning of class closure *****'\n print 'The engine is ready and we still have %f of fuel' % self.fuel\n print '***** End of class closure *****'\n\n def start(self):\n self.emit('engine-started', self.get_property('fuel'))\n\ngobject.type_register(Car)\n\n",
"The answers are correct of course, but using libraries is less prone to pains:\nimport gobject\n\nfrom pygtkhelpers.utils import gsignal\n\nclass Car(gobject.GObject):\n\n gsignal('engine-started', float) # yeah baby\n\n"
] |
[
8,
4
] |
[] |
[] |
[
"gtk",
"pygtk",
"python"
] |
stackoverflow_0002057921_gtk_pygtk_python.txt
|
Q:
Single linked list in Python, how to write pop and push?
I am trying to code a class that makes use of Push and Pop from a stack (with single linked list). I am not sure how to write the push and pop functions. I really need a simple example written in Python with the following functions.
Push
Pop
ifEmpty
A:
From the docs that Dyno Fu linked to:
The list methods make it very easy to
use a list as a stack, where the last
element added is the first element
retrieved (“last-in, first-out”). To
add an item to the top of the stack,
use append(). To retrieve an item from
the top of the stack, use pop()
without an explicit index. For
example:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
And finally, to check if a list is empty:
>>> my_list = []
>>> not my_list
True
A:
And here is the simplest stack class:
class stack(list):
def push(self,item):
self.append(item)
def isEmpty(self):
return not self
>>> a = stack()
>>> a.push(1)
>> a.isEmpty()
False
>>> a.pop()
1
>>> a.isEmpty()
True
|
Single linked list in Python, how to write pop and push?
|
I am trying to code a class that makes use of Push and Pop from a stack (with single linked list). I am not sure how to write the push and pop functions. I really need a simple example written in Python with the following functions.
Push
Pop
ifEmpty
|
[
"From the docs that Dyno Fu linked to:\n\nThe list methods make it very easy to\n use a list as a stack, where the last\n element added is the first element\n retrieved (“last-in, first-out”). To\n add an item to the top of the stack,\n use append(). To retrieve an item from\n the top of the stack, use pop()\n without an explicit index. For\n example:\n\n>>> stack = [3, 4, 5]\n>>> stack.append(6)\n>>> stack.append(7)\n>>> stack\n[3, 4, 5, 6, 7]\n>>> stack.pop()\n7\n>>> stack\n[3, 4, 5, 6]\n>>> stack.pop()\n6\n>>> stack.pop()\n5\n>>> stack\n[3, 4]\n\nAnd finally, to check if a list is empty:\n>>> my_list = []\n>>> not my_list\nTrue\n\n",
"And here is the simplest stack class:\nclass stack(list):\n def push(self,item):\n self.append(item)\n def isEmpty(self):\n return not self\n\n>>> a = stack()\n>>> a.push(1)\n>> a.isEmpty()\nFalse\n>>> a.pop()\n1\n>>> a.isEmpty()\nTrue\n\n"
] |
[
8,
3
] |
[] |
[] |
[
"python",
"stack"
] |
stackoverflow_0002160994_python_stack.txt
|
Q:
How do I pass compressed data using the Task Queue Python API in App Engine?
I'm trying to use compressed data with my Tasks in the Task Queue like so:
t = taskqueue.Task(url='/tasks/queue',
params={'param': zlib.compress(some_string)}
However when I try to decompress it in the queue handler like so
message = self.request.get('param')
message = zlib.decompress(message)
I get this error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u06b8' in position 2: ordinal not in range(128)
Anyone know of what's going on here? Is there a work around?
A:
Instead of using params, use payload, which includes your data in the body of the request, unencoded. Then you can use zlib.decompress(self.request.body) to retrieve the data.
A:
Read the docs... (my emphasis!):
params Dictionary of parameters to use
for this Task. Values in the
dictionary may be iterable to indicate
repeated parameters. May not be
specified for a POST request if
payload is already specified. For POST
requests, these params will be encoded
as 'application/x-www-form-urlencoded'
and set to the payload; for all other
methods, the parameters will be
converted to a query string. May not
be specified if the URL already
contains a query string and the method
is GET.
zlib.compress produces an arbitrary string of bytes... but then query-string conversion interprets it as Unicode! So, use any 1-byte codec, such as latin-1, to .encode the compressed results in order to pass (what's actually a binary) bytestring of params, and the same codec for a .decode to get back from the "unicode" string to a string of bytes that you can decompress. Phew... you sure the compression is crucial enough to your app's performance to be worth this weird set of gyrations, or wouldn't it be better to eschew it?-)
|
How do I pass compressed data using the Task Queue Python API in App Engine?
|
I'm trying to use compressed data with my Tasks in the Task Queue like so:
t = taskqueue.Task(url='/tasks/queue',
params={'param': zlib.compress(some_string)}
However when I try to decompress it in the queue handler like so
message = self.request.get('param')
message = zlib.decompress(message)
I get this error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u06b8' in position 2: ordinal not in range(128)
Anyone know of what's going on here? Is there a work around?
|
[
"Instead of using params, use payload, which includes your data in the body of the request, unencoded. Then you can use zlib.decompress(self.request.body) to retrieve the data.\n",
"Read the docs... (my emphasis!):\n\nparams Dictionary of parameters to use\n for this Task. Values in the\n dictionary may be iterable to indicate\n repeated parameters. May not be\n specified for a POST request if\n payload is already specified. For POST\n requests, these params will be encoded\n as 'application/x-www-form-urlencoded'\n and set to the payload; for all other\n methods, the parameters will be\n converted to a query string. May not\n be specified if the URL already\n contains a query string and the method\n is GET.\n\nzlib.compress produces an arbitrary string of bytes... but then query-string conversion interprets it as Unicode! So, use any 1-byte codec, such as latin-1, to .encode the compressed results in order to pass (what's actually a binary) bytestring of params, and the same codec for a .decode to get back from the \"unicode\" string to a string of bytes that you can decompress. Phew... you sure the compression is crucial enough to your app's performance to be worth this weird set of gyrations, or wouldn't it be better to eschew it?-)\n"
] |
[
5,
2
] |
[] |
[] |
[
"google_app_engine",
"python",
"task_queue",
"zlib"
] |
stackoverflow_0002160011_google_app_engine_python_task_queue_zlib.txt
|
Q:
JSON python to javascript
I want to transfer some data from python to javascript. I use Django at python side and jQuery at javascript side.
The object I serialize at python side is a dictionary.
Besides simple objects like lists and variables, this dictionary contains instances of SomeClass. To serialize those instances I extendeded simplejson.JSONEncode like this:
class HandleSomeClass(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle SomeClass """
def default(self, obj):
if isinstance(obj, SomeClass):
readyToSerialize = do_something(obj)
readyToSerialize.magicParameter = 'SomeClass'
return readyToSerialize
return simplejson.JSONEncoder.default(self, obj)
This way, the SomeClass instances appear in JSON as dictionaries having magicParameter == 'SomeClass' Those instances can be nested at various deph.
Now I would like to recreate those instances at javascript side.
I basically would like to hava a JSON decoder, which will convert all dictionaries with magicParameter == 'SomeClass' to custom javascript objects using a simple object factory:
SomeClass = function( rawSomeClass ) {
jQuery.extend( this, rawSomeClass ) // jQuery extend merges the newly-created object and the rawSomeClass object
}
and then I could add methods like this to recreate the original objects:
SomeClass.prototype.get = function( arguments ) {
// function body
}
How to write a decoder, which will scan the JSON object and perform the convertion?
A:
Eval the JSON string into an object
Run through the values of the object and identify values with magicParameter='SomeClass'
Run those values through a converter
Assign the result back to where the value initially was in the result object
|
JSON python to javascript
|
I want to transfer some data from python to javascript. I use Django at python side and jQuery at javascript side.
The object I serialize at python side is a dictionary.
Besides simple objects like lists and variables, this dictionary contains instances of SomeClass. To serialize those instances I extendeded simplejson.JSONEncode like this:
class HandleSomeClass(simplejson.JSONEncoder):
""" simplejson.JSONEncoder extension: handle SomeClass """
def default(self, obj):
if isinstance(obj, SomeClass):
readyToSerialize = do_something(obj)
readyToSerialize.magicParameter = 'SomeClass'
return readyToSerialize
return simplejson.JSONEncoder.default(self, obj)
This way, the SomeClass instances appear in JSON as dictionaries having magicParameter == 'SomeClass' Those instances can be nested at various deph.
Now I would like to recreate those instances at javascript side.
I basically would like to hava a JSON decoder, which will convert all dictionaries with magicParameter == 'SomeClass' to custom javascript objects using a simple object factory:
SomeClass = function( rawSomeClass ) {
jQuery.extend( this, rawSomeClass ) // jQuery extend merges the newly-created object and the rawSomeClass object
}
and then I could add methods like this to recreate the original objects:
SomeClass.prototype.get = function( arguments ) {
// function body
}
How to write a decoder, which will scan the JSON object and perform the convertion?
|
[
"\nEval the JSON string into an object\nRun through the values of the object and identify values with magicParameter='SomeClass'\nRun those values through a converter\nAssign the result back to where the value initially was in the result object\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"javascript",
"jquery",
"json",
"python"
] |
stackoverflow_0002161457_django_javascript_jquery_json_python.txt
|
Q:
Is it possible to access the GetLongPathName() Win32 API in Python?
I need to convert paths in 8.3 convention to full path.
In Perl, I can use Win32::GetLongPathName() as pointed out in How do I get full Win32 path from 8.3 DOS path with Perl? But, I need to do it in Python.
A:
Use ctypes which is available in the Python standard without the need of using the pywin32 API. Like this:
from ctypes import *
buf = create_unicode_buffer(260)
GetLongPathName = windll.kernel32.GetLongPathNameW
rv = GetLongPathName(path, buf, 260)
print buf.value
From http://mail.python.org/pipermail/python-win32/2008-January/006642.html
A:
Use the GetLongPathName function from win32file
import win32file
print win32file.GetLongPathName(r'C:\progra~1')
outputs:
C:\Program Files
|
Is it possible to access the GetLongPathName() Win32 API in Python?
|
I need to convert paths in 8.3 convention to full path.
In Perl, I can use Win32::GetLongPathName() as pointed out in How do I get full Win32 path from 8.3 DOS path with Perl? But, I need to do it in Python.
|
[
"Use ctypes which is available in the Python standard without the need of using the pywin32 API. Like this:\nfrom ctypes import *\n\nbuf = create_unicode_buffer(260)\nGetLongPathName = windll.kernel32.GetLongPathNameW\nrv = GetLongPathName(path, buf, 260)\nprint buf.value\n\nFrom http://mail.python.org/pipermail/python-win32/2008-January/006642.html\n",
"Use the GetLongPathName function from win32file\nimport win32file\nprint win32file.GetLongPathName(r'C:\\progra~1')\n\noutputs:\nC:\\Program Files\n\n"
] |
[
8,
5
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0001587816_python_windows.txt
|
Q:
python libxml2dom xpath question
quick question... i can create/parse a chunk of html using libxml2dom, etc...
however, is there a way to somehow display the xpath used to generate/extract the html chunk.. i'm assuming that there's some method/way of doing this that i can't find..
ex:
import libxml2dom
d = libxml2dom.parseString(s, html=1)
##
hdr="//div[3]/table[1]/tr/th"
thdr_ = d.xpath(hdr)
print "lent = ",len(thdr_)
at this point, thdr_ is an array/list of objects.. each of which points to a chunk of html (if you will)
i'm trying to figure out if there's a way to get, say, the xpath for say, the thdr_[x] element/item of the list...
ie:
thdr_[0]=//div[3]/table[1]/tr[0]/th
thdr_[1]=//div[3]/table[1]/tr[1]/th
thdr_[2]=//div[3]/table[1]/tr[2]/th
.
.
.
any thoughts/comments..
thanks
-tom
A:
I did this by iterating each node and comparing the textContent with my expected text. For fuzzy comparisons I used the SequenceMatcher class from difflib.
|
python libxml2dom xpath question
|
quick question... i can create/parse a chunk of html using libxml2dom, etc...
however, is there a way to somehow display the xpath used to generate/extract the html chunk.. i'm assuming that there's some method/way of doing this that i can't find..
ex:
import libxml2dom
d = libxml2dom.parseString(s, html=1)
##
hdr="//div[3]/table[1]/tr/th"
thdr_ = d.xpath(hdr)
print "lent = ",len(thdr_)
at this point, thdr_ is an array/list of objects.. each of which points to a chunk of html (if you will)
i'm trying to figure out if there's a way to get, say, the xpath for say, the thdr_[x] element/item of the list...
ie:
thdr_[0]=//div[3]/table[1]/tr[0]/th
thdr_[1]=//div[3]/table[1]/tr[1]/th
thdr_[2]=//div[3]/table[1]/tr[2]/th
.
.
.
any thoughts/comments..
thanks
-tom
|
[
"I did this by iterating each node and comparing the textContent with my expected text. For fuzzy comparisons I used the SequenceMatcher class from difflib.\n"
] |
[
0
] |
[] |
[] |
[
"libxml2",
"python"
] |
stackoverflow_0001937477_libxml2_python.txt
|
Q:
Returning the first N characters of a unicode string
I have a string in unicode and I need to return the first N characters.
I am doing this:
result = unistring[:5]
but of course the length of unicode strings != length of characters.
Any ideas? The only solution is using re?
Edit: More info
unistring = "Μεταλλικα" #Metallica written in Greek letters
result = unistring[:1]
returns-> ?
I think that unicode strings are two bytes (char), that's why this thing happens. If I do:
result = unistring[:2]
I get
M
which is correct,
So, should I always slice*2 or should I convert to something?
A:
When you say:
unistring = "Μεταλλικα" #Metallica written in Greek letters
You do not have a unicode string. You have a bytestring in (presumably) UTF-8. That is not the same thing. A unicode string is a separate datatype in Python. You get unicode by decoding bytestrings using the right encoding:
unistring = "Μεταλλικα".decode('utf-8')
or by using the unicode literal in a source file with the right encoding declaration
# coding: UTF-8
unistring = u"Μεταλλικα"
The unicode string will do what you want when you do unistring[:5].
A:
Unfortunately for historical reasons prior to Python 3.0 there are two string types. byte strings (str) and Unicode strings (unicode).
Prior to the unification in Python 3.0 there are two ways to declare a string literal: unistring = "Μεταλλικα" which is a byte string and unistring = u"Μεταλλικα" which is a unicode string.
The reason you see ? when you do result = unistring[:1] is because some of the characters in your Unicode text cannot be correctly represented in the non-unicode string. You have probably seen this kind of problem if you ever used a really old email client and received emails from friends in countries like Greece for example.
So in Python 2.x if you need to handle Unicode you have to do it explicitly. Take a look at this introduction to dealing with Unicode in Python: Unicode HOWTO
A:
There is no correct straight-forward approach with any type of "Unicode string".
Even Python "Unicode" UTF-16 string has variable length characters so, you can't just cut with ustring[:5]. Because some Unicode Code points may use more then one "character" i.e. Surrogate pairs.
So if you want to cut 5 code points (note these are not characters) so you may analyze the text, see http://en.wikipedia.org/wiki/UTF-8 and http://en.wikipedia.org/wiki/UTF-16 definitions. So you need to use some bit masks to figure out boundaries.
Also you still do not get characters. Because for example. Word "שָלוֹם" -- peace in Hebrew "Shalom" consists of 4 characters and 6 code points letter "shin", vowel "a" letter "lamed", letter "vav" and vowel "o" and final letter "mem".
So character is not code point.
Same for most western languages where a letter with diacritics may be represented as two code points. Search for example for "unicode normalization".
So... If you really need 5 first characters you have to use tools like ICU library. For example there is ICU library for Python that provides characters boundary iterator.
|
Returning the first N characters of a unicode string
|
I have a string in unicode and I need to return the first N characters.
I am doing this:
result = unistring[:5]
but of course the length of unicode strings != length of characters.
Any ideas? The only solution is using re?
Edit: More info
unistring = "Μεταλλικα" #Metallica written in Greek letters
result = unistring[:1]
returns-> ?
I think that unicode strings are two bytes (char), that's why this thing happens. If I do:
result = unistring[:2]
I get
M
which is correct,
So, should I always slice*2 or should I convert to something?
|
[
"When you say:\nunistring = \"Μεταλλικα\" #Metallica written in Greek letters\n\nYou do not have a unicode string. You have a bytestring in (presumably) UTF-8. That is not the same thing. A unicode string is a separate datatype in Python. You get unicode by decoding bytestrings using the right encoding:\nunistring = \"Μεταλλικα\".decode('utf-8')\n\nor by using the unicode literal in a source file with the right encoding declaration\n# coding: UTF-8\nunistring = u\"Μεταλλικα\"\n\nThe unicode string will do what you want when you do unistring[:5].\n",
"Unfortunately for historical reasons prior to Python 3.0 there are two string types. byte strings (str) and Unicode strings (unicode). \nPrior to the unification in Python 3.0 there are two ways to declare a string literal: unistring = \"Μεταλλικα\" which is a byte string and unistring = u\"Μεταλλικα\" which is a unicode string.\nThe reason you see ? when you do result = unistring[:1] is because some of the characters in your Unicode text cannot be correctly represented in the non-unicode string. You have probably seen this kind of problem if you ever used a really old email client and received emails from friends in countries like Greece for example.\nSo in Python 2.x if you need to handle Unicode you have to do it explicitly. Take a look at this introduction to dealing with Unicode in Python: Unicode HOWTO\n",
"There is no correct straight-forward approach with any type of \"Unicode string\".\nEven Python \"Unicode\" UTF-16 string has variable length characters so, you can't just cut with ustring[:5]. Because some Unicode Code points may use more then one \"character\" i.e. Surrogate pairs.\nSo if you want to cut 5 code points (note these are not characters) so you may analyze the text, see http://en.wikipedia.org/wiki/UTF-8 and http://en.wikipedia.org/wiki/UTF-16 definitions. So you need to use some bit masks to figure out boundaries.\nAlso you still do not get characters. Because for example. Word \"שָלוֹם\" -- peace in Hebrew \"Shalom\" consists of 4 characters and 6 code points letter \"shin\", vowel \"a\" letter \"lamed\", letter \"vav\" and vowel \"o\" and final letter \"mem\".\nSo character is not code point.\nSame for most western languages where a letter with diacritics may be represented as two code points. Search for example for \"unicode normalization\".\nSo... If you really need 5 first characters you have to use tools like ICU library. For example there is ICU library for Python that provides characters boundary iterator.\n"
] |
[
7,
7,
4
] |
[] |
[] |
[
"python",
"python_2.x",
"unicode"
] |
stackoverflow_0002153920_python_python_2.x_unicode.txt
|
Q:
Modpython and virtualenv
Is it any way to run django site on virtualenv without administration rights? How can I do it? Virtualenv is already installed.
A:
Yes, but not with mod_python.
|
Modpython and virtualenv
|
Is it any way to run django site on virtualenv without administration rights? How can I do it? Virtualenv is already installed.
|
[
"Yes, but not with mod_python.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"mod_python",
"python",
"virtualenv"
] |
stackoverflow_0002162790_django_mod_python_python_virtualenv.txt
|
Q:
Python path in environment
I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script.
e.g.
c:\python26\python.exe test.py
$PYTHONPATH\python.exe test.py
Is there any way to have PYTHONPATH like setting ?
A:
The simplest thing is to add c:\python26 to you system's PATH.
Also, depending on how you installed Python, you should be able to just use test.py on the command line.
A:
set PYTHON_INSTALL=D:\python26
then:
%PYTHON_INSTALL%\python.exe test.py
You could set up the PYTHON_INSTALL var using My Computer | Advanced | Environment Variables if you want it to persist.
EDIT:
And building on the other post (put the path to Python in the system path), you could have the best of both worlds:
set PATH=%PATH%;%PYTHON_INSTALL%
Then you can just call:
python test.py
EDIT 2:
Renamed 'PYTHONPATH' to 'PYTHON_INSTALL' as another poster pointed out that the environment variable 'PYTHONPATH' already has a defined use.
A:
Try
set PYTHONPATH=c:\python26
%PYTHONPATH%\python.exe test.py
Or
set PATH=%PATH%;C:\python26;
python test.py
Note: environment variable PYTHONPATH has different purpose for searching python modules/extensions, So should not be shadowed.
PYTHONPATH : ';'-separated list of directories prefixed to the
default module search path. The result is sys.path.
|
Python path in environment
|
I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script.
e.g.
c:\python26\python.exe test.py
$PYTHONPATH\python.exe test.py
Is there any way to have PYTHONPATH like setting ?
|
[
"The simplest thing is to add c:\\python26 to you system's PATH.\nAlso, depending on how you installed Python, you should be able to just use test.py on the command line.\n",
"set PYTHON_INSTALL=D:\\python26\n\nthen:\n%PYTHON_INSTALL%\\python.exe test.py\n\nYou could set up the PYTHON_INSTALL var using My Computer | Advanced | Environment Variables if you want it to persist.\nEDIT:\nAnd building on the other post (put the path to Python in the system path), you could have the best of both worlds:\nset PATH=%PATH%;%PYTHON_INSTALL%\n\nThen you can just call:\npython test.py\n\nEDIT 2:\nRenamed 'PYTHONPATH' to 'PYTHON_INSTALL' as another poster pointed out that the environment variable 'PYTHONPATH' already has a defined use.\n",
"Try\nset PYTHONPATH=c:\\python26\n%PYTHONPATH%\\python.exe test.py\n\nOr\nset PATH=%PATH%;C:\\python26;\npython test.py\n\nNote: environment variable PYTHONPATH has different purpose for searching python modules/extensions, So should not be shadowed.\nPYTHONPATH : ';'-separated list of directories prefixed to the\n default module search path. The result is sys.path.\n\n"
] |
[
4,
3,
0
] |
[] |
[] |
[
"development_environment",
"environment_variables",
"python",
"scripting",
"windows"
] |
stackoverflow_0002163429_development_environment_environment_variables_python_scripting_windows.txt
|
Q:
Python: subprocess loops forever
I'm trying to start/stop rsyslog through a python script:
RSYSLOG_INIT_SCRIPT='/etc/init.s/rsyslogd'
subprocess.call([RSYSLOG_INIT_SCRIPT,'stop'])
/etc/init.d/rsyslogd is a regular init script. The problem is that it continues executing this script again and again. (I've added an echo to the script to confirm this).
This is the stacktrace when i kill it:
File "queuerunner.py", line 72, in <module>
rsysloglauncher.startrsyslog()
File "/root/logging-server/Logging-server-init/src/initializer/rsyslog/rsysloglauncher.py", line 23, in startrsyslog
subprocess.call([RSYSLOG_INIT_SCRIPT,"stop"])
File "/storage/local/python-2.6.4/lib/python2.6/subprocess.py", line 470, in call
return Popen(*popenargs, **kwargs).wait()
File "/storage/local/python-2.6.4/lib/python2.6/subprocess.py", line 1157, in wait
pid, sts = os.waitpid(self.pid, 0)
A:
Not sure what is going on, but try creating your shell script like this:
#!/bin/sh
while :
do
echo "Sleeping..."
sleep 1
done
Then confirm that your python program when running this script does the same thing.
Then confirm the python call with this script:
#!/bin/sh
echo "I will exit"
See if you can get more output from the original script, create a 'proxy' script - which you will call from your Python script.
#!/bin/sh
/etc/init.s/rsyslogd stop > /tmp/log 2>&1
And edit your original script to produce more output:
#!/bin/sh -xv
I'm assuming it's bourne-shell or bash.
Then call this script : and then check the /tmp/log with a :
tail -f /tmp/log
Also, can you get the :
subprocess.call(...
To return a PID of the process that is created ? If so, then track it using something like:
ps -eaf |grep <PID>
Where should be replaced by the actual PID of course.
Depending on OS, you might also be able to :
truss -o /tmp/truss.out <PID>
If this 'truss.out' continues to fill up with system calls, then you know your shell-script is looping - and then something differs (I'm not sure what yet) between the commandline invocation and the python invocation.
I agree with the other poster : it looks like the script is looping - rather than a problem strictly with the python script.
Another thing to try:
Right at the start of the script, echo out the arguments - you might find that it loops if it cannot get hold of the correct params or something.
A:
Are you sure the script isn't looping itself? The python code looks like it's just waiting for the sub-process to exit.
Get the PID of the python script, then do:
watch pstree -ap <PID>
Look to see if the PID of the start/stop script is the same - maybe the python code is looping itself for some reason.
If the init.d script PID is constant, then do strace or truss on that PID to see what it's doing.
|
Python: subprocess loops forever
|
I'm trying to start/stop rsyslog through a python script:
RSYSLOG_INIT_SCRIPT='/etc/init.s/rsyslogd'
subprocess.call([RSYSLOG_INIT_SCRIPT,'stop'])
/etc/init.d/rsyslogd is a regular init script. The problem is that it continues executing this script again and again. (I've added an echo to the script to confirm this).
This is the stacktrace when i kill it:
File "queuerunner.py", line 72, in <module>
rsysloglauncher.startrsyslog()
File "/root/logging-server/Logging-server-init/src/initializer/rsyslog/rsysloglauncher.py", line 23, in startrsyslog
subprocess.call([RSYSLOG_INIT_SCRIPT,"stop"])
File "/storage/local/python-2.6.4/lib/python2.6/subprocess.py", line 470, in call
return Popen(*popenargs, **kwargs).wait()
File "/storage/local/python-2.6.4/lib/python2.6/subprocess.py", line 1157, in wait
pid, sts = os.waitpid(self.pid, 0)
|
[
"Not sure what is going on, but try creating your shell script like this:\n#!/bin/sh\nwhile :\ndo\n echo \"Sleeping...\"\n sleep 1\ndone\n\nThen confirm that your python program when running this script does the same thing.\nThen confirm the python call with this script:\n#!/bin/sh\necho \"I will exit\"\n\nSee if you can get more output from the original script, create a 'proxy' script - which you will call from your Python script.\n#!/bin/sh\n/etc/init.s/rsyslogd stop > /tmp/log 2>&1\n\nAnd edit your original script to produce more output:\n#!/bin/sh -xv\n\nI'm assuming it's bourne-shell or bash. \nThen call this script : and then check the /tmp/log with a :\ntail -f /tmp/log\n\nAlso, can you get the :\nsubprocess.call(...\n\nTo return a PID of the process that is created ? If so, then track it using something like:\nps -eaf |grep <PID>\n\nWhere should be replaced by the actual PID of course.\nDepending on OS, you might also be able to :\ntruss -o /tmp/truss.out <PID>\n\nIf this 'truss.out' continues to fill up with system calls, then you know your shell-script is looping - and then something differs (I'm not sure what yet) between the commandline invocation and the python invocation.\nI agree with the other poster : it looks like the script is looping - rather than a problem strictly with the python script.\nAnother thing to try:\nRight at the start of the script, echo out the arguments - you might find that it loops if it cannot get hold of the correct params or something.\n",
"Are you sure the script isn't looping itself? The python code looks like it's just waiting for the sub-process to exit.\nGet the PID of the python script, then do:\nwatch pstree -ap <PID>\n\nLook to see if the PID of the start/stop script is the same - maybe the python code is looping itself for some reason.\nIf the init.d script PID is constant, then do strace or truss on that PID to see what it's doing.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"rsyslog",
"subprocess"
] |
stackoverflow_0002163582_python_rsyslog_subprocess.txt
|
Q:
Running external subprocesses and reading return code
I'm creating a python script to sort a lot of images (game screenshots).
I found a way to do that in imagemagick : I know that, if a specific square of the image is the same as the reference crop, then the image is of category one. If not, I check for another crop and another category, and if that doesn't fit either, I put the image in category three.
I found how to do that in Imagemagick :
convert file.jpg -crop 80x10+90+980 +repage crop.jpg
compare -metric PSNR reference.jpg crop.jpg crop.jpg
(I cut a piece of the image, then compare that piece to "reference.jpg")
How do I call that from the script, and do an if based on what convert returns (it's a number) ?
A:
import subprocess
retcode = subprocess.call(['convert', 'file.jpg', '-crop',
'80x10+90+980', '+repage', 'crop.jpg'])
if retcode != 0:
print 'error on convert'
else:
retcode = subprocess.call(['compare', '-metric', 'PSNR',
'reference.jpg', 'crop.jpg', 'crop.jpg'])
print retcode
|
Running external subprocesses and reading return code
|
I'm creating a python script to sort a lot of images (game screenshots).
I found a way to do that in imagemagick : I know that, if a specific square of the image is the same as the reference crop, then the image is of category one. If not, I check for another crop and another category, and if that doesn't fit either, I put the image in category three.
I found how to do that in Imagemagick :
convert file.jpg -crop 80x10+90+980 +repage crop.jpg
compare -metric PSNR reference.jpg crop.jpg crop.jpg
(I cut a piece of the image, then compare that piece to "reference.jpg")
How do I call that from the script, and do an if based on what convert returns (it's a number) ?
|
[
"import subprocess\n\nretcode = subprocess.call(['convert', 'file.jpg', '-crop', \n '80x10+90+980', '+repage', 'crop.jpg'])\nif retcode != 0:\n print 'error on convert'\nelse:\n retcode = subprocess.call(['compare', '-metric', 'PSNR', \n 'reference.jpg', 'crop.jpg', 'crop.jpg'])\n print retcode\n\n"
] |
[
4
] |
[] |
[] |
[
"popen",
"process",
"python",
"return",
"subprocess"
] |
stackoverflow_0002163579_popen_process_python_return_subprocess.txt
|
Q:
How can I run a loop against 2 random elements from a list at a time?
Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string?
What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for them to not be chosen?
A:
you need to look into random module. It has for example a random.choice function that lets you select a random element from a sequence or a random.sample that selects given number of samples, it's easy to account for different weights too.
A:
explain better your problem, what operations and what elements you're focusing?
regarding the problem with the elements beeing chosen more often, give each string an "chance multiplier", each comparison you multiply a number between 1 and 10 and the chance multiplyer of the string, if the result is higher than X (say... 5), so it select the string, if not, it searches for another string. this way, strings with higher multipliers will have more chance to be selected
|
How can I run a loop against 2 random elements from a list at a time?
|
Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string?
What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for them to not be chosen?
|
[
"you need to look into random module. It has for example a random.choice function that lets you select a random element from a sequence or a random.sample that selects given number of samples, it's easy to account for different weights too.\n",
"explain better your problem, what operations and what elements you're focusing?\nregarding the problem with the elements beeing chosen more often, give each string an \"chance multiplier\", each comparison you multiply a number between 1 and 10 and the chance multiplyer of the string, if the result is higher than X (say... 5), so it select the string, if not, it searches for another string. this way, strings with higher multipliers will have more chance to be selected\n"
] |
[
4,
0
] |
[] |
[] |
[
"probability",
"python"
] |
stackoverflow_0002163765_probability_python.txt
|
Q:
Check if a file is setuid root in Python
I'm trying to check if a file has the setuid bit in Python.
The stat doc mentions a S_ISUID function but it only works with os.chmod(), not to actually read the setuid bit. It also lists S_IMODE, but I have no idea how to interpret it.
How can I easily check if a file as the setuid root bit set?
A:
stat.S_ISUID is the mode bit for 'setuid'. You compare the stat result's mode to see if it contains that bit:
>>> ping = os.stat('/bin/ping')
>>> ping.st_mode & stat.S_ISUID
2048
>>> echo = os.stat('/bin/echo')
>>> echo.st_mode & stat.S_ISUID
0
|
Check if a file is setuid root in Python
|
I'm trying to check if a file has the setuid bit in Python.
The stat doc mentions a S_ISUID function but it only works with os.chmod(), not to actually read the setuid bit. It also lists S_IMODE, but I have no idea how to interpret it.
How can I easily check if a file as the setuid root bit set?
|
[
"stat.S_ISUID is the mode bit for 'setuid'. You compare the stat result's mode to see if it contains that bit:\n>>> ping = os.stat('/bin/ping')\n>>> ping.st_mode & stat.S_ISUID\n2048\n>>> echo = os.stat('/bin/echo')\n>>> echo.st_mode & stat.S_ISUID\n0\n\n"
] |
[
7
] |
[] |
[] |
[
"file",
"python",
"setuid",
"stat"
] |
stackoverflow_0002163800_file_python_setuid_stat.txt
|
Q:
Can a Python package depend on a specific version control revision of another Python package?
Some useful Python packages are broken on pypi, and the only acceptable version is a particular revision in a revision control system. Can that be expressed in setup.py e.g
requires = 'svn://example.org/useful.package/trunk@1234' ?
A:
You need to do two things. First, require the exact version you want, e.g.:
install_requires = "useful.package==1.9dev-r1234"
and then include a dependency_links setting specifying where to find it:
dependency_links = ["svn://example.org/useful.package/trunk@1234#egg=useful.package-1.9dev-r1234"]
Note that the version #egg= part of the dependency_links URL must exactly match what you specified in install_requires; this is what links the two pieces together.
What happens is that setuptools sees the #egg tag on the link and saves the URL as an available download URL for that precise version of the package. Then, when it tries to resolve that requirement later, it should download that precise SVN URL.
(Note, however, that for this to really work, the targeted SVN revision has to actually build an egg with that name and version. Otherwise, your dependency will fail at runtime! So, this really only works if the package you're depending on uses SVN revision tags in their default build version numbers.)
A:
If you really require an obscure version of another package, and there's no way to make do with other versions, you might want to simply distribute that version of the package with your own. If necessary put it in your own namespace to ensure that your version is the one that is used.
A:
I haven't figured out how to reference this from setup.py but pip can check out specific revisions of Python packages with a simple requirements file. With a requirements file called requires.txt, pip install -r requires.txt will install all the packages listed in that file (and their dependencies).
Here is part of my requirements file. The lines starting with -e check out specific revisions of packages from version control (git, svn, or mercurial), including my project, and install them in an editable form. pip freeze lists all installed packages in this format.
requires.txt:
-e hg+file:///home/me/my-private-project#egg=myproject
-e hg+http://bitbucket.org/ianb/webob@tip#egg=WebOb
-e svn+http://svn.sqlalchemy.org/sqlalchemy/trunk@6638#egg=SQLAlchemy
-e svn+http://svn.zope.org/repos/main/z3c.saconfig/trunk@106508#egg=z3c.saconfig
## The following requirements were added by pip --freeze:
APScheduler==1.01
simplejson==2.0.9
... (many more)
A:
You can release packages of specific versions, but you have to distribute them together. There is no way to automatically download them with standard Python.
However, you can use Buildout and create a buildout.cfg that makes it possible to replicate the environment. It can check out and install specific revisions if you use extensions like mr.developer.
http://pypi.python.org/pypi/zc.buildout
http://pypi.python.org/pypi/mr.developer
|
Can a Python package depend on a specific version control revision of another Python package?
|
Some useful Python packages are broken on pypi, and the only acceptable version is a particular revision in a revision control system. Can that be expressed in setup.py e.g
requires = 'svn://example.org/useful.package/trunk@1234' ?
|
[
"You need to do two things. First, require the exact version you want, e.g.:\ninstall_requires = \"useful.package==1.9dev-r1234\"\n\nand then include a dependency_links setting specifying where to find it:\ndependency_links = [\"svn://example.org/useful.package/trunk@1234#egg=useful.package-1.9dev-r1234\"]\n\nNote that the version #egg= part of the dependency_links URL must exactly match what you specified in install_requires; this is what links the two pieces together.\nWhat happens is that setuptools sees the #egg tag on the link and saves the URL as an available download URL for that precise version of the package. Then, when it tries to resolve that requirement later, it should download that precise SVN URL.\n(Note, however, that for this to really work, the targeted SVN revision has to actually build an egg with that name and version. Otherwise, your dependency will fail at runtime! So, this really only works if the package you're depending on uses SVN revision tags in their default build version numbers.)\n",
"If you really require an obscure version of another package, and there's no way to make do with other versions, you might want to simply distribute that version of the package with your own. If necessary put it in your own namespace to ensure that your version is the one that is used.\n",
"I haven't figured out how to reference this from setup.py but pip can check out specific revisions of Python packages with a simple requirements file. With a requirements file called requires.txt, pip install -r requires.txt will install all the packages listed in that file (and their dependencies).\nHere is part of my requirements file. The lines starting with -e check out specific revisions of packages from version control (git, svn, or mercurial), including my project, and install them in an editable form. pip freeze lists all installed packages in this format.\nrequires.txt:\n-e hg+file:///home/me/my-private-project#egg=myproject\n-e hg+http://bitbucket.org/ianb/webob@tip#egg=WebOb\n-e svn+http://svn.sqlalchemy.org/sqlalchemy/trunk@6638#egg=SQLAlchemy\n-e svn+http://svn.zope.org/repos/main/z3c.saconfig/trunk@106508#egg=z3c.saconfig\n## The following requirements were added by pip --freeze:\nAPScheduler==1.01\nsimplejson==2.0.9\n... (many more)\n\n",
"You can release packages of specific versions, but you have to distribute them together. There is no way to automatically download them with standard Python.\nHowever, you can use Buildout and create a buildout.cfg that makes it possible to replicate the environment. It can check out and install specific revisions if you use extensions like mr.developer.\nhttp://pypi.python.org/pypi/zc.buildout\nhttp://pypi.python.org/pypi/mr.developer\n"
] |
[
12,
2,
2,
1
] |
[] |
[] |
[
"distutils",
"easy_install",
"pip",
"python",
"setuptools"
] |
stackoverflow_0002087492_distutils_easy_install_pip_python_setuptools.txt
|
Q:
m2crypto custom certificate verification
I need to build an encrypted connection between two peers, and I need to authenticate both.
Both peers already share a fingerprint (SHA256 hash) of the other peer public key.
I'm not using X509 or OpenPGP keys/certs as they are too big and bulky for my needs and they don't fit in the security model.
I'm trying to build a connection with M2Crypto (nice library) by abusing its x509 model:
given the rsa private key, create a selfsigned almost-empty cert.
connect to the other peer offering my cert
verify the other peer cert public key fingerprint;
Is the following code secure? is it correct? is there a way do do it better (maybe with other libraries)?
My doubts are about OpenSSL not actually using the certificate public key for authentication as I'm not requesting any verification of the certificates.
I just need to use encrypted streams authed by der-encoded rsa keys, any Free Software solution for python is welcome. I'd like M2Crypto more because I know it better and have already some code using it in the same project.
Here is my code (just the client peer, server should be similar):
other_fingerprints = [] #list of fingerprints, (binary data)
mysocket = ... #any socket object
CERTFILE, KEYFILE = "testcert","testkey" # private key wrapped in the cert
from M2Crypto import *
ctx = SSL.Context('sslv3')
ctx.set_verify(SSL.verify_none, depth=1)
ctx.load_cert(CERTFILE, KEYFILE)
c = SSL.Connection(ctx, mysocket)
c.connect_ssl()
peercert = c.get_peer_cert()
keyobj = peercert.get_pubkey()
keydata = keyobj.as_der()
md = EVP.MessageDigest('sha256')
md.update(keydata)
h = md.digest()
if h not in other_fingerprints:
raise(IOError) #other party not auth'ed
# from now on the connection is secure, right?
c.send("Hello secret world!")
print c.recv(4096)
c.close()
Thank you all in advance for your answers and advice.
A:
It seems your approach should work, but there is already a builtin fingerprint checker you might be able to use. See here: What to put for a commonName when making an OpenSSL key?
|
m2crypto custom certificate verification
|
I need to build an encrypted connection between two peers, and I need to authenticate both.
Both peers already share a fingerprint (SHA256 hash) of the other peer public key.
I'm not using X509 or OpenPGP keys/certs as they are too big and bulky for my needs and they don't fit in the security model.
I'm trying to build a connection with M2Crypto (nice library) by abusing its x509 model:
given the rsa private key, create a selfsigned almost-empty cert.
connect to the other peer offering my cert
verify the other peer cert public key fingerprint;
Is the following code secure? is it correct? is there a way do do it better (maybe with other libraries)?
My doubts are about OpenSSL not actually using the certificate public key for authentication as I'm not requesting any verification of the certificates.
I just need to use encrypted streams authed by der-encoded rsa keys, any Free Software solution for python is welcome. I'd like M2Crypto more because I know it better and have already some code using it in the same project.
Here is my code (just the client peer, server should be similar):
other_fingerprints = [] #list of fingerprints, (binary data)
mysocket = ... #any socket object
CERTFILE, KEYFILE = "testcert","testkey" # private key wrapped in the cert
from M2Crypto import *
ctx = SSL.Context('sslv3')
ctx.set_verify(SSL.verify_none, depth=1)
ctx.load_cert(CERTFILE, KEYFILE)
c = SSL.Connection(ctx, mysocket)
c.connect_ssl()
peercert = c.get_peer_cert()
keyobj = peercert.get_pubkey()
keydata = keyobj.as_der()
md = EVP.MessageDigest('sha256')
md.update(keydata)
h = md.digest()
if h not in other_fingerprints:
raise(IOError) #other party not auth'ed
# from now on the connection is secure, right?
c.send("Hello secret world!")
print c.recv(4096)
c.close()
Thank you all in advance for your answers and advice.
|
[
"It seems your approach should work, but there is already a builtin fingerprint checker you might be able to use. See here: What to put for a commonName when making an OpenSSL key?\n"
] |
[
0
] |
[
"The answer is in the question: use proper x509 certificates, and validate/verify symmetrically. \"Is this secure?\" - no, because you have to ask.\nYour solution may work, but the fact you are asking for advice on \"Is this secure?\" tells me that you should probably use stuff straight from the box.\n"
] |
[
-2
] |
[
"m2crypto",
"python",
"x509"
] |
stackoverflow_0002160158_m2crypto_python_x509.txt
|
Q:
force unpacking of certain egg directories
I have an egg distribution of a PyQt application which i build myself, and it contains sphinx generated documentation. When i call the help file from the application it opens the sphinx index.html in a QtWebKit.QWebView window. Apparently, only the index.html file is extracted from the egg into the OS's egg-directory (e.g. [..]\Application Data\Python-Eggs\ under Windows).
This results in broken css, broken images, and broken links, because these other files don't seem to get unpacked; they are present in the egg file, but not in the egg-directory.
Am i missing something here? Is there a way to force unpacking all html, css, image file immediately?
A:
I see that you've already found another way to do it, but for future reference, here's the non-workaround way to do it automatically, from the documentation at http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction [emphasis added]:
If you are using tools that expect your resources to be "real" files, or your project includes non-extension native libraries or other files that your C extensions expect to be able to access, you may need to list those files in the eager_resources argument to setup(), so that the files will be extracted together
So, in this case, what you want to do is have:
eager_resources=['doc/sphinx/build/html', 'doc/sphinx/build/html/index.html']
in your setup.py, which will cause the 'html' directory to be recursively extracted when you ask for the index.html (assuming that 'doc' in your example is a top-level package).
(You can find out more about the eager_resources keyword in the docs at http://peak.telecommunity.com/DevCenter/setuptools#new-and-changed-setup-keywords)
A:
def get_help_url(self):
from pkg_resources import resource_filename
from doc import sphinx
import os
from PyQt4.QtCore import QUrl
html_path = resource_filename(sphinx.__name__, os.path.join('build', 'html'))
return QUrl(os.path.join(html_path, 'index.html'))
instead of
html = resource_filename(sphinx.__name__, os.path.join('build', 'html', 'index.html'))
return QUrl(html)
did the trick
A:
Probable cause: not all the files are included in the egg in the first place.
Check this by unzipping the .egg (you might need to rename it to a .zip file for that on windows). Check if all the contents are there.
Look at how you made the egg. Do you use a MANIFEST.in file to tell setuptools which files to include? If not, you're probably trusting on setuptools' automatic inclusion of subversion files. All subversion'ed files automatically end up in the egg, python files do to, the rest does not.
The sphinx documentation is probably generated, so it is not in subversion, so it doesn't get included automatically.
Two solutions:
Use a MANIFEST.in file to manually specify (wildcards do work) all the files that should be included. Fail-safe as long as you're complete.
Or specify the html files as package_data, see How does setuptools decide which files to keep for sdist/bdist?
|
force unpacking of certain egg directories
|
I have an egg distribution of a PyQt application which i build myself, and it contains sphinx generated documentation. When i call the help file from the application it opens the sphinx index.html in a QtWebKit.QWebView window. Apparently, only the index.html file is extracted from the egg into the OS's egg-directory (e.g. [..]\Application Data\Python-Eggs\ under Windows).
This results in broken css, broken images, and broken links, because these other files don't seem to get unpacked; they are present in the egg file, but not in the egg-directory.
Am i missing something here? Is there a way to force unpacking all html, css, image file immediately?
|
[
"I see that you've already found another way to do it, but for future reference, here's the non-workaround way to do it automatically, from the documentation at http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction [emphasis added]:\n\nIf you are using tools that expect your resources to be \"real\" files, or your project includes non-extension native libraries or other files that your C extensions expect to be able to access, you may need to list those files in the eager_resources argument to setup(), so that the files will be extracted together\n\nSo, in this case, what you want to do is have:\neager_resources=['doc/sphinx/build/html', 'doc/sphinx/build/html/index.html']\n\nin your setup.py, which will cause the 'html' directory to be recursively extracted when you ask for the index.html (assuming that 'doc' in your example is a top-level package).\n(You can find out more about the eager_resources keyword in the docs at http://peak.telecommunity.com/DevCenter/setuptools#new-and-changed-setup-keywords)\n",
"def get_help_url(self):\n from pkg_resources import resource_filename\n from doc import sphinx\n import os\n from PyQt4.QtCore import QUrl\n html_path = resource_filename(sphinx.__name__, os.path.join('build', 'html'))\n\n return QUrl(os.path.join(html_path, 'index.html'))\n\ninstead of \n html = resource_filename(sphinx.__name__, os.path.join('build', 'html', 'index.html'))\n\n return QUrl(html)\n\ndid the trick\n",
"Probable cause: not all the files are included in the egg in the first place.\n\nCheck this by unzipping the .egg (you might need to rename it to a .zip file for that on windows). Check if all the contents are there.\nLook at how you made the egg. Do you use a MANIFEST.in file to tell setuptools which files to include? If not, you're probably trusting on setuptools' automatic inclusion of subversion files. All subversion'ed files automatically end up in the egg, python files do to, the rest does not.\nThe sphinx documentation is probably generated, so it is not in subversion, so it doesn't get included automatically.\n\nTwo solutions:\n\nUse a MANIFEST.in file to manually specify (wildcards do work) all the files that should be included. Fail-safe as long as you're complete.\nOr specify the html files as package_data, see How does setuptools decide which files to keep for sdist/bdist?\n\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"egg",
"python",
"python_sphinx",
"setuptools"
] |
stackoverflow_0001762306_egg_python_python_sphinx_setuptools.txt
|
Q:
How can I manually register distributions with pkg_resources?
I'm trying to get a package installed on Google App Engine. The package relies rather extensively on pkg_resources, but there's no way to run setup.py on App Engine.
There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of pkg_resources installed and working as well.
The only problem is getting the package actually registered with pkg_resources so when it calls iter_entry_points it can find the appropriate plugins.
What methods do I need to call to register modules on sys.path with all the appropriate metadata, and how do I figure out what that metadata needs to be?
A:
Yes, for setuptools-based libraries you'll need to deploy the library's "Egg" metadata along with it. The easiest way I've found is to deploy a whole virtualenv environment containing your project and the required libraries.
I did this process manually and added this code to main.py to initialize the site-packages folder in a way that pkg_resources will work:
import site
site.addsitedir('lib/python2.5/site-packages')
However, you could try appengine-monkey which automates most of this for you.
A:
On your local development system, run python setup.py bdist_egg, which will create a Zip archive with the necessary metadata included. Add it to your sys.path, and it should work properly.
A:
Create a setup.py for the package just as you would normally, and then use "setup.py sdist --formats=zip" to build your source zip. The built source zip will include an .egg-info metadata directory, which will then be findable by pkg_resources. Alternately, you can use bdist_egg for all your packages.
|
How can I manually register distributions with pkg_resources?
|
I'm trying to get a package installed on Google App Engine. The package relies rather extensively on pkg_resources, but there's no way to run setup.py on App Engine.
There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of pkg_resources installed and working as well.
The only problem is getting the package actually registered with pkg_resources so when it calls iter_entry_points it can find the appropriate plugins.
What methods do I need to call to register modules on sys.path with all the appropriate metadata, and how do I figure out what that metadata needs to be?
|
[
"Yes, for setuptools-based libraries you'll need to deploy the library's \"Egg\" metadata along with it. The easiest way I've found is to deploy a whole virtualenv environment containing your project and the required libraries.\nI did this process manually and added this code to main.py to initialize the site-packages folder in a way that pkg_resources will work:\nimport site\nsite.addsitedir('lib/python2.5/site-packages')\n\nHowever, you could try appengine-monkey which automates most of this for you.\n",
"On your local development system, run python setup.py bdist_egg, which will create a Zip archive with the necessary metadata included. Add it to your sys.path, and it should work properly.\n",
"Create a setup.py for the package just as you would normally, and then use \"setup.py sdist --formats=zip\" to build your source zip. The built source zip will include an .egg-info metadata directory, which will then be findable by pkg_resources. Alternately, you can use bdist_egg for all your packages.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"google_app_engine",
"pkg_resources",
"python",
"setuptools"
] |
stackoverflow_0000599205_google_app_engine_pkg_resources_python_setuptools.txt
|
Q:
How can I deal with python eggs for multiple platforms in one location?
We have a common python installation for all of our systems in order to ensure every system has the same python installation and to ease configuration issues. This installation is located on a shared drive. We also have multiple platforms that share this installation. We get around conflicting platform-specific files by setting the --exec-prefix configure option when compiling python.
My issue is that I now want to install an egg using easy_install (or otherwise) that is platform-dependent. easy_install puts the egg in the site-packages directory of the platform-independent part of the install. The name of the egg has the platform in it so there should be no conflict. But python will only load the first one it finds. (So, on Solaris it might try to load the Linux egg). Modifying the easy-install.pth file can change which one it finds, but that's pretty useless.
I can move the .egg files into a platform-depended packages directory and then use pkg_resources.require() to load them (or manually adjust the path). But it seems as though I shouldn't have to since the platform is in the name of the egg.
Is there any more generic way I can ensure that python will load the egg for the correct platform?
A:
Try virtualenv ... http://pypi.python.org/pypi/virtualenv ... helps you create isolated environment with it's own python interpreter + site_packages folder. Thus you never have any conflicts with packages installed in say local path.
A:
What I ended up going with was manually moving the platform-dependent egg to the platform-specific site-packages directory (as specified at http://docs.python.org/install/index.html). Then I made another easy-install.pth in that same directory, listing the eggs to be installed.
This would be much more convenient if easy_install were to honour the exec_prefix and put platform-dependent eggs in the correct "non-pure module distribution" location. Perhaps I will request this from the easy_install folks.
A:
Python has enough hooks to make this possible but it is probably not wise. If you really want to implement this, look at PEP 302 and start hacking on the easy_install or distribute source code. As you know, there's not really any logic in easy-install.pth.
You would probably be much better off simply keeping track of which Python packages you want installed. You could for example write your own Python package that just depends on the desired set.
A:
Use "easy_install -m" to install all the platform-specific packages, so that there is no default version on sys.path. That way, version resolution takes place at runtime, and platform information will be taken into consideration.
|
How can I deal with python eggs for multiple platforms in one location?
|
We have a common python installation for all of our systems in order to ensure every system has the same python installation and to ease configuration issues. This installation is located on a shared drive. We also have multiple platforms that share this installation. We get around conflicting platform-specific files by setting the --exec-prefix configure option when compiling python.
My issue is that I now want to install an egg using easy_install (or otherwise) that is platform-dependent. easy_install puts the egg in the site-packages directory of the platform-independent part of the install. The name of the egg has the platform in it so there should be no conflict. But python will only load the first one it finds. (So, on Solaris it might try to load the Linux egg). Modifying the easy-install.pth file can change which one it finds, but that's pretty useless.
I can move the .egg files into a platform-depended packages directory and then use pkg_resources.require() to load them (or manually adjust the path). But it seems as though I shouldn't have to since the platform is in the name of the egg.
Is there any more generic way I can ensure that python will load the egg for the correct platform?
|
[
"Try virtualenv ... http://pypi.python.org/pypi/virtualenv ... helps you create isolated environment with it's own python interpreter + site_packages folder. Thus you never have any conflicts with packages installed in say local path.\n",
"What I ended up going with was manually moving the platform-dependent egg to the platform-specific site-packages directory (as specified at http://docs.python.org/install/index.html). Then I made another easy-install.pth in that same directory, listing the eggs to be installed.\nThis would be much more convenient if easy_install were to honour the exec_prefix and put platform-dependent eggs in the correct \"non-pure module distribution\" location. Perhaps I will request this from the easy_install folks.\n",
"Python has enough hooks to make this possible but it is probably not wise. If you really want to implement this, look at PEP 302 and start hacking on the easy_install or distribute source code. As you know, there's not really any logic in easy-install.pth.\nYou would probably be much better off simply keeping track of which Python packages you want installed. You could for example write your own Python package that just depends on the desired set.\n",
"Use \"easy_install -m\" to install all the platform-specific packages, so that there is no default version on sys.path. That way, version resolution takes place at runtime, and platform information will be taken into consideration.\n"
] |
[
2,
2,
1,
0
] |
[] |
[] |
[
"easy_install",
"pkg_resources",
"python"
] |
stackoverflow_0001903653_easy_install_pkg_resources_python.txt
|
Q:
easy_install -f vs easy_install -i
This is related to this question I asked a while back.
The end game is I want to be able to install my package "identity.model" and all dependencies. like so...
$ easy_install -f http://eggs.sadphaeton.com identity.model
Searching for identity.model
Reading http://eggs.sadphaeton.com
Reading http://pypi.python.org/simple/identity.model/
Couldn't find index page for 'identity.model' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for identity.model
error: Could not find suitable distribution for Requirement.parse('identity.model')
for whatever reason running this easy_install hits the home page which I laid out according to this information
My index.html
<html>
<head>
<title>SadPhaeton Egg Repository</title>
</head>
<body>
<a rel="homepage" href="AlchemyExtra">AlchemyExtra</a>
<a rel="homepage" href="identity.model">identity.model</a>
<a rel="homepage" href="repoze.what.plugins.config">repoze.what.plugins.config</a>
</body>
</html>
if I run ...
$ easy_install -i http://eggs.sadphaeton.com identity.model
it does find my package and the repoze.what.plugins.config I put up there as well since it's a dependency. however then when it goes to fetch tw.forms(external dependency hosted on pypi) It ends with a failure as it only searched http://eggs.sadphaeton.com
Obviously I've misunderstood the "spec". Anyone have any idea what the trick is?
A:
-f will take the url you give it, and look there for packages, as well as on PyPI. An example of such a page is http://dist.plone.org/release/3.3.1/ As you see, this is a list of distribution files.
With -i you define the main index page. It defaults to http://pypi.python.org/simple/ As you see, the index page is an index of packages, not of distribution files.
So in your case easy_install -i http://eggs.sadphaeton.com identity.model should work to download identity.model. And it did for me, like twice in the middle, but not the first time nor the second time. I don't know if you maybe are trying different formats? But in any case, it will then fail on tw.forms, as it's not on your index page.
So the solution should be to make a page like http://dist.plone.org/release/3.3.1/ with your eggs on it. I don't know how exact the format has to be, but I think it's quite flexible.
Update:
Here is a step for step solution:
Put all your distributions in a directory.
cd to that directory.
Type python -c "from SimpleHTTPServer import test; test()"
Now type easy_install -f http://localhost:8080/ <modulename>
It will install the module.
A:
Well looks like the trick is in having the rel="download" links on the index.html of the root.
<html>
<head>
<title>SadPhaeton Egg Repository</title>
</head>
<body>
<a rel="homepage" href="AlchemyExtra">AlchemyExtra</a> <a rel="download" href="AlchemyExtra/AlchemyExtra-0.0dev-py2.6.egg">download</a><br>
<a rel="homepage" href="identity.model">identity.model</a> <a rel="download" href="identity.model/identity.model-0.0dev-py2.6.egg">download</a><br>
<a rel="homepage" href="repoze.what.plugins.config">repoze.what.plugins.config</a> <a rel="download" href="repoze.what.plugins.config/repoze.what.plugins.config-0.0.0-py2.6.egg">download</a><br>
</body>
</html>
that solves my immediate issue, though it would be nice if there were more details on this in the spec. I was expecting based on what I read that easy_install would consult the homepage for download link but it doesn't seem to want to do that for me.
now to somehow automate this because doing this crap manually is a PITA.
A:
The problem is you're trying to mix -i and -f modes of making your page; you need to pick one or the other, as the rel="" stuff only works with -i.
If you want to use -f mode, then you just need a webserver directory with the eggs in it. If you want to use -i, then you must have a subdirectory for each project with an index.html in it, and it's those index.html files that would contain the rel="homepage" stuff.
|
easy_install -f vs easy_install -i
|
This is related to this question I asked a while back.
The end game is I want to be able to install my package "identity.model" and all dependencies. like so...
$ easy_install -f http://eggs.sadphaeton.com identity.model
Searching for identity.model
Reading http://eggs.sadphaeton.com
Reading http://pypi.python.org/simple/identity.model/
Couldn't find index page for 'identity.model' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for identity.model
error: Could not find suitable distribution for Requirement.parse('identity.model')
for whatever reason running this easy_install hits the home page which I laid out according to this information
My index.html
<html>
<head>
<title>SadPhaeton Egg Repository</title>
</head>
<body>
<a rel="homepage" href="AlchemyExtra">AlchemyExtra</a>
<a rel="homepage" href="identity.model">identity.model</a>
<a rel="homepage" href="repoze.what.plugins.config">repoze.what.plugins.config</a>
</body>
</html>
if I run ...
$ easy_install -i http://eggs.sadphaeton.com identity.model
it does find my package and the repoze.what.plugins.config I put up there as well since it's a dependency. however then when it goes to fetch tw.forms(external dependency hosted on pypi) It ends with a failure as it only searched http://eggs.sadphaeton.com
Obviously I've misunderstood the "spec". Anyone have any idea what the trick is?
|
[
"-f will take the url you give it, and look there for packages, as well as on PyPI. An example of such a page is http://dist.plone.org/release/3.3.1/ As you see, this is a list of distribution files.\nWith -i you define the main index page. It defaults to http://pypi.python.org/simple/ As you see, the index page is an index of packages, not of distribution files.\nSo in your case easy_install -i http://eggs.sadphaeton.com identity.model should work to download identity.model. And it did for me, like twice in the middle, but not the first time nor the second time. I don't know if you maybe are trying different formats? But in any case, it will then fail on tw.forms, as it's not on your index page.\nSo the solution should be to make a page like http://dist.plone.org/release/3.3.1/ with your eggs on it. I don't know how exact the format has to be, but I think it's quite flexible.\nUpdate:\nHere is a step for step solution:\n\nPut all your distributions in a directory.\ncd to that directory.\nType python -c \"from SimpleHTTPServer import test; test()\"\nNow type easy_install -f http://localhost:8080/ <modulename>\n\nIt will install the module.\n",
"Well looks like the trick is in having the rel=\"download\" links on the index.html of the root.\n<html>\n<head>\n <title>SadPhaeton Egg Repository</title>\n</head>\n<body>\n <a rel=\"homepage\" href=\"AlchemyExtra\">AlchemyExtra</a> <a rel=\"download\" href=\"AlchemyExtra/AlchemyExtra-0.0dev-py2.6.egg\">download</a><br>\n <a rel=\"homepage\" href=\"identity.model\">identity.model</a> <a rel=\"download\" href=\"identity.model/identity.model-0.0dev-py2.6.egg\">download</a><br>\n\n <a rel=\"homepage\" href=\"repoze.what.plugins.config\">repoze.what.plugins.config</a> <a rel=\"download\" href=\"repoze.what.plugins.config/repoze.what.plugins.config-0.0.0-py2.6.egg\">download</a><br>\n\n</body>\n</html>\n\nthat solves my immediate issue, though it would be nice if there were more details on this in the spec. I was expecting based on what I read that easy_install would consult the homepage for download link but it doesn't seem to want to do that for me.\nnow to somehow automate this because doing this crap manually is a PITA.\n",
"The problem is you're trying to mix -i and -f modes of making your page; you need to pick one or the other, as the rel=\"\" stuff only works with -i.\nIf you want to use -f mode, then you just need a webserver directory with the eggs in it. If you want to use -i, then you must have a subdirectory for each project with an index.html in it, and it's those index.html files that would contain the rel=\"homepage\" stuff.\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"python",
"setuptools"
] |
stackoverflow_0001585077_python_setuptools.txt
|
Q:
Can I write browser plugins with Python?
I'm thinking about writing a browser plugin, but I don't know any C.
Can I write browser plugins with Java or Python?
I was thinking... All those websites store cookies on my browser to identify me.
If I wrote a plugin that would supply a browser GUID in the http headers, webservers could identify the browser.
I think that would rule out the need for 99% of all the cookies, pretending for a moment that all users and servers use it.
A:
You can certainly write an ActiveX plugin for IE in Python using the win32com interfaces. But you'd have to install Python and pywin32 along with your plugin for it to work, so it'd be pretty bulky. I don't think it's going to be popular to install all that just to get a GUID.
(Actually most people specifically don't want a GUID. Is that really your only aim? If you're thinking about single-sign-on options, look at systems like OpenID as used on SO... this gives the user much greater control.)
|
Can I write browser plugins with Python?
|
I'm thinking about writing a browser plugin, but I don't know any C.
Can I write browser plugins with Java or Python?
I was thinking... All those websites store cookies on my browser to identify me.
If I wrote a plugin that would supply a browser GUID in the http headers, webservers could identify the browser.
I think that would rule out the need for 99% of all the cookies, pretending for a moment that all users and servers use it.
|
[
"You can certainly write an ActiveX plugin for IE in Python using the win32com interfaces. But you'd have to install Python and pywin32 along with your plugin for it to work, so it'd be pretty bulky. I don't think it's going to be popular to install all that just to get a GUID.\n(Actually most people specifically don't want a GUID. Is that really your only aim? If you're thinking about single-sign-on options, look at systems like OpenID as used on SO... this gives the user much greater control.)\n"
] |
[
1
] |
[] |
[] |
[
"browser_plugin",
"java",
"python"
] |
stackoverflow_0002163816_browser_plugin_java_python.txt
|
Q:
Is it not possible to define multiple constructors in Python?
Possible Duplicate:
What is a clean, pythonic way to have multiple constructors in Python?
Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it?
For example, let's say you wanted to define a class City.
I'd like to be able to say someCity = City() or someCity = City("Berlin"), where the first just gives a default name value, and the second defines it.
A:
Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.
def __init__(self, city="Berlin"):
self.city = city
A:
If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance-based approach mentioned in another answer, and instead use keyword arguments.
If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:
class C(object):
def __init__(self, fd):
# Assume fd is a file-like object.
self.fd = fd
@classmethod
def from_filename(cls, name):
return cls(open(name, 'rb'))
# Now you can do:
c = C(fd)
# or:
c = C.from_filename('a filename')
Notice all those class methods still go through the same __init__, but using class methods can be much more convenient than having to remember what combinations of keyword arguments to __init__ work.
isinstance is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file), because there are many file-like objects that do not subclass file (like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.
A:
For the example you gave, use default values:
class City:
def __init__(self, name="Default City Name"):
...
...
In general, you have two options:
Do if-elif blocks based on the type:
def __init__(self, name):
if isinstance(name, str):
# todo
elif isinstance(name, City):
# todo
# todo
Use duck typing - that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.
A:
The answer by Jack M. is correct. Do it this way:
>>> class City:
... def __init__(self, city=None):
... self.city = city
... def __repr__(self):
... if self.city: return self.city
... return ''
...
>>> c = City('Berlin')
>>> print c
Berlin
>>> c = City()
>>> print c
>>>
A:
The easiest way is through keyword arguments:
class City():
def __init__(self, city=None):
pass
someCity = City(city="Berlin")
This is pretty basic stuff. Maybe look at the Python documentation?
|
Is it not possible to define multiple constructors in Python?
|
Possible Duplicate:
What is a clean, pythonic way to have multiple constructors in Python?
Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it?
For example, let's say you wanted to define a class City.
I'd like to be able to say someCity = City() or someCity = City("Berlin"), where the first just gives a default name value, and the second defines it.
|
[
"Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.\ndef __init__(self, city=\"Berlin\"):\n self.city = city\n\n",
"If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance-based approach mentioned in another answer, and instead use keyword arguments.\nIf using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:\nclass C(object):\n\n def __init__(self, fd):\n # Assume fd is a file-like object.\n self.fd = fd\n\n @classmethod\n def from_filename(cls, name):\n return cls(open(name, 'rb'))\n\n# Now you can do:\nc = C(fd)\n# or:\nc = C.from_filename('a filename')\n\nNotice all those class methods still go through the same __init__, but using class methods can be much more convenient than having to remember what combinations of keyword arguments to __init__ work.\nisinstance is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file), because there are many file-like objects that do not subclass file (like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.\n",
"For the example you gave, use default values:\nclass City:\n def __init__(self, name=\"Default City Name\"):\n ...\n ...\n\nIn general, you have two options:\n\nDo if-elif blocks based on the type:\ndef __init__(self, name):\n if isinstance(name, str):\n # todo \n elif isinstance(name, City):\n # todo \n # todo \n\n\nUse duck typing - that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.\n\n\n",
"The answer by Jack M. is correct. Do it this way:\n>>> class City:\n... def __init__(self, city=None):\n... self.city = city\n... def __repr__(self):\n... if self.city: return self.city\n... return ''\n...\n>>> c = City('Berlin')\n>>> print c\nBerlin\n>>> c = City()\n>>> print c\n\n>>>\n\n",
"The easiest way is through keyword arguments:\nclass City():\n def __init__(self, city=None):\n pass\n\nsomeCity = City(city=\"Berlin\")\n\nThis is pretty basic stuff. Maybe look at the Python documentation?\n"
] |
[
365,
305,
14,
5,
4
] |
[] |
[] |
[
"constructor",
"python"
] |
stackoverflow_0002164258_constructor_python.txt
|
Q:
Python looping: idiomatically comparing successive items in a list
I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some clever way? Simply looping over the index seems pretty clear, but I wonder if there's a more expressive or concise way to do it.
for revindex in xrange(len(dm_revisions) - 1):
summary = \
svn.diff_summarize(svn_path,
revision1=dm_revisions[revindex],
revision2 = dm_revisions[revindex+1])
A:
This is called a sliding window. There's an example in the itertools documentation that does it. Here's the code:
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
What that, you can say this:
for r1, r2 in window(dm_revisions):
summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)
Of course you only care about the case where n=2, so you can get away with something much simpler:
def adjacent_pairs(seq):
it = iter(seq)
a = it.next()
for b in it:
yield a, b
a = b
for r1, r2 in adjacent_pairs(dm_revisions):
summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)
A:
I'd probably do:
import itertools
for rev1, rev2 in zip(dm_revisions, itertools.islice(dm_revisions, 1, None)):
summary = svn.diff_sumeraize(svn_python, revision1=rev, revision2=rev2)
Something similarly cleverer and not touching the iterators themselves could probably be done using
A:
So many complex solutions posted, why not keep it simple?
myList = range(5)
for idx, item1 in enumerate(myList[:-1]):
item2 = L[idx + 1]
print item1, item2
>>>
0 1
1 2
2 3
3 4
A:
Store the previous value in a variable. Initialize the variable with a value you're not likely to find in the sequence you're handling, so you can know if you're at the first element. Compare the old value to the current value.
|
Python looping: idiomatically comparing successive items in a list
|
I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some clever way? Simply looping over the index seems pretty clear, but I wonder if there's a more expressive or concise way to do it.
for revindex in xrange(len(dm_revisions) - 1):
summary = \
svn.diff_summarize(svn_path,
revision1=dm_revisions[revindex],
revision2 = dm_revisions[revindex+1])
|
[
"This is called a sliding window. There's an example in the itertools documentation that does it. Here's the code:\nfrom itertools import islice\n\ndef window(seq, n=2):\n \"Returns a sliding window (of width n) over data from the iterable\"\n \" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... \"\n it = iter(seq)\n result = tuple(islice(it, n))\n if len(result) == n:\n yield result \n for elem in it:\n result = result[1:] + (elem,)\n yield result\n\nWhat that, you can say this:\nfor r1, r2 in window(dm_revisions):\n summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)\n\nOf course you only care about the case where n=2, so you can get away with something much simpler:\ndef adjacent_pairs(seq):\n it = iter(seq)\n a = it.next()\n for b in it:\n yield a, b\n a = b\n\nfor r1, r2 in adjacent_pairs(dm_revisions):\n summary = svn.diff_summarize(svn_path, revision1=r1, revision2=r2)\n\n",
"I'd probably do:\nimport itertools\nfor rev1, rev2 in zip(dm_revisions, itertools.islice(dm_revisions, 1, None)):\n summary = svn.diff_sumeraize(svn_python, revision1=rev, revision2=rev2)\n\nSomething similarly cleverer and not touching the iterators themselves could probably be done using\n",
"So many complex solutions posted, why not keep it simple?\nmyList = range(5)\n\nfor idx, item1 in enumerate(myList[:-1]):\n item2 = L[idx + 1]\n print item1, item2\n\n>>> \n0 1\n1 2\n2 3\n3 4\n\n",
"Store the previous value in a variable. Initialize the variable with a value you're not likely to find in the sequence you're handling, so you can know if you're at the first element. Compare the old value to the current value.\n"
] |
[
13,
4,
3,
0
] |
[
"Reduce can be used for this purpose, if you take care to leave a copy of the current item in the result of the reducing function.\ndef diff_summarize(revisionList, nextRevision):\n '''helper function (adaptor) for using svn.diff_summarize with reduce'''\n if revisionList:\n # remove the previously tacked on item\n r1 = revisionList.pop()\n revisionList.append(svn.diff_summarize(\n svn_path, revision1=r1, revision2=nextRevision))\n # tack the current item onto the end of the list for use in next iteration\n revisionList.append(nextRevision)\n return revisionList\n\nsummaries = reduce(diff_summarize, dm_revisions, [])\n\nEDIT: Yes, but nobody said the result of the function in reduce has to be scalar. I changed my example to use a list. Basically, the last element is allways the previous revision (except on first pass), with all preceding elements being the results of the svn.diff_summarize call. This way, you get a list of results as your final output...\nEDIT2: Yep, the code really was broken. I have here a workable dummy:\n>>> def compare(lst, nxt):\n... if lst:\n... prev = lst.pop()\n... lst.append((prev, nxt))\n... lst.append(nxt)\n... return lst\n...\n>>> reduce(compare, \"abcdefg\", [])\n[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g'), 'g']\n\nThis was tested in the shell, as you can see. You will want to replace (prev, nxt) in the lst.append call of compare to actually append the summary of the call to svn.diff_summarize.\n>>> help(reduce)\nHelp on built-in function reduce in module __builtin__:\n\nreduce(...)\n reduce(function, sequence[, initial]) -> value\n\n Apply a function of two arguments cumulatively to the items of a sequence,\n from left to right, so as to reduce the sequence to a single value.\n For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n of the sequence in the calculation, and serves as a default when the\n sequence is empty.\n\n"
] |
[
-1
] |
[
"iterator",
"loops",
"python"
] |
stackoverflow_0002152640_iterator_loops_python.txt
|
Q:
Python order of execution
I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.
For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it is implemented before all the ones below it.
Is it the same for Python? Like if I open a file of data, read in the data, close the file, then do other stuff do I know for sure that the file is closed before the lines after I close the file are executed??
The reason I ask is because I'm trying to read in a large file of data (1.6GB) and use this python module specific to the work I do on the data. When I run this module I get this error message:
File "/glast01/software/ScienceTools/ScienceTools-v9r15p2-SL4/sane/v3r18p1/python/GtApp.py", line 57, in run
input, output = self.runWithOutput(print_command)
File "/glast01/software/ScienceTools/ScienceTools-v9r15p2-SL4/sane/v3r18p1/python/GtApp.py", line 77, in runWithOutput
return os.popen4(self.command(print_command))
File "/Home/eud/jmcohen/.local/lib/python2.5/os.py", line 690, in popen4
stdout, stdin = popen2.popen4(cmd, bufsize)
File "/Home/eud/jmcohen/.local/lib/python2.5/popen2.py", line 199, in popen4
inst = Popen4(cmd, bufsize)
File "/Home/eud/jmcohen/.local/lib/python2.5/popen2.py", line 125, in __init__
self.pid = os.fork()
OSError: [Errno 12] Cannot allocate memory
>>>
Exception exceptions.AttributeError: AttributeError("Popen4 instance has no attribute 'pid'",) in <bound method Popen4.__del__ of <popen2.Popen4 instance at 0x9ee6fac>> ignored
I assume it's related to the size of the data I read in (it has 17608310 rows and 22 columns).
I thought perhaps if I closed the file I opened right after I read in the data this would help, but it didn't. This led me to thinking about the order that lines of code are executed in, hence my question.
Thanks
A:
The only thing I can think of that may surprise some people is:
def test():
try:
return True
finally:
return False
print test()
Output:
False
finally clauses really are executed last, even if a return statement precedes them. However, this is not specific to Python.
A:
Execution of C certainly is sequential, for actual statements. There are even rules that define the sequence points, so you can know how individual expressions evaluate.
A:
CPython itself is written in such a way that any effects like those you mention are minimized; code always executes top to bottom barring literal evaluation during compilation, objects are GCed as soon as their refcount hits 0, etc.
A:
Execution in the cpython vm is very linear. I do not think whatever problem you have has to do with order of execution.
One thing you should be careful about in Python but not C: exceptions can be raised everywhere, so just because you see a close() call below the corresponding open() call does not mean that call is actually reached. Use try/finally everywhere (or the with statement in new enough pythons) to make sure opened files are closed (and other kinds of resources that can be freed explicitly are freed).
If your problem is with memory usage, not some other kind of resource, debugging it can be harder. Memory cannot be freed explicitly in python. The cpython vm (which you are most likely using) does release memory as soon as the last reference to it goes away, but sometimes cannot free memory trapped in cycles with objects that have a __del__ method. If you have any __del__ methods of your own or use classes that have them this may be part of your problem.
Your actual question (the memory one, not the order of execution one) is hard to answer without seeing more code, though. It may be something obvious (or there may at least be some obvious way to reduce the amount of memory you need).
A:
"if I open a file of data, read in the data, close the file, then do other stuff do I know for sure that the file is closed before the lines after I close the file are executed??"
Closed yes.
Released from memory. No. No guarantees about when garbage collection will occur.
Further, closing a file says nothing about all the other variables you've created and the other objects you've left laying around attached to those variables.
There's no "order of operations" issue.
I'll bet that you have too many global variables with too many copies of the data.
A:
If the data consists of columns and rows, why not use the built in file iterator to fetch one line at a time?
f = open('file.txt')
first_line = f.next()
A:
popen2.py:
class Popen4(Popen3):
childerr = None
def __init__(self, cmd, bufsize=-1):
_cleanup()
self.cmd = cmd
p2cread, p2cwrite = os.pipe()
c2pread, c2pwrite = os.pipe()
self.pid = os.fork()
if self.pid == 0:
# Child
os.dup2(p2cread, 0)
os.dup2(c2pwrite, 1)
os.dup2(c2pwrite, 2)
self._run_child(cmd)
os.close(p2cread)
self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
os.close(c2pwrite)
self.fromchild = os.fdopen(c2pread, 'r', bufsize)
man 2 fork:
The fork() function may fail if:
[ENOMEM]
Insufficient storage space is available.
os.popen4 eventually calls open2.Popen4.__init__, which must fork in order to create the child process that you try to read from/write to. This underlying call is failing, likely due to resource exhaustion.
You may be using too much memory elsewhere, causing fork to attempt to use more than the RLIMIT_DATA or RLIMIT_RSS limit given to your user. As recommended by Python memory profiler - Stack Overflow, Heapy can help you determine whether this is the case.
|
Python order of execution
|
I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.
For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it is implemented before all the ones below it.
Is it the same for Python? Like if I open a file of data, read in the data, close the file, then do other stuff do I know for sure that the file is closed before the lines after I close the file are executed??
The reason I ask is because I'm trying to read in a large file of data (1.6GB) and use this python module specific to the work I do on the data. When I run this module I get this error message:
File "/glast01/software/ScienceTools/ScienceTools-v9r15p2-SL4/sane/v3r18p1/python/GtApp.py", line 57, in run
input, output = self.runWithOutput(print_command)
File "/glast01/software/ScienceTools/ScienceTools-v9r15p2-SL4/sane/v3r18p1/python/GtApp.py", line 77, in runWithOutput
return os.popen4(self.command(print_command))
File "/Home/eud/jmcohen/.local/lib/python2.5/os.py", line 690, in popen4
stdout, stdin = popen2.popen4(cmd, bufsize)
File "/Home/eud/jmcohen/.local/lib/python2.5/popen2.py", line 199, in popen4
inst = Popen4(cmd, bufsize)
File "/Home/eud/jmcohen/.local/lib/python2.5/popen2.py", line 125, in __init__
self.pid = os.fork()
OSError: [Errno 12] Cannot allocate memory
>>>
Exception exceptions.AttributeError: AttributeError("Popen4 instance has no attribute 'pid'",) in <bound method Popen4.__del__ of <popen2.Popen4 instance at 0x9ee6fac>> ignored
I assume it's related to the size of the data I read in (it has 17608310 rows and 22 columns).
I thought perhaps if I closed the file I opened right after I read in the data this would help, but it didn't. This led me to thinking about the order that lines of code are executed in, hence my question.
Thanks
|
[
"The only thing I can think of that may surprise some people is:\ndef test():\n try:\n return True\n finally:\n return False\n\nprint test()\n\nOutput:\nFalse\n\nfinally clauses really are executed last, even if a return statement precedes them. However, this is not specific to Python.\n",
"Execution of C certainly is sequential, for actual statements. There are even rules that define the sequence points, so you can know how individual expressions evaluate. \n",
"CPython itself is written in such a way that any effects like those you mention are minimized; code always executes top to bottom barring literal evaluation during compilation, objects are GCed as soon as their refcount hits 0, etc.\n",
"Execution in the cpython vm is very linear. I do not think whatever problem you have has to do with order of execution.\nOne thing you should be careful about in Python but not C: exceptions can be raised everywhere, so just because you see a close() call below the corresponding open() call does not mean that call is actually reached. Use try/finally everywhere (or the with statement in new enough pythons) to make sure opened files are closed (and other kinds of resources that can be freed explicitly are freed).\nIf your problem is with memory usage, not some other kind of resource, debugging it can be harder. Memory cannot be freed explicitly in python. The cpython vm (which you are most likely using) does release memory as soon as the last reference to it goes away, but sometimes cannot free memory trapped in cycles with objects that have a __del__ method. If you have any __del__ methods of your own or use classes that have them this may be part of your problem.\nYour actual question (the memory one, not the order of execution one) is hard to answer without seeing more code, though. It may be something obvious (or there may at least be some obvious way to reduce the amount of memory you need).\n",
"\"if I open a file of data, read in the data, close the file, then do other stuff do I know for sure that the file is closed before the lines after I close the file are executed??\"\nClosed yes.\nReleased from memory. No. No guarantees about when garbage collection will occur.\nFurther, closing a file says nothing about all the other variables you've created and the other objects you've left laying around attached to those variables.\nThere's no \"order of operations\" issue.\nI'll bet that you have too many global variables with too many copies of the data.\n",
"If the data consists of columns and rows, why not use the built in file iterator to fetch one line at a time?\nf = open('file.txt')\nfirst_line = f.next()\n\n",
"popen2.py:\nclass Popen4(Popen3):\n childerr = None\n\n def __init__(self, cmd, bufsize=-1):\n _cleanup()\n self.cmd = cmd\n p2cread, p2cwrite = os.pipe()\n c2pread, c2pwrite = os.pipe()\n self.pid = os.fork()\n if self.pid == 0:\n # Child\n os.dup2(p2cread, 0)\n os.dup2(c2pwrite, 1)\n os.dup2(c2pwrite, 2)\n self._run_child(cmd)\n os.close(p2cread)\n self.tochild = os.fdopen(p2cwrite, 'w', bufsize)\n os.close(c2pwrite)\n self.fromchild = os.fdopen(c2pread, 'r', bufsize)\n\nman 2 fork:\n\nThe fork() function may fail if:\n[ENOMEM]\n Insufficient storage space is available.\n\nos.popen4 eventually calls open2.Popen4.__init__, which must fork in order to create the child process that you try to read from/write to. This underlying call is failing, likely due to resource exhaustion.\nYou may be using too much memory elsewhere, causing fork to attempt to use more than the RLIMIT_DATA or RLIMIT_RSS limit given to your user. As recommended by Python memory profiler - Stack Overflow, Heapy can help you determine whether this is the case.\n"
] |
[
12,
3,
3,
3,
1,
0,
0
] |
[] |
[] |
[
"execution",
"python"
] |
stackoverflow_0002162975_execution_python.txt
|
Q:
Django and Postgres transaction rollback
I have a piece of code that works in a background process which looks like
from django.db import transaction
try:
<some code>
transaction.commit()
except Exception, e:
print e
transaction.rollback()
In a test, I break <some_code> with data that causes a database error. The exception is following
File "/home/commando/Development/Diploma/streaminatr/stream/testcases/feeds.py", line 261, in testInterrupt
form.save(self.user1)
File "/usr/lib/pymodules/python2.5/django/db/transaction.py", line 223, in _autocommit
return func(*args, **kw)
File "/home/commando/Development/Diploma/streaminatr/stream/forms.py", line 99, in save
print(models.FeedChannel.objects.all())
File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 68, in `__repr__ `
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 83, in `__len__ `
self._result_cache.extend(list(self._iter))
File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 238, in iterator
for row in self.query.results_iter():
File "/usr/lib/pymodules/python2.5/django/db/models/sql/query.py", line 287, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/pymodules/python2.5/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
InternalError: current transaction is aborted, commands ignored until end of transaction block
This is what I expect. The bad thing is that I still get the same error when I try to access the DB after transaction.rollback is called. What should I do to rollback the transaction succcessfully and make the connection usable once again?
Btw, I also tried inserting print connection.queries to debug the code, and it always returns an empty list. Could it be that Django is using some other DB connection?
The code is run outside of request-response cycle. I tried switching TransactionMiddleware on and off, but it gave no effect.
I am using Django 1.1 and Postgres 8.4.
A:
Default TestCase does not know anything about transactions, you need to use TransactionalTestCase in this case.
A:
I wrote this decorator based on the transaction middleware source. Hope it helps, works perfectly for me.
def djangoDBManaged(func):
def f(*args, **kwargs):
django.db.transaction.enter_transaction_management()
django.db.transaction.managed(True)
try:
rs = func(*args, **kwargs)
except Exception:
if django.db.transaction.is_dirty():
django.db.transaction.rollback()
django.db.transaction.leave_transaction_management()
raise
finally:
if django.db.transaction.is_managed():
if django.db.transaction.is_dirty():
django.db.transaction.commit()
django.db.transaction.leave_transaction_management()
return rs
# So logging gets the right call info whatever the decorator order is
f.__name__ = func.__name__
f.__doc__ = func.__doc__
f.__dict__ = func.__dict__
return f
|
Django and Postgres transaction rollback
|
I have a piece of code that works in a background process which looks like
from django.db import transaction
try:
<some code>
transaction.commit()
except Exception, e:
print e
transaction.rollback()
In a test, I break <some_code> with data that causes a database error. The exception is following
File "/home/commando/Development/Diploma/streaminatr/stream/testcases/feeds.py", line 261, in testInterrupt
form.save(self.user1)
File "/usr/lib/pymodules/python2.5/django/db/transaction.py", line 223, in _autocommit
return func(*args, **kw)
File "/home/commando/Development/Diploma/streaminatr/stream/forms.py", line 99, in save
print(models.FeedChannel.objects.all())
File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 68, in `__repr__ `
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 83, in `__len__ `
self._result_cache.extend(list(self._iter))
File "/usr/lib/pymodules/python2.5/django/db/models/query.py", line 238, in iterator
for row in self.query.results_iter():
File "/usr/lib/pymodules/python2.5/django/db/models/sql/query.py", line 287, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/pymodules/python2.5/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
InternalError: current transaction is aborted, commands ignored until end of transaction block
This is what I expect. The bad thing is that I still get the same error when I try to access the DB after transaction.rollback is called. What should I do to rollback the transaction succcessfully and make the connection usable once again?
Btw, I also tried inserting print connection.queries to debug the code, and it always returns an empty list. Could it be that Django is using some other DB connection?
The code is run outside of request-response cycle. I tried switching TransactionMiddleware on and off, but it gave no effect.
I am using Django 1.1 and Postgres 8.4.
|
[
"Default TestCase does not know anything about transactions, you need to use TransactionalTestCase in this case.\n",
"I wrote this decorator based on the transaction middleware source. Hope it helps, works perfectly for me.\ndef djangoDBManaged(func):\n def f(*args, **kwargs):\n django.db.transaction.enter_transaction_management()\n django.db.transaction.managed(True)\n try:\n rs = func(*args, **kwargs)\n except Exception:\n if django.db.transaction.is_dirty():\n django.db.transaction.rollback()\n django.db.transaction.leave_transaction_management()\n raise\n finally:\n if django.db.transaction.is_managed():\n if django.db.transaction.is_dirty():\n django.db.transaction.commit()\n django.db.transaction.leave_transaction_management()\n return rs\n # So logging gets the right call info whatever the decorator order is\n f.__name__ = func.__name__\n f.__doc__ = func.__doc__\n f.__dict__ = func.__dict__\n return f\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"django",
"postgresql",
"python",
"transactions"
] |
stackoverflow_0002161723_django_postgresql_python_transactions.txt
|
Q:
Custom address field in Django Model
What's the common practice to represent postal addresses in Django models? Is there a library for custom model fields that include postal address fields and potentially handle validation and formatting?
If no library exists, how can I write one? Can I represent a composite field (a field that gets serialized to multiple columns in db) in django? The hope is that this eliminates the need to having a joining query.
A:
I don't know of a single form field for addresses, but you can use localflavor to validate the input and a combo of MultiWidget and MultiValueField for creating an address field. Mine looks something like this:
class SplitAddressWidget(forms.MultiWidget):
def __init__(self, attrs=None):
widgets = []
widgets.append(forms.TextInput(attrs=attrs))
widgets.append(forms.TextInput(attrs=attrs))
widgets.append(forms.TextInput(attrs=attrs))
widgets.append(forms.TextInput(attrs=attrs))
widgets.append(forms.TextInput(attrs=attrs))
super(SplitAddressWidget, self).__init__(widgets, attrs)
...
class SplitAddressField(forms.MultiValueField):
widget = SplitAddressWidget
def __init__(self, *args, **kwargs):
fields = (
forms.CharField(required=kwargs['required']),
forms.CharField(required=0),
forms.CharField(required=kwargs['required']),
USStateField(required=kwargs['required']),
USZipCodeField(required=kwargs['required']),
)
super(SplitAddressField, self).__init__(fields, *args, **kwargs)
...
There is more code involved, but it is a bit much to paste in here. This info should get you headed in the right direction.
Note: as of Nov. 21, 2013 localflavor has been moved to an external package (available on PyPi).
|
Custom address field in Django Model
|
What's the common practice to represent postal addresses in Django models? Is there a library for custom model fields that include postal address fields and potentially handle validation and formatting?
If no library exists, how can I write one? Can I represent a composite field (a field that gets serialized to multiple columns in db) in django? The hope is that this eliminates the need to having a joining query.
|
[
"I don't know of a single form field for addresses, but you can use localflavor to validate the input and a combo of MultiWidget and MultiValueField for creating an address field. Mine looks something like this:\nclass SplitAddressWidget(forms.MultiWidget):\n def __init__(self, attrs=None): \n widgets = []\n widgets.append(forms.TextInput(attrs=attrs))\n widgets.append(forms.TextInput(attrs=attrs))\n widgets.append(forms.TextInput(attrs=attrs))\n widgets.append(forms.TextInput(attrs=attrs))\n widgets.append(forms.TextInput(attrs=attrs))\n super(SplitAddressWidget, self).__init__(widgets, attrs)\n ...\n\nclass SplitAddressField(forms.MultiValueField):\n widget = SplitAddressWidget\n def __init__(self, *args, **kwargs):\n fields = (\n forms.CharField(required=kwargs['required']),\n forms.CharField(required=0), \n forms.CharField(required=kwargs['required']),\n USStateField(required=kwargs['required']),\n USZipCodeField(required=kwargs['required']),\n )\n super(SplitAddressField, self).__init__(fields, *args, **kwargs)\n ...\n\nThere is more code involved, but it is a bit much to paste in here. This info should get you headed in the right direction.\nNote: as of Nov. 21, 2013 localflavor has been moved to an external package (available on PyPi).\n"
] |
[
6
] |
[] |
[] |
[
"django",
"django_models",
"field",
"python"
] |
stackoverflow_0002165252_django_django_models_field_python.txt
|
Q:
How to get progress of os.walk in python?
I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along os.walk is. How would I accomplish such a thing?
I tried doing startpt = root.count(os.sep) and gauging off of that but that just gives how deep os.walk is in a directory tree.
def locate(filelist, root=os.curdir): #Find a list of files, return directories.
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in returnMatches(filelist, [k.lower() for k in files]):
yield path + "\\"
A:
It depends!
If the files and directories are distributed more or less evenly you could show rough process by assuming every toplevel directory is going to take the same amount of time. But if they are not distributed evenly you cannot find out about it cheaply. You either have to know roughly how populated every directory is in advance, or you have to os.walk the entire thing twice (but that is only useful if your actual processing takes much longer than the os.walk itself does).
That is: say you have 4 toplevel directories, and each one contains 4 files. If you assume every toplevel dir takes 25% of progress, and each file takes another 25% of the progress for that dir, you can show a nice progress indicator. But if the last subdir turns out to contain many more files than the first few your progress indicator will have hit 75% before you find out about it. You cannot really fix that if the os.walk itself is the bottleneck (not your processing) and it's an arbitrary directory tree (not one where you know in advance roughly how long every subtree is going to take).
And of course that's assuming the cost here is about the same for every file...
A:
Just show an indeterminate progress bar (i.e. the ones that show a blob bouncing back and forth or the barber pole effect). That way users know that the program is doing something useful but doesn't mislead them as far as time to complete and such.
A:
I figured this out.
I used os.listdir to get a list of toplevel directories, and then used the .split function on the path that os.walk returned, returning the first level directory that it was currently in.
That left me with a list of toplevel directories, which I could find the index of the current directory of os.walk, and compare the index returned with the length of the list, giving me a % complete. ;)
This doesn't give me a smooth progress, because the level of work done in each directory can vary but smoothing out the progress indicator is of no concern for me. But it could easily be accomplished by extending the path checking deeper into the directory structure.
Here is the final code from getting my progress:
def locateGameDirs(filelist, root=os.curdir): #Find a list of files, return directories.
toplevel = [folder for folder in os.listdir(root) if os.path.isdir(os.path.join(root, folder))] #List of top-level directories
fileset = set(filelist)
for path, dirs, files in os.walk(os.path.abspath(root)):
curdir = path.split('\\')[1] #The directory os.walk is currently in.
try: #Thrown here because there's a nonexistant(?) first entry.
youarehere = toplevel.index(curdir)
progress = int(((youarehere)/len(toplevel))*100)
except:
pass
for filename in returnMatches(filelist, [k.lower() for k in files]):
yield filename, path + "\\", progress
And right now for debugging purposes I'm doing this further in the code:
for wow in locateGameDirs(["wow.exe", "firefox.exe", "vlc.exe"], "C:\\"):
print wow
Is there a nice little way to get rid of that try/except?; it seems the first iteration of path gives me nothing...
A:
Do it in two passes: first count how many total files/folders are in the tree, and then during the second pass do actual processing.
A:
You need to know the total number of files to do a meaningful progress indicator.
You can get the number of files like this
len(list(os.walk(os.path.abspath(root))))
but that is going to take some time and you probably need a progress indicator for that...
To find the number of files really quickly you'd need a filesystem which keeps track of the number of files for you.
Perhaps you can save the total from a previous run and use that as an estimate
A:
I suggest you avoid walking the directory. Instead use an indexed-based app for quickly finding files. You can use the app's command-line interface via subprocess and find the files almost instantaneously.
On Windows, see Everything. On UNIX, check out locate. Not sure about Mac, but I'm sure there's an option there too.
A:
as I said in the comment, the performance bottle neck likely lies outside of the locate function. your returnMatches is a fairly expensive function. I think you'd be better off replacing it with the following code:
def locate(filelist, root=os.curdir)
fileset = set(filelist) # if possible, pass the set instead of the list as a first argument
for path, dirs, files in os.walk(os.path.abspath(root)):
if any(file.lower() in fileset for file in files):
yield path + '\\'
This way you reduce the number of wasteful operations, yield once per file in the directory (which I think is what you actually indented to do) and you can forget about the progress at the same time. I don't think that progress would be an expected feature of the interface anyway.
A:
Thinking out of the box here...what if you did it based on size:
Use subprocess to run 'du -sb' and get the total_size of your root directory
As you walk, check the size of each file and decrement from your total_size (giving you remaining_size)
pct_complete = (total_size - remaining_size)/total_size
Thoughts?
-aj
A:
One optimisation you could do - you are converting filelist into a set on every call to returnMatches, even though it never changes. move the conversion to the start of the 'locate' function and pass the set in on every iteration.
A:
Well, this was fun. Here is another silly way of doing it, but as everything else, it only calculates the right progress for uniform paths.
import os, sys, time
def calc_progress(progress, root, dirs):
prog_start, prog_end, prog_slice = 0.0, 1.0, 1.0
current_progress = 0.0
parent_path, current_name = os.path.split(root)
data = progress.get(parent_path)
if data:
prog_start, prog_end, subdirs = data
i = subdirs.index(current_name)
prog_slice = (prog_end - prog_start) / len(subdirs)
current_progress = prog_slice * i + prog_start
if i == (len(subdirs) - 1):
del progress[parent_path]
if dirs:
progress[root] = (current_progress, current_progress+prog_slice, dirs)
return current_progress
def walk(start_root):
progress = {}
print 'Starting with {start_root}'.format(**locals())
for root, dirs, files in os.walk(start_root):
print '{0}: {1:%}'.format(root[len(start_root)+1:], calc_progress(progress, root, dirs))
|
How to get progress of os.walk in python?
|
I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along os.walk is. How would I accomplish such a thing?
I tried doing startpt = root.count(os.sep) and gauging off of that but that just gives how deep os.walk is in a directory tree.
def locate(filelist, root=os.curdir): #Find a list of files, return directories.
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in returnMatches(filelist, [k.lower() for k in files]):
yield path + "\\"
|
[
"It depends!\nIf the files and directories are distributed more or less evenly you could show rough process by assuming every toplevel directory is going to take the same amount of time. But if they are not distributed evenly you cannot find out about it cheaply. You either have to know roughly how populated every directory is in advance, or you have to os.walk the entire thing twice (but that is only useful if your actual processing takes much longer than the os.walk itself does).\nThat is: say you have 4 toplevel directories, and each one contains 4 files. If you assume every toplevel dir takes 25% of progress, and each file takes another 25% of the progress for that dir, you can show a nice progress indicator. But if the last subdir turns out to contain many more files than the first few your progress indicator will have hit 75% before you find out about it. You cannot really fix that if the os.walk itself is the bottleneck (not your processing) and it's an arbitrary directory tree (not one where you know in advance roughly how long every subtree is going to take).\nAnd of course that's assuming the cost here is about the same for every file...\n",
"Just show an indeterminate progress bar (i.e. the ones that show a blob bouncing back and forth or the barber pole effect). That way users know that the program is doing something useful but doesn't mislead them as far as time to complete and such.\n",
"I figured this out.\nI used os.listdir to get a list of toplevel directories, and then used the .split function on the path that os.walk returned, returning the first level directory that it was currently in.\nThat left me with a list of toplevel directories, which I could find the index of the current directory of os.walk, and compare the index returned with the length of the list, giving me a % complete. ;)\nThis doesn't give me a smooth progress, because the level of work done in each directory can vary but smoothing out the progress indicator is of no concern for me. But it could easily be accomplished by extending the path checking deeper into the directory structure.\nHere is the final code from getting my progress:\ndef locateGameDirs(filelist, root=os.curdir): #Find a list of files, return directories.\n toplevel = [folder for folder in os.listdir(root) if os.path.isdir(os.path.join(root, folder))] #List of top-level directories\n fileset = set(filelist)\n\n for path, dirs, files in os.walk(os.path.abspath(root)):\n\n curdir = path.split('\\\\')[1] #The directory os.walk is currently in.\n\n try: #Thrown here because there's a nonexistant(?) first entry.\n youarehere = toplevel.index(curdir)\n progress = int(((youarehere)/len(toplevel))*100)\n except:\n pass\n\n for filename in returnMatches(filelist, [k.lower() for k in files]):\n yield filename, path + \"\\\\\", progress\n\nAnd right now for debugging purposes I'm doing this further in the code:\n for wow in locateGameDirs([\"wow.exe\", \"firefox.exe\", \"vlc.exe\"], \"C:\\\\\"):\n print wow\n\nIs there a nice little way to get rid of that try/except?; it seems the first iteration of path gives me nothing...\n",
"Do it in two passes: first count how many total files/folders are in the tree, and then during the second pass do actual processing.\n",
"You need to know the total number of files to do a meaningful progress indicator.\nYou can get the number of files like this\nlen(list(os.walk(os.path.abspath(root))))\n\nbut that is going to take some time and you probably need a progress indicator for that...\nTo find the number of files really quickly you'd need a filesystem which keeps track of the number of files for you.\nPerhaps you can save the total from a previous run and use that as an estimate\n",
"I suggest you avoid walking the directory. Instead use an indexed-based app for quickly finding files. You can use the app's command-line interface via subprocess and find the files almost instantaneously.\nOn Windows, see Everything. On UNIX, check out locate. Not sure about Mac, but I'm sure there's an option there too.\n",
"as I said in the comment, the performance bottle neck likely lies outside of the locate function. your returnMatches is a fairly expensive function. I think you'd be better off replacing it with the following code:\ndef locate(filelist, root=os.curdir)\n fileset = set(filelist) # if possible, pass the set instead of the list as a first argument\n for path, dirs, files in os.walk(os.path.abspath(root)):\n if any(file.lower() in fileset for file in files):\n yield path + '\\\\'\n\nThis way you reduce the number of wasteful operations, yield once per file in the directory (which I think is what you actually indented to do) and you can forget about the progress at the same time. I don't think that progress would be an expected feature of the interface anyway.\n",
"Thinking out of the box here...what if you did it based on size:\n\nUse subprocess to run 'du -sb' and get the total_size of your root directory\nAs you walk, check the size of each file and decrement from your total_size (giving you remaining_size)\npct_complete = (total_size - remaining_size)/total_size\n\nThoughts?\n-aj\n",
"One optimisation you could do - you are converting filelist into a set on every call to returnMatches, even though it never changes. move the conversion to the start of the 'locate' function and pass the set in on every iteration.\n",
"Well, this was fun. Here is another silly way of doing it, but as everything else, it only calculates the right progress for uniform paths.\nimport os, sys, time\n\ndef calc_progress(progress, root, dirs):\n prog_start, prog_end, prog_slice = 0.0, 1.0, 1.0\n\n current_progress = 0.0\n parent_path, current_name = os.path.split(root)\n data = progress.get(parent_path)\n if data:\n prog_start, prog_end, subdirs = data\n i = subdirs.index(current_name)\n prog_slice = (prog_end - prog_start) / len(subdirs)\n current_progress = prog_slice * i + prog_start\n\n if i == (len(subdirs) - 1):\n del progress[parent_path]\n\n if dirs:\n progress[root] = (current_progress, current_progress+prog_slice, dirs)\n\n return current_progress\n\ndef walk(start_root):\n progress = {}\n print 'Starting with {start_root}'.format(**locals())\n\n for root, dirs, files in os.walk(start_root):\n print '{0}: {1:%}'.format(root[len(start_root)+1:], calc_progress(progress, root, dirs))\n\n"
] |
[
5,
4,
4,
2,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"os.walk",
"python"
] |
stackoverflow_0002164391_os.walk_python.txt
|
Q:
In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?
e.g.:
def Factotum(models.Model):
id_ref = models.IntegerField()
def calculateSeniorityFactor():
return (1000 - id_ref) * 1000
I want to be able to run a command line in the Django shell to tell me all of the public methods of a Django model. The output of running on above would be:
>> introspect Factotoum
--> Variable: id_ref
--> Methods: calculateSeniorityFactor
A:
Well, things you can introspect are many, not just one.
Good things to start with are:
>>> help(object)
>>> dir(object)
>>> object.__dict__
Also take a look at the inspect module in the standard library.
That should make 99% of all the bases belong to you.
A:
Use inspect:
import inspect
def introspect(something):
methods = inspect.getmembers(something, inspect.ismethod)
others = inspect.getmembers(something, lambda x: not inspect.ismethod(x))
print 'Variable:', # ?! what a WEIRD heading you want -- ah well, w/ever
for name, _ in others: print name,
print
print 'Methods:',
for name, _ in methods: print name,
print
There's no way you can invoke this without parentheses in a normal Python shell, you'll have to use introspect(Factotum) ((with class Factotum property imported in the current namespace of course)) and not introspect Factotum with a space. If this irks you terribly, you may want to look at IPython.
|
In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?
|
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?
e.g.:
def Factotum(models.Model):
id_ref = models.IntegerField()
def calculateSeniorityFactor():
return (1000 - id_ref) * 1000
I want to be able to run a command line in the Django shell to tell me all of the public methods of a Django model. The output of running on above would be:
>> introspect Factotoum
--> Variable: id_ref
--> Methods: calculateSeniorityFactor
|
[
"Well, things you can introspect are many, not just one.\nGood things to start with are:\n>>> help(object)\n>>> dir(object)\n>>> object.__dict__\n\nAlso take a look at the inspect module in the standard library.\nThat should make 99% of all the bases belong to you.\n",
"Use inspect:\nimport inspect\ndef introspect(something):\n methods = inspect.getmembers(something, inspect.ismethod)\n others = inspect.getmembers(something, lambda x: not inspect.ismethod(x))\n print 'Variable:', # ?! what a WEIRD heading you want -- ah well, w/ever\n for name, _ in others: print name,\n print\n print 'Methods:',\n for name, _ in methods: print name,\n print\n\nThere's no way you can invoke this without parentheses in a normal Python shell, you'll have to use introspect(Factotum) ((with class Factotum property imported in the current namespace of course)) and not introspect Factotum with a space. If this irks you terribly, you may want to look at IPython.\n"
] |
[
50,
6
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002164767_django_python.txt
|
Q:
Modifying a Python class
I'd like to modify all classes in Python. For example str and int and others like Person(object).
I'd like to add an attribute to them and to change the way its methods works.
Which is the best approach for this? Metaclasses?
A:
While you can do this for classes defined in python code (it will not work for builtin ones) by reassigning their attributes please do not actually do so. Just subclass and use the subclass, or write functions that take an instance of the class as argument instead of adding your own methods. Doing what you have to mind leads to awkward, fragile code, especially if you end up using multiple libraries simultaneously that try to do this to the same classes.
Is there an actual problem you're trying to solve this way?
A:
Built-in classes can't be modified, but you can "hide" a built-in class (or any other of course) by one of the same name.
For example, suppose that the change is to add to a bunch of classes a new attribute "foobar" whose initial value is 23, and to every instance of those classes a new attribute "murf" whose initial value is 45. Here's one way:
def changedclass(cls):
def __init__(self, *a, **k):
cls.__init__(self, *a, **k)
self.murf = 45
return type(cls.__name__, (cls,), {'foobar': 23, '__init__': __init__})
def changemany(changed, classes_by_module):
for module, classnames in classes_by_module.iteritems():
for name in classnames:
cls = getattr(module, name)
subcls = changed(cls)
setattr(module, name, subcls)
import __builtin__
import mymod
changemany(changedclass, {__builtin__: ('int', 'str'), mymod: ('Person',)})
Note that bare literals like 'ciao' and 23 will still belong to the real classes -- there's no way to change that; you'll need to use str('ciao') and int(23) to use the "fake" classes.
A:
You can't edit the class directly like you might with javascript's prototype attribute, it's better if you subclass them. This let's you add the functionality you want and not force it to be used everywhere.
A:
subclass:
class int(int):
def foo(self):
print "foo"
int(2).foo()
|
Modifying a Python class
|
I'd like to modify all classes in Python. For example str and int and others like Person(object).
I'd like to add an attribute to them and to change the way its methods works.
Which is the best approach for this? Metaclasses?
|
[
"While you can do this for classes defined in python code (it will not work for builtin ones) by reassigning their attributes please do not actually do so. Just subclass and use the subclass, or write functions that take an instance of the class as argument instead of adding your own methods. Doing what you have to mind leads to awkward, fragile code, especially if you end up using multiple libraries simultaneously that try to do this to the same classes.\nIs there an actual problem you're trying to solve this way?\n",
"Built-in classes can't be modified, but you can \"hide\" a built-in class (or any other of course) by one of the same name.\nFor example, suppose that the change is to add to a bunch of classes a new attribute \"foobar\" whose initial value is 23, and to every instance of those classes a new attribute \"murf\" whose initial value is 45. Here's one way:\ndef changedclass(cls):\n def __init__(self, *a, **k):\n cls.__init__(self, *a, **k)\n self.murf = 45\n return type(cls.__name__, (cls,), {'foobar': 23, '__init__': __init__})\n\ndef changemany(changed, classes_by_module):\n for module, classnames in classes_by_module.iteritems():\n for name in classnames:\n cls = getattr(module, name)\n subcls = changed(cls)\n setattr(module, name, subcls)\n\nimport __builtin__\nimport mymod\nchangemany(changedclass, {__builtin__: ('int', 'str'), mymod: ('Person',)})\n\nNote that bare literals like 'ciao' and 23 will still belong to the real classes -- there's no way to change that; you'll need to use str('ciao') and int(23) to use the \"fake\" classes.\n",
"You can't edit the class directly like you might with javascript's prototype attribute, it's better if you subclass them. This let's you add the functionality you want and not force it to be used everywhere.\n",
"subclass:\n\nclass int(int):\n def foo(self):\n print \"foo\"\n\nint(2).foo()\n\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"metaclass",
"python"
] |
stackoverflow_0002165200_metaclass_python.txt
|
Q:
What would be the jquery equivalent of 'Dive into python'?
I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery?
I see that jquery 1.4 has been released. Does this change anything w.r.t answers?
A:
Well python is a language and jQuery is a framework, so I'll give you one for javascript and then you can move to jQuery:
This book should be a required read for front end devs:
JavaScript: The Good Parts by Douglas Crockford
Then:
The jQuery Cookbook
This one is a pretty awesome dive into all the different aspects of programming real world applications with jQuery, whereas "Dive into Python" and "JS The Good Parts" are more like poignant language overviews.
A:
jQuery's main documentation is quite good. You might start with How jQuery works.
If you have a certain problem and you google for it, you mostly find plenty of tutorials.
|
What would be the jquery equivalent of 'Dive into python'?
|
I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery?
I see that jquery 1.4 has been released. Does this change anything w.r.t answers?
|
[
"Well python is a language and jQuery is a framework, so I'll give you one for javascript and then you can move to jQuery:\nThis book should be a required read for front end devs:\nJavaScript: The Good Parts by Douglas Crockford\nThen:\nThe jQuery Cookbook\nThis one is a pretty awesome dive into all the different aspects of programming real world applications with jQuery, whereas \"Dive into Python\" and \"JS The Good Parts\" are more like poignant language overviews.\n",
"jQuery's main documentation is quite good. You might start with How jQuery works.\nIf you have a certain problem and you google for it, you mostly find plenty of tutorials.\n"
] |
[
4,
1
] |
[] |
[] |
[
"javascript",
"jquery",
"python"
] |
stackoverflow_0002165811_javascript_jquery_python.txt
|
Q:
How to make pyuic4 automatically set tabs to "MainWindow"?
After adding a new label and textEdit to a grid right above these tabs, When I generate the ui.py file with pyuic4, It generates the the following lines for many different tabs which gives errors about not having enough arguments.
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6),)
However the .ui would generate this fine before I made the changes.
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6), QtGui.QApplication.translate("MainWindow", " ", None, QtGui.QApplication.UnicodeUTF8))
This code works fine, and If I edit this into the ui.py file my changes also work fine. However how do I get it to automatically do this when i use pyuic4. Because from what I understand is that you should never have to edit the ui.py file. Thanks
Edited: I updated everything to no avail. pretty much any change I do to old UI file will cause this problem if I use pyuic4 on it. translatable IS checked under currentTabText in qtDesigner if that matters. The problem happens in this function of the .py file:
def retranslateUi(self, MainWindow):
#these are incorrect ones pyuic4 generates
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6), )
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_9), )
#these are the correct lines it used to generate
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6),QtGui.QApplication.translate("MainWinow", " ", None, QtGui.QApplication.UnicodeUTF8))
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_9), QtGui.QApplication.translate("MainWindow", " ", None, QtGui.QApplication.UnicodeUTF8))
Edit2: Even when I open the .ui up in qtdesigner, click something, without even modifying it, save, then use pyuic4, it generates the bad code.
A:
YAY!!!!
The setTabText field for tabs when using designer must have something in it. It turns out the ui was using white spaces as the tabText, whenever you open designer it got rid of the white spaces. So if you set the tab text to a space again after making your changes it works.
|
How to make pyuic4 automatically set tabs to "MainWindow"?
|
After adding a new label and textEdit to a grid right above these tabs, When I generate the ui.py file with pyuic4, It generates the the following lines for many different tabs which gives errors about not having enough arguments.
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6),)
However the .ui would generate this fine before I made the changes.
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6), QtGui.QApplication.translate("MainWindow", " ", None, QtGui.QApplication.UnicodeUTF8))
This code works fine, and If I edit this into the ui.py file my changes also work fine. However how do I get it to automatically do this when i use pyuic4. Because from what I understand is that you should never have to edit the ui.py file. Thanks
Edited: I updated everything to no avail. pretty much any change I do to old UI file will cause this problem if I use pyuic4 on it. translatable IS checked under currentTabText in qtDesigner if that matters. The problem happens in this function of the .py file:
def retranslateUi(self, MainWindow):
#these are incorrect ones pyuic4 generates
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6), )
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_9), )
#these are the correct lines it used to generate
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6),QtGui.QApplication.translate("MainWinow", " ", None, QtGui.QApplication.UnicodeUTF8))
self.tcTab.setTabText(self.tcTab.indexOf(self.tab_9), QtGui.QApplication.translate("MainWindow", " ", None, QtGui.QApplication.UnicodeUTF8))
Edit2: Even when I open the .ui up in qtdesigner, click something, without even modifying it, save, then use pyuic4, it generates the bad code.
|
[
"YAY!!!!\nThe setTabText field for tabs when using designer must have something in it. It turns out the ui was using white spaces as the tabText, whenever you open designer it got rid of the white spaces. So if you set the tab text to a space again after making your changes it works.\n"
] |
[
1
] |
[] |
[] |
[
"designer",
"pyqt",
"python",
"qt"
] |
stackoverflow_0002120232_designer_pyqt_python_qt.txt
|
Q:
Regex to separate Numeric from Alpha
I have a bunch of strings:
"10people"
"5cars"
..
How would I split this to?
['10','people']
['5','cars']
It can be any amount of numbers and text.
I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python.
A:
Use the regex (\d+)([a-zA-Z]+).
import re
a = ["10people", "5cars"]
[re.match('^(\\d+)([a-zA-Z]+)$', x).groups() for x in a]
Result:
[('10', 'people'), ('5', 'cars')]
A:
>>> re.findall('(\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')
['12', 'fgsdfg', '234', 'jhfq', '35', 'rjg']
A:
>>> re.findall("\d+|[a-zA-Z]+","10people")
['10', 'people']
>>> re.findall("\d+|[a-zA-Z]+","10people5cars")
['10', 'people', '5', 'cars']
A:
In general, a split on /(?<=[0-9])(?=[a-z])|(?<=[a-z])(?=[0-9])/i separates a string that way.
A:
>>> import re
>>> s = '10cars'
>>> m = re.match(r'(\d+)([a-z]+)', s)
>>> print m.group(1)
10
>>> print m.group(2)
cars
A:
If you are like me and goes long loops around to avoid regexpes justbecause they are ugly, here is a non-regex approach:
data = "5people10cars"
numbers = "".join(ch if ch.isdigit() else "\n" for ch in data).split()
names = "".join(ch if not ch.isdigit() else "\n" for ch in data).split()
final = zip (numbers, names)
A:
Piggybacking on jsbueno's idea, using str.translate, followed by split:
import string
allchars = ''.join(chr(i) for i in range(32,256))
digExtractTrans = string.maketrans(allchars, ''.join(ch if ch.isdigit() else ' ' for ch in allchars))
alpExtractTrans = string.maketrans(allchars, ''.join(ch if ch.isalpha() else ' ' for ch in allchars))
data = "5people10cars"
numbers = data.translate(digExtractTrans).split()
names = data.translate(alpExtractTrans).split()
You only need to create the translation tables once, then call translate and split as often as you want.
|
Regex to separate Numeric from Alpha
|
I have a bunch of strings:
"10people"
"5cars"
..
How would I split this to?
['10','people']
['5','cars']
It can be any amount of numbers and text.
I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python.
|
[
"Use the regex (\\d+)([a-zA-Z]+).\nimport re\na = [\"10people\", \"5cars\"]\n[re.match('^(\\\\d+)([a-zA-Z]+)$', x).groups() for x in a]\n\nResult: \n[('10', 'people'), ('5', 'cars')]\n\n",
">>> re.findall('(\\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')\n['12', 'fgsdfg', '234', 'jhfq', '35', 'rjg']\n\n",
">>> re.findall(\"\\d+|[a-zA-Z]+\",\"10people\")\n['10', 'people']\n\n>>> re.findall(\"\\d+|[a-zA-Z]+\",\"10people5cars\")\n['10', 'people', '5', 'cars']\n\n",
"In general, a split on /(?<=[0-9])(?=[a-z])|(?<=[a-z])(?=[0-9])/i separates a string that way.\n",
">>> import re\n>>> s = '10cars'\n>>> m = re.match(r'(\\d+)([a-z]+)', s)\n>>> print m.group(1)\n10\n>>> print m.group(2)\ncars\n\n",
"If you are like me and goes long loops around to avoid regexpes justbecause they are ugly, here is a non-regex approach:\ndata = \"5people10cars\"\n\nnumbers = \"\".join(ch if ch.isdigit() else \"\\n\" for ch in data).split()\nnames = \"\".join(ch if not ch.isdigit() else \"\\n\" for ch in data).split()\n\nfinal = zip (numbers, names)\n\n",
"Piggybacking on jsbueno's idea, using str.translate, followed by split:\nimport string\n\nallchars = ''.join(chr(i) for i in range(32,256))\ndigExtractTrans = string.maketrans(allchars, ''.join(ch if ch.isdigit() else ' ' for ch in allchars))\nalpExtractTrans = string.maketrans(allchars, ''.join(ch if ch.isalpha() else ' ' for ch in allchars))\n\ndata = \"5people10cars\"\nnumbers = data.translate(digExtractTrans).split()\nnames = data.translate(alpExtractTrans).split()\n\nYou only need to create the translation tables once, then call translate and split as often as you want.\n"
] |
[
8,
8,
3,
2,
0,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002161519_python_regex.txt
|
Q:
Removing html tags from a text using Regular Expression in python
I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far.
import urllib.request, re
def test(url):
html = str(urllib.request.urlopen(url).read())
print(re.findall('<[\w\/\.\w]*>',html))
The html is a simple page with a few links and text but my regex won't pick up !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" and 'a href="...." tags. Can anyone explain what I need to change in my regex?
A:
Use BeautifulSoup. Use lxml. Do not use regular expressions to parse HTML.
Edit 2010-01-29: This would be a reasonable starting point for lxml:
from lxml.html import fromstring
from lxml.html.clean import Cleaner
import requests
url = "https://stackoverflow.com/questions/2165943/removing-html-tags-from-a-text-using-regular-expression-in-python"
html = requests.get(url).text
doc = fromstring(html)
tags = ['h1','h2','h3','h4','h5','h6',
'div', 'span',
'img', 'area', 'map']
args = {'meta':False, 'safe_attrs_only':False, 'page_structure':False,
'scripts':True, 'style':True, 'links':True, 'remove_tags':tags}
cleaner = Cleaner(**args)
path = '/html/body'
body = doc.xpath(path)[0]
print cleaner.clean_html(body).text_content().encode('ascii', 'ignore')
You want the content, so presumably you don't want any javascript or CSS. Also, presumably you want only the content in the body and not HTML from the head, too. Read up on lxml.html.clean to see what you can easily strip out. Way smarter than regular expressions, no?
Also, watch out for unicode encoding problems. You can easily end up with HTML that you cannot print.
2012-11-08: changed from using urllib2 to requests. Just use requests!
|
Removing html tags from a text using Regular Expression in python
|
I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far.
import urllib.request, re
def test(url):
html = str(urllib.request.urlopen(url).read())
print(re.findall('<[\w\/\.\w]*>',html))
The html is a simple page with a few links and text but my regex won't pick up !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" and 'a href="...." tags. Can anyone explain what I need to change in my regex?
|
[
"Use BeautifulSoup. Use lxml. Do not use regular expressions to parse HTML.\n\nEdit 2010-01-29: This would be a reasonable starting point for lxml:\nfrom lxml.html import fromstring\nfrom lxml.html.clean import Cleaner\nimport requests\n\nurl = \"https://stackoverflow.com/questions/2165943/removing-html-tags-from-a-text-using-regular-expression-in-python\"\nhtml = requests.get(url).text\n\ndoc = fromstring(html)\n\ntags = ['h1','h2','h3','h4','h5','h6',\n 'div', 'span', \n 'img', 'area', 'map']\nargs = {'meta':False, 'safe_attrs_only':False, 'page_structure':False, \n 'scripts':True, 'style':True, 'links':True, 'remove_tags':tags}\ncleaner = Cleaner(**args)\n\npath = '/html/body'\nbody = doc.xpath(path)[0]\n\nprint cleaner.clean_html(body).text_content().encode('ascii', 'ignore')\n\nYou want the content, so presumably you don't want any javascript or CSS. Also, presumably you want only the content in the body and not HTML from the head, too. Read up on lxml.html.clean to see what you can easily strip out. Way smarter than regular expressions, no?\nAlso, watch out for unicode encoding problems. You can easily end up with HTML that you cannot print.\n\n2012-11-08: changed from using urllib2 to requests. Just use requests!\n"
] |
[
15
] |
[
"import re\npatjunk = re.compile(\"<.*?>| |&\",re.DOTALL|re.M)\nurl=\"http://www.yahoo.com\"\ndef test(url,pat):\n html = urllib2.urlopen(url).read()\n return pat.sub(\"\",html)\n\nprint test(url,patjunk)\n\n"
] |
[
-1
] |
[
"html",
"python",
"regex",
"tags"
] |
stackoverflow_0002165943_html_python_regex_tags.txt
|
Q:
Casting from a list of lists of strings to list of lists of ints in Python
I'm reading some numbers from a data source that represent x- and y-coordinates that I'll be using for a TSP-esque problem. I'm new to Python, so I'm trying to make the most of lists. After reading and parsing through the data, I'm left with a list of string lists that looks like this:
[['565.0', '575.0'], ['1215.0',
'245.0'], ...yougetthepoint...
['1740.0', '245.0']]
I would rather be dealing with integer points. How can I transform these lists containing strings to lists containing ints? They don't seem to be casting nicely, as I get this error:
ValueError: invalid literal for int()
with base 10: '565.0'
The decimal seems to be causing issues.
A:
x = [['565.0', '575.0'], ['1215.0', '245.0'], ['1740.0', '245.0']]
x = [[int(float(j)) for j in i] for i in x]
|
Casting from a list of lists of strings to list of lists of ints in Python
|
I'm reading some numbers from a data source that represent x- and y-coordinates that I'll be using for a TSP-esque problem. I'm new to Python, so I'm trying to make the most of lists. After reading and parsing through the data, I'm left with a list of string lists that looks like this:
[['565.0', '575.0'], ['1215.0',
'245.0'], ...yougetthepoint...
['1740.0', '245.0']]
I would rather be dealing with integer points. How can I transform these lists containing strings to lists containing ints? They don't seem to be casting nicely, as I get this error:
ValueError: invalid literal for int()
with base 10: '565.0'
The decimal seems to be causing issues.
|
[
"x = [['565.0', '575.0'], ['1215.0', '245.0'], ['1740.0', '245.0']]\nx = [[int(float(j)) for j in i] for i in x]\n\n"
] |
[
21
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002166577_python.txt
|
Q:
Integer Field Math in Django
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 30)
lot_no = models.CharField(max_length = 30)
inventory = models.IntegerField()
commited = models.IntegerField()
available = models.IntegerField()
reorder = models.IntegerField()
created_date = models.DateField(auto_now_add = True)
comment_user = models.ForeignKey(User, null=True)
comment_txt = models.TextField()
def __unicode__(self):
return self.code + " - " + self.name + " - " + self.lot_no + " - " + str(self.created_date)
@property
def available(self):
return self.inventory - self.commited
Im trying to have available calculated by (inventory - self) when a person enters in the data for inventory and commited in django admin template. But I'm not sure how.
Thanks,
Jon
A:
Try overriding the save method on the model:
def save(self, *args, **kwargs):
"update number available on save"
self.available = self.inventory - self.committed
super(Product, self).save(*args, **kwargs)
You could also put logic in there that would do something if self.available became negative.
A:
It seems like you may have two problems; the overlapping available property+field and availability not showing up as you expect in the admin.
Choose one way (property or field) to represent the availability and go with it. Don and Seth have shown a way to do it using a field and Daniel and Ignacio have suggested going with a property.
Since you really want this field to show up in the admin just go with the field; give it a helpful help_text="...", remove the @property, and override save().
class Product(models.Model):
# ...
availability = models.IntegerField(help_text="(updated on save)")
# Use Seth's save()
def save(self, *args, **kwargs):
self.availability = self.inventory - self.commited
super(Product, self).save(*args, **kwargs)
This is not the best way to do things in terms of normalized data but it will probably be the simplest solution to your current problem.
If you are using trunk instead of Django-1.1.1, you can also use readonly_fields in the admin.
A:
You've bound both a Django field and a vanilla Python property to the same name on your model. One of these attributes is masking the other, which is why you're getting unexpected behavior in the Django admin. This is almost certainly not what you want.
Override the save method and remove your def available property entirely.
Ignacio is trying to help you keep your data normalized by not storing information in your DB twice. It's a good practice to follow in the general case, but there are many times when you want to store calculated values in your DB. This seems like a practical use of data duplication.
A:
Don is correct that you have the name available duplicated, because you have both a field and a property. Drop the field.
This is what I said when I gave you the solution to this problem in your original question - I explicitly said "drop the existing 'available' field". Following half a solution is never going to work.
However I fundamentally disagree with Seth and Don who recommend overriding the save() function to calculate this value. That is a totally unnecessary duplication of data. The property is the correct solution.
A:
The property is actually removing the available integer field off the admin page it seems
A:
See the Django documentation for model properties
|
Integer Field Math in Django
|
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 30)
lot_no = models.CharField(max_length = 30)
inventory = models.IntegerField()
commited = models.IntegerField()
available = models.IntegerField()
reorder = models.IntegerField()
created_date = models.DateField(auto_now_add = True)
comment_user = models.ForeignKey(User, null=True)
comment_txt = models.TextField()
def __unicode__(self):
return self.code + " - " + self.name + " - " + self.lot_no + " - " + str(self.created_date)
@property
def available(self):
return self.inventory - self.commited
Im trying to have available calculated by (inventory - self) when a person enters in the data for inventory and commited in django admin template. But I'm not sure how.
Thanks,
Jon
|
[
"Try overriding the save method on the model: \ndef save(self, *args, **kwargs):\n \"update number available on save\"\n self.available = self.inventory - self.committed\n\n super(Product, self).save(*args, **kwargs)\n\nYou could also put logic in there that would do something if self.available became negative.\n",
"It seems like you may have two problems; the overlapping available property+field and availability not showing up as you expect in the admin.\nChoose one way (property or field) to represent the availability and go with it. Don and Seth have shown a way to do it using a field and Daniel and Ignacio have suggested going with a property.\nSince you really want this field to show up in the admin just go with the field; give it a helpful help_text=\"...\", remove the @property, and override save().\nclass Product(models.Model):\n # ...\n availability = models.IntegerField(help_text=\"(updated on save)\")\n\n # Use Seth's save()\n def save(self, *args, **kwargs):\n self.availability = self.inventory - self.commited\n super(Product, self).save(*args, **kwargs)\n\nThis is not the best way to do things in terms of normalized data but it will probably be the simplest solution to your current problem.\nIf you are using trunk instead of Django-1.1.1, you can also use readonly_fields in the admin.\n",
"You've bound both a Django field and a vanilla Python property to the same name on your model. One of these attributes is masking the other, which is why you're getting unexpected behavior in the Django admin. This is almost certainly not what you want.\nOverride the save method and remove your def available property entirely.\nIgnacio is trying to help you keep your data normalized by not storing information in your DB twice. It's a good practice to follow in the general case, but there are many times when you want to store calculated values in your DB. This seems like a practical use of data duplication.\n",
"Don is correct that you have the name available duplicated, because you have both a field and a property. Drop the field.\nThis is what I said when I gave you the solution to this problem in your original question - I explicitly said \"drop the existing 'available' field\". Following half a solution is never going to work.\nHowever I fundamentally disagree with Seth and Don who recommend overriding the save() function to calculate this value. That is a totally unnecessary duplication of data. The property is the correct solution.\n",
"The property is actually removing the available integer field off the admin page it seems\n",
"See the Django documentation for model properties\n"
] |
[
3,
2,
1,
1,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002136928_django_python.txt
|
Q:
How would you further lock down a Google App Engine app executing untrusted code?
We are currently using Google App Engine to evaluate solutions to Python problems submitted by students. We have moved all of the untrusted code execution off to a separate GAE application that doesn't use the datastore. Everything seems to be working fine for the 50+ problems we have uploaded, but I'm curious what security holes remain that industrious students will find. How should we further protect this code from the untrusted code it execs in GAE?
#The solution and doctest are untrusted code passed in to the GAE app.
solution = 'b=5'
doctest = '>>> b \n 5'
#Compile and exec the untrusted solution provided by the user.
compiled = compile(solution, 'submitted code', 'exec')
sandbox = {}
exec compiled in sandbox
#Compile and exec each of the doctests
test_cases = doctest.DocTestParser().get_examples(doctest)
for test in test_cases:
if not test.want:
exec test.source in sandbox
A:
Look at shell.appspot.com's source -- it actually even uses the datastore (for session persistence). At the core it's basically just doing a simple exec just like you are -- there are other refinements, but nothing special relative to "lockdown" of the untrusted code. Presumably the Google engineers (in the App Engine team) who released this sample code feel pretty good about its security against untrusted code.
The one feasible "attack" that I can think of is a "denial of service" attack that repeatedly sucks up resources and cause your account to be charged (if enabled for charging for beyond-the-free-quota usage) -- as long as you've stored somewhere safe (in a different app) the identity of whoever's uploaded a given piece of code, I don't see why a student should try such a prank and risk expulsion or something.
|
How would you further lock down a Google App Engine app executing untrusted code?
|
We are currently using Google App Engine to evaluate solutions to Python problems submitted by students. We have moved all of the untrusted code execution off to a separate GAE application that doesn't use the datastore. Everything seems to be working fine for the 50+ problems we have uploaded, but I'm curious what security holes remain that industrious students will find. How should we further protect this code from the untrusted code it execs in GAE?
#The solution and doctest are untrusted code passed in to the GAE app.
solution = 'b=5'
doctest = '>>> b \n 5'
#Compile and exec the untrusted solution provided by the user.
compiled = compile(solution, 'submitted code', 'exec')
sandbox = {}
exec compiled in sandbox
#Compile and exec each of the doctests
test_cases = doctest.DocTestParser().get_examples(doctest)
for test in test_cases:
if not test.want:
exec test.source in sandbox
|
[
"Look at shell.appspot.com's source -- it actually even uses the datastore (for session persistence). At the core it's basically just doing a simple exec just like you are -- there are other refinements, but nothing special relative to \"lockdown\" of the untrusted code. Presumably the Google engineers (in the App Engine team) who released this sample code feel pretty good about its security against untrusted code.\nThe one feasible \"attack\" that I can think of is a \"denial of service\" attack that repeatedly sucks up resources and cause your account to be charged (if enabled for charging for beyond-the-free-quota usage) -- as long as you've stored somewhere safe (in a different app) the identity of whoever's uploaded a given piece of code, I don't see why a student should try such a prank and risk expulsion or something.\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002166650_google_app_engine_python.txt
|
Q:
In Python, how do you programmatically execute unit tests stored in a string?
The following code is used to execute doctests in a Google App Engine app. How would you do this for tests written as unit test asserts rather than as doctests?
#The solution and tests are untrusted code passed in to the GAE app.
solution = 'b=5'
unittest = 'assertEqual(b, 5)'
#Here is the doctest version as a reference.
solution = 'b=5'
doctest = '>>> b \n 5'
#Compile and exec the untrusted solution provided by the user.
compiled = compile(solution, 'submitted code', 'exec')
sandbox = {}
exec compiled in sandbox
#Compile and exec each of the doctests
test_cases = doctest.DocTestParser().get_examples(doctest)
for test in test_cases:
if not test.want:
exec test.source in sandbox
A:
Methods of a class, such as unittest.TestCase.assertEqual, don't execute outside of the context provided by an instance of that class. So, a string like your 'assertEqual(b, 5)' is really a very, VERY bad case -- note that the string as written will never execute properly (you need to prepend, at the very least, somethink like 'self.', and then self needs to be made into an instance of the class, etc, etc).
I'm not sure exactly why you want to support such disastrous constructs, but, in case you're adamant that you do at all costs want to, then that's the general idea: make an instance of the unittest.Testcase class, prepend the instance-reference name and a dot to that string, and execute that compound string. Then, of course, you get into all sorts of other funny requirements, such as catching the exception that may get raised (since you don't really have a test runner to do all such housekeeping tasks for you). Yecch.
|
In Python, how do you programmatically execute unit tests stored in a string?
|
The following code is used to execute doctests in a Google App Engine app. How would you do this for tests written as unit test asserts rather than as doctests?
#The solution and tests are untrusted code passed in to the GAE app.
solution = 'b=5'
unittest = 'assertEqual(b, 5)'
#Here is the doctest version as a reference.
solution = 'b=5'
doctest = '>>> b \n 5'
#Compile and exec the untrusted solution provided by the user.
compiled = compile(solution, 'submitted code', 'exec')
sandbox = {}
exec compiled in sandbox
#Compile and exec each of the doctests
test_cases = doctest.DocTestParser().get_examples(doctest)
for test in test_cases:
if not test.want:
exec test.source in sandbox
|
[
"Methods of a class, such as unittest.TestCase.assertEqual, don't execute outside of the context provided by an instance of that class. So, a string like your 'assertEqual(b, 5)' is really a very, VERY bad case -- note that the string as written will never execute properly (you need to prepend, at the very least, somethink like 'self.', and then self needs to be made into an instance of the class, etc, etc).\nI'm not sure exactly why you want to support such disastrous constructs, but, in case you're adamant that you do at all costs want to, then that's the general idea: make an instance of the unittest.Testcase class, prepend the instance-reference name and a dot to that string, and execute that compound string. Then, of course, you get into all sorts of other funny requirements, such as catching the exception that may get raised (since you don't really have a test runner to do all such housekeeping tasks for you). Yecch.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"testing"
] |
stackoverflow_0002166761_python_testing.txt
|
Q:
pygame saving audio files
How can I convert a .wav file to some other format such as .mp3 in pygame?
Update:
Why not Gstreamer or Pygame:
I want to use native Windows environment to install a package that can do this (i.e. don't want to install cygwin). I am searching for a package which has a binary installer available for windows (with Python 2.6) or atleast where I can do "python setup.py install" without a need to install any dependencies.
A:
The answer is you can not do this using PyGame.
I found out GStreamer installer for windows from GStreamer-Winbuild project: http://www.gstreamer-winbuild.ylatuya.es/doku.php So, I will be using Gstreamer framework for audio handling.
|
pygame saving audio files
|
How can I convert a .wav file to some other format such as .mp3 in pygame?
Update:
Why not Gstreamer or Pygame:
I want to use native Windows environment to install a package that can do this (i.e. don't want to install cygwin). I am searching for a package which has a binary installer available for windows (with Python 2.6) or atleast where I can do "python setup.py install" without a need to install any dependencies.
|
[
"The answer is you can not do this using PyGame. \nI found out GStreamer installer for windows from GStreamer-Winbuild project: http://www.gstreamer-winbuild.ylatuya.es/doku.php So, I will be using Gstreamer framework for audio handling.\n"
] |
[
0
] |
[
"Pygame is an SDL wrapper. Not a multimedia framework. Why do you want to do audio format conversions in Pygame? Can't you use something else like maybe the gstreamer bindings for Python?\n"
] |
[
-2
] |
[
"pygame",
"python"
] |
stackoverflow_0002141315_pygame_python.txt
|
Q:
install python Mysql module
I've just installed python 2.6 on my win7 machine.
Now I tried to install mysqldb. But when run "python setup.py install"
C:\MySQL-python-1.2.3c1>python setup.py install
Traceback (most recent call last):
File "setup.py", line 15, in <module>
metadata, options = get_config()
File "C:\MySQL-python-1.2.3c1\setup_windows.py", line 7, in get_config
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
options['registry_key'])
WindowsError: [Error 2] Das System kann die angegebene Datei nicht finden
(System cannot find the given file)
But which file?
Thanks for your help!
A:
I have compiled MySQLdb 1.2.3c1 once with python26, you could find it here
A:
Are you running from an Administrator Mode command prompt? Also, do you have the MySQL headers available for the compiler to link against?
If you are just an end-user, you will probably find it easier to use a pre-built MySQLdb binary, as compiling in Windows is a pain. Unfortunately the official site still hasn't built against 2.6 yet, but you can download other people's builds. See this question for some links.
|
install python Mysql module
|
I've just installed python 2.6 on my win7 machine.
Now I tried to install mysqldb. But when run "python setup.py install"
C:\MySQL-python-1.2.3c1>python setup.py install
Traceback (most recent call last):
File "setup.py", line 15, in <module>
metadata, options = get_config()
File "C:\MySQL-python-1.2.3c1\setup_windows.py", line 7, in get_config
serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
options['registry_key'])
WindowsError: [Error 2] Das System kann die angegebene Datei nicht finden
(System cannot find the given file)
But which file?
Thanks for your help!
|
[
"I have compiled MySQLdb 1.2.3c1 once with python26, you could find it here\n",
"Are you running from an Administrator Mode command prompt? Also, do you have the MySQL headers available for the compiler to link against?\nIf you are just an end-user, you will probably find it easier to use a pre-built MySQLdb binary, as compiling in Windows is a pain. Unfortunately the official site still hasn't built against 2.6 yet, but you can download other people's builds. See this question for some links.\n"
] |
[
4,
1
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0002081240_mysql_python.txt
|
Q:
After handshake of websocket, chrome disconnects. Is this due to domain mismatch? Or Chrome bug?
I made my own simple WebSocket server in Python but Chrome 4.0.249.78 dev (36714) ALWAYS disconnects after the handshake. To make sure it wasn't my code I used the WebSocket server found at https://stackoverflow.com/questions/2153294?tab=newest#tab-top to test it and got the same result (below).
listening...
connection!
GET / HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: localhost:1234
Origin: http://localhost
handshaken
got:
got:
Traceback (most recent call last):
File "test.py", line 44, in <module>
start_server()
File "test.py", line 18, in start_server
interact(csock, tick)
File "test.py", line 40, in interact
send_data(client, "clock ! tick%d" % (tick))
File "test.py", line 25, in send_data
return client.send(str)
socket.error: [Errno 10053] An established connection was aborted by the softwar
e in your host machine
Press any key to continue . . .
Here is the Javascript...
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:1234");
ws.onopen = function() {
alert('opened');
ws.send("test");
}
ws.onmessage = function (evt) {
alert('hit');
$('#game').html(evt.data);
}
ws.onclose = function () {
$('#game').html('Lost Connection');
}
} else {
$('#game').html('No support');
}
Is anyone else running into this problem or does this appear to be a domain mismatch issue?
A:
I upgraded Chrome to a new build (4.0.302.3 dev) and now I am getting proper javascript errors in the console. It was indeed a domain mismatch error.
To anyone else getting this same issue, make sure to update your browser first and then check your urls.
|
After handshake of websocket, chrome disconnects. Is this due to domain mismatch? Or Chrome bug?
|
I made my own simple WebSocket server in Python but Chrome 4.0.249.78 dev (36714) ALWAYS disconnects after the handshake. To make sure it wasn't my code I used the WebSocket server found at https://stackoverflow.com/questions/2153294?tab=newest#tab-top to test it and got the same result (below).
listening...
connection!
GET / HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: localhost:1234
Origin: http://localhost
handshaken
got:
got:
Traceback (most recent call last):
File "test.py", line 44, in <module>
start_server()
File "test.py", line 18, in start_server
interact(csock, tick)
File "test.py", line 40, in interact
send_data(client, "clock ! tick%d" % (tick))
File "test.py", line 25, in send_data
return client.send(str)
socket.error: [Errno 10053] An established connection was aborted by the softwar
e in your host machine
Press any key to continue . . .
Here is the Javascript...
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:1234");
ws.onopen = function() {
alert('opened');
ws.send("test");
}
ws.onmessage = function (evt) {
alert('hit');
$('#game').html(evt.data);
}
ws.onclose = function () {
$('#game').html('Lost Connection');
}
} else {
$('#game').html('No support');
}
Is anyone else running into this problem or does this appear to be a domain mismatch issue?
|
[
"I upgraded Chrome to a new build (4.0.302.3 dev) and now I am getting proper javascript errors in the console. It was indeed a domain mismatch error.\nTo anyone else getting this same issue, make sure to update your browser first and then check your urls.\n"
] |
[
2
] |
[] |
[] |
[
"google_chrome",
"javascript",
"python",
"websocket"
] |
stackoverflow_0002165308_google_chrome_javascript_python_websocket.txt
|
Q:
Can I get my instance of mechanize.Browser to stay on the same page after calling b.form.submit()?
In Python's mechanize.Browser module, when you submit a form the browser instance goes to that page. For this one request, I don't want that; I want it just to stay on the page it's currently on and give me the response in another object (for looping purposes). Anyone know a quick to do this?
EDIT:
Hmm, so I have this kind of working with ClientForm.HTMLForm.click(), which returns a urllib2 request, but I need the cookies from mechanize's cookiejar to be used on my urllib2.urlopen request. Is there a method in mechanize that will let me send a request just like urllib2 with the exception that cookies will be imported?
A:
The answer to my immediate question in the headline is yes, with mechanize.Browser.open_novisit(). It works just like open(), but it doesn't change the state of the Browser instance -- that is, it will retrieve the page, and your Browser object will stay where it was.
|
Can I get my instance of mechanize.Browser to stay on the same page after calling b.form.submit()?
|
In Python's mechanize.Browser module, when you submit a form the browser instance goes to that page. For this one request, I don't want that; I want it just to stay on the page it's currently on and give me the response in another object (for looping purposes). Anyone know a quick to do this?
EDIT:
Hmm, so I have this kind of working with ClientForm.HTMLForm.click(), which returns a urllib2 request, but I need the cookies from mechanize's cookiejar to be used on my urllib2.urlopen request. Is there a method in mechanize that will let me send a request just like urllib2 with the exception that cookies will be imported?
|
[
"The answer to my immediate question in the headline is yes, with mechanize.Browser.open_novisit(). It works just like open(), but it doesn't change the state of the Browser instance -- that is, it will retrieve the page, and your Browser object will stay where it was.\n"
] |
[
7
] |
[] |
[] |
[
"mechanize",
"python",
"screen_scraping"
] |
stackoverflow_0002152098_mechanize_python_screen_scraping.txt
|
Q:
Alternative ways to browse the python api
Is it just me, or the python standard library documentation is extremely difficult to browse through?
http://docs.python.org/3.1/library/index.html
http://docs.python.org/3.1/modindex.html
Java has its brilliant Javadocs, Ruby has its helpful Ruby-Docs, only in python I cannot find a good way to navigate through the standard library documentation.
There's the Epydoc project, which looks nice, but does anyone know if it is actually being used on the standard library, so we can all go through it? If not, what are the alternatives people are using to browse python documentation.
A:
I usually use the built-in pydoc, if you are on windows it should be called Module Docs if you are on linux use pydoc -p 8000 and connect through browser.
A:
pydoc from the command line, help() from the interactive interpreter prompt.
A:
pydoc -p 8080
The python community is semi-hostile to automatically generated documentation, especially if it's Object-Orientated. Python isn't just object-orientated (it's a multi-paradigm language), so Python developers generally prefer human-written documentation. Sometimes the functions are important, sometimes the Class structure is important.
A:
you can go to here and download the chm version of Python 3.1. With that, searching through the docs should be easy.
A:
I used to use the python sidebar from Edgewall a long time ago.
These days, I google for the python function (the standard docs almost always show up as the first link).If I want to browse the source of the module (useful sometimes), I use this little shell function I wrote.
epy () {
cmd="import $1 as a ; print a.__file__.endswith('.pyc') and a.__file__[:-1] or a.__file__"
file=$(/usr/bin/env python -c $cmd)
echo $file
emacsclient --no-wait $file
}
A:
I guess I'm going to get downvoted but I find nothing wrong with the Sphinx docs and I find them way way better than the java alternative.
|
Alternative ways to browse the python api
|
Is it just me, or the python standard library documentation is extremely difficult to browse through?
http://docs.python.org/3.1/library/index.html
http://docs.python.org/3.1/modindex.html
Java has its brilliant Javadocs, Ruby has its helpful Ruby-Docs, only in python I cannot find a good way to navigate through the standard library documentation.
There's the Epydoc project, which looks nice, but does anyone know if it is actually being used on the standard library, so we can all go through it? If not, what are the alternatives people are using to browse python documentation.
|
[
"I usually use the built-in pydoc, if you are on windows it should be called Module Docs if you are on linux use pydoc -p 8000 and connect through browser.\n",
"pydoc from the command line, help() from the interactive interpreter prompt.\n",
"pydoc -p 8080\nThe python community is semi-hostile to automatically generated documentation, especially if it's Object-Orientated. Python isn't just object-orientated (it's a multi-paradigm language), so Python developers generally prefer human-written documentation. Sometimes the functions are important, sometimes the Class structure is important. \n",
"you can go to here and download the chm version of Python 3.1. With that, searching through the docs should be easy.\n",
"I used to use the python sidebar from Edgewall a long time ago. \nThese days, I google for the python function (the standard docs almost always show up as the first link).If I want to browse the source of the module (useful sometimes), I use this little shell function I wrote.\nepy () {\n cmd=\"import $1 as a ; print a.__file__.endswith('.pyc') and a.__file__[:-1] or a.__file__\" \n file=$(/usr/bin/env python -c $cmd) \n echo $file\n emacsclient --no-wait $file\n}\n\n",
"I guess I'm going to get downvoted but I find nothing wrong with the Sphinx docs and I find them way way better than the java alternative.\n"
] |
[
9,
3,
3,
2,
0,
0
] |
[] |
[] |
[
"documentation",
"python",
"standard_library"
] |
stackoverflow_0002131419_documentation_python_standard_library.txt
|
Q:
What is the use of the "-O" flag for running Python?
Python can run scripts in optimized mode (python -O) which turns off debugs, removes assert statements, and IIRC it also removes docstrings.
However, I have not seen it used. Is python -O actually used? If so, what for?
A:
python -O does the following currently:
completely ignores asserts
sets the special builtin name __debug__ to False (which by default is True)
and when called as python -OO
removes docstrings from the code
I don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.
A:
It saves a small amount of memory, and a small amount of disk space if you distribute any archive form containing only the .pyo files. (If you use assert a lot, and perhaps with complicated conditions, the savings can be not trivial and can extend to running time too).
So, it's definitely not useless -- and of course it's being used (if you deploy a Python-coded server program to a huge number N of server machines, why ever would you want to waste N * X bytes to keep docstrings which nobody, ever, would anyway be able to access?!). Of course it would be better if it saved even more, but, hey -- waste not, want not!-)
So it's pretty much a no-brainer to keep this functionality (which is in any case trivially simple to provide, you know;-) in Python 3 -- why add even "epsilon" to the latter's adoption difficulties?-)
A:
Prepacked software in different Linux distributions often comes byte-compiled with -O. For example, this if from Fedora packaging guidelines for python applications:
In the past it was common practice to %ghost .pyo files in order to save a small amount of space on the users filesystem. However, this has two issues: 1. With SELinux, if a user is running python -O [APP] it will try to write the .pyos when they don't exist. This leads to AVC denial records in the logs. 2. If the system administrator runs python -OO [APP] the .pyos will get created with no docstrings. Some programs require docstrings in order to function. On subsequent runs with python -O [APP] python will use the cached .pyos even though a different optimization level has been requested. The only way to fix this is to find out where the .pyos are and delete them.
The current method of dealing with pyo files is to include them as is, no %ghosting.
A:
Removing assertions means a small performance benefit, so you could use this for "release" code. Anyway nobody uses it because many Python libraries are open sourced and thus the help() function should work.
So, as long as there isn't any real optimization in this mode, you can ignore it.
|
What is the use of the "-O" flag for running Python?
|
Python can run scripts in optimized mode (python -O) which turns off debugs, removes assert statements, and IIRC it also removes docstrings.
However, I have not seen it used. Is python -O actually used? If so, what for?
|
[
"python -O does the following currently:\n\ncompletely ignores asserts\nsets the special builtin name __debug__ to False (which by default is True)\n\nand when called as python -OO\n\nremoves docstrings from the code\n\nI don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.\n",
"It saves a small amount of memory, and a small amount of disk space if you distribute any archive form containing only the .pyo files. (If you use assert a lot, and perhaps with complicated conditions, the savings can be not trivial and can extend to running time too).\nSo, it's definitely not useless -- and of course it's being used (if you deploy a Python-coded server program to a huge number N of server machines, why ever would you want to waste N * X bytes to keep docstrings which nobody, ever, would anyway be able to access?!). Of course it would be better if it saved even more, but, hey -- waste not, want not!-)\nSo it's pretty much a no-brainer to keep this functionality (which is in any case trivially simple to provide, you know;-) in Python 3 -- why add even \"epsilon\" to the latter's adoption difficulties?-)\n",
"Prepacked software in different Linux distributions often comes byte-compiled with -O. For example, this if from Fedora packaging guidelines for python applications:\n\nIn the past it was common practice to %ghost .pyo files in order to save a small amount of space on the users filesystem. However, this has two issues: 1. With SELinux, if a user is running python -O [APP] it will try to write the .pyos when they don't exist. This leads to AVC denial records in the logs. 2. If the system administrator runs python -OO [APP] the .pyos will get created with no docstrings. Some programs require docstrings in order to function. On subsequent runs with python -O [APP] python will use the cached .pyos even though a different optimization level has been requested. The only way to fix this is to find out where the .pyos are and delete them.\nThe current method of dealing with pyo files is to include them as is, no %ghosting.\n\n",
"Removing assertions means a small performance benefit, so you could use this for \"release\" code. Anyway nobody uses it because many Python libraries are open sourced and thus the help() function should work.\nSo, as long as there isn't any real optimization in this mode, you can ignore it.\n"
] |
[
62,
52,
7,
3
] |
[] |
[] |
[
"assert",
"assertion",
"python"
] |
stackoverflow_0002055557_assert_assertion_python.txt
|
Q:
pubDate RSS parsing weirdness with Beautifulsoup/Python
I'm trying to parse an RSS/Podcast feed using Beautifulsoup and everything is working nicely except I can't seem to parse the 'pubDate' field.
data = urllib2.urlopen("http://www.democracynow.org/podcast.xml")
dom = BeautifulStoneSoup(data, fromEncoding='utf-8')
items = dom.findAll('item');
for item in items:
title = item.find('title').string.strip()
pubDate = item.find('pubDate').string.strip()
The title gets parsed fine but when it gets to pubDate, it says:
Traceback (most recent call last):
File "", line 2, in
AttributeError: 'NoneType' object has no attribute 'string'
However, when I download a copy of the XML file and rename 'pubDate' to something else, then parse it again, it seems to work. Is pubDate a reserved variable or something in Python?
Thanks,
g
A:
It works with item.find('pubdate').string.strip().
Why don't you use feedparser ?
|
pubDate RSS parsing weirdness with Beautifulsoup/Python
|
I'm trying to parse an RSS/Podcast feed using Beautifulsoup and everything is working nicely except I can't seem to parse the 'pubDate' field.
data = urllib2.urlopen("http://www.democracynow.org/podcast.xml")
dom = BeautifulStoneSoup(data, fromEncoding='utf-8')
items = dom.findAll('item');
for item in items:
title = item.find('title').string.strip()
pubDate = item.find('pubDate').string.strip()
The title gets parsed fine but when it gets to pubDate, it says:
Traceback (most recent call last):
File "", line 2, in
AttributeError: 'NoneType' object has no attribute 'string'
However, when I download a copy of the XML file and rename 'pubDate' to something else, then parse it again, it seems to work. Is pubDate a reserved variable or something in Python?
Thanks,
g
|
[
"It works with item.find('pubdate').string.strip().\nWhy don't you use feedparser ?\n"
] |
[
3
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0002168516_beautifulsoup_python.txt
|
Q:
python string split
I am trying to recognise user typed strings such as "exit" or "add number" using this:
command, data = input('>').split(" ", 1)
It works for two word input, but not one word of input ("need more than 1 value to unpack").
What is the best way of accepting both one/two word inputs?
A:
This is what partition is for:
command, _, data = raw_input('>').partition(" ")
If only one word was specified, data will be assigned an empty string.
A:
I am certain that someone is going to come up with a "Pythonic" solution, but what ever happened to just accepting it as a list and checking it afterward?
command_data = raw_input('>').split(" ", 1)
if len(command_data) > 1:
do some brilliant stuff next
Sorry, I think the C++ side of my brain is getting moody :)
Edit: Maybe str.partition is what you're looking for. At least you're guaranteed a 3-tuple to unpack. Mind you if you ever add a second argument to the command you'll have to find a new solution.
A:
The best way is to build a parser, but if you just want something to work quickly you could just have a list of the commands you want to allow, such as:
commands = ['foo', 'bar', 'exit', 'hello world', 'add number']
Then for each command check if your input satisfies s.startswith(command). If so, you can do the appropriate thing for that command.
A:
line = raw_input('>').split(" ", 1)
command = line[0]
data = line[1] if len(line) > 1 else ""
Make sure you use raw_input if you don't want your data being evaluated as a Python expression.
A:
command, data = (input('>') + ' ').split(" ", 1)
|
python string split
|
I am trying to recognise user typed strings such as "exit" or "add number" using this:
command, data = input('>').split(" ", 1)
It works for two word input, but not one word of input ("need more than 1 value to unpack").
What is the best way of accepting both one/two word inputs?
|
[
"This is what partition is for:\ncommand, _, data = raw_input('>').partition(\" \")\n\nIf only one word was specified, data will be assigned an empty string.\n",
"I am certain that someone is going to come up with a \"Pythonic\" solution, but what ever happened to just accepting it as a list and checking it afterward?\ncommand_data = raw_input('>').split(\" \", 1)\nif len(command_data) > 1:\n do some brilliant stuff next\n\nSorry, I think the C++ side of my brain is getting moody :)\nEdit: Maybe str.partition is what you're looking for. At least you're guaranteed a 3-tuple to unpack. Mind you if you ever add a second argument to the command you'll have to find a new solution.\n",
"The best way is to build a parser, but if you just want something to work quickly you could just have a list of the commands you want to allow, such as:\ncommands = ['foo', 'bar', 'exit', 'hello world', 'add number']\n\nThen for each command check if your input satisfies s.startswith(command). If so, you can do the appropriate thing for that command.\n",
"line = raw_input('>').split(\" \", 1)\ncommand = line[0]\ndata = line[1] if len(line) > 1 else \"\"\n\nMake sure you use raw_input if you don't want your data being evaluated as a Python expression.\n",
"command, data = (input('>') + ' ').split(\" \", 1)\n\n"
] |
[
3,
2,
2,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002168522_python.txt
|
Q:
How can I pickle suds results?
To avoid repeatedly accessing a SOAP server during development, I'm trying to cache the results so I can run the rest of my code without querying the server each time.
With the code below I get a PicklingError: Can't pickle <class suds.sudsobject.AdvertiserSearchResponse at 0x03424060>: it's not found as suds.sudsobject.AdvertiserSearchResponse when I try to pickle a suds result. I guess this is because the classes are dynamically created.
import pickle
from suds.client import Client
client = Client(...)
result = client.service.search(...)
file = open('test_pickle.dat', 'wb')
pickle.dump(result, file, -1)
file.close()
If I drop the -1 protocol version from pickle.dump(result, file, -1), I get a different error:
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled
Is pickling the right thing to do? Can I make it work? Is there a better way?
A:
As the error message you're currently getting is trying to tell you, you're trying to pickle instances that are not picklable (in the ancient legacy pickle protocol you're now using) because their class defines __slots__ but not a __getstate__ method.
However, even altering their class would not help because then you'd run into the other problem -- which you already correctly identified as being likely due to dynamically generated classes. All pickle protocols serialize classes (and functions) "by name", essentially constraining them to be at top-level names in their modules. And, serializing an instance absolutely does require serializing the class (how else could you possibly reconstruct the instance later if the class was not around?!).
So you'll need to save and reload your data in some other way, breaking your current direct dependence on concrete classes in suds.sudsobject in favor of depending on an interface (either formalized or just defined by duck typing) that can be implemented both by such concrete classes when you are in fact accessing the SOAP server, or simpler "homemade" ones when you're loading the data from a file. (The data representing instance state can no doubt be represented as a dict, so you can force it through pickle if you really want, e.g. via the copy_reg module which allows you to customize serialize/deserialize protocols for objects that you're forced to treat non-invasively [[so you can't go around adding __getstate__ or the like to their classes]] -- the problem will come only if there's a rich mesh of mutual references among such objects).
A:
You are pickling the class object itself, and not instance objects of the class. This won't work if the class object is recreated. However, pickling instances of the class will work as long as the class object exists.
|
How can I pickle suds results?
|
To avoid repeatedly accessing a SOAP server during development, I'm trying to cache the results so I can run the rest of my code without querying the server each time.
With the code below I get a PicklingError: Can't pickle <class suds.sudsobject.AdvertiserSearchResponse at 0x03424060>: it's not found as suds.sudsobject.AdvertiserSearchResponse when I try to pickle a suds result. I guess this is because the classes are dynamically created.
import pickle
from suds.client import Client
client = Client(...)
result = client.service.search(...)
file = open('test_pickle.dat', 'wb')
pickle.dump(result, file, -1)
file.close()
If I drop the -1 protocol version from pickle.dump(result, file, -1), I get a different error:
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled
Is pickling the right thing to do? Can I make it work? Is there a better way?
|
[
"As the error message you're currently getting is trying to tell you, you're trying to pickle instances that are not picklable (in the ancient legacy pickle protocol you're now using) because their class defines __slots__ but not a __getstate__ method.\nHowever, even altering their class would not help because then you'd run into the other problem -- which you already correctly identified as being likely due to dynamically generated classes. All pickle protocols serialize classes (and functions) \"by name\", essentially constraining them to be at top-level names in their modules. And, serializing an instance absolutely does require serializing the class (how else could you possibly reconstruct the instance later if the class was not around?!).\nSo you'll need to save and reload your data in some other way, breaking your current direct dependence on concrete classes in suds.sudsobject in favor of depending on an interface (either formalized or just defined by duck typing) that can be implemented both by such concrete classes when you are in fact accessing the SOAP server, or simpler \"homemade\" ones when you're loading the data from a file. (The data representing instance state can no doubt be represented as a dict, so you can force it through pickle if you really want, e.g. via the copy_reg module which allows you to customize serialize/deserialize protocols for objects that you're forced to treat non-invasively [[so you can't go around adding __getstate__ or the like to their classes]] -- the problem will come only if there's a rich mesh of mutual references among such objects).\n",
"You are pickling the class object itself, and not instance objects of the class. This won't work if the class object is recreated. However, pickling instances of the class will work as long as the class object exists.\n"
] |
[
9,
3
] |
[] |
[] |
[
"pickle",
"python",
"soap",
"suds"
] |
stackoverflow_0002167894_pickle_python_soap_suds.txt
|
Q:
What vim plugins mix results in this interface
I saw this VIM UI and thought it was awesome and now I want it. Anyone know what plugins the author is using?
http://werkzeug.pocoo.org/wiki30/files/wiki30.mp4
A:
A bit dated, but this is his blog post that I was referring to: Vim as Development Environment
|
What vim plugins mix results in this interface
|
I saw this VIM UI and thought it was awesome and now I want it. Anyone know what plugins the author is using?
http://werkzeug.pocoo.org/wiki30/files/wiki30.mp4
|
[
"A bit dated, but this is his blog post that I was referring to: Vim as Development Environment\n"
] |
[
0
] |
[] |
[] |
[
"ide",
"plugins",
"python",
"vim"
] |
stackoverflow_0002166201_ide_plugins_python_vim.txt
|
Q:
How can I add a cookie to an existing cookielib CookieJar instance in Python?
I have a CookieJar that's being used with Mechanize that I want to add a cookie to. How can I go about doing this?
make_cookie() and set_cookie() weren't clear enough for me.
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
A:
I managed to figure this out:
import mechanize
import cookielib
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
ck = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
cj.set_cookie(ck)
for index, cookie in enumerate(cj):
print index, ' : ', cookie
Output:
0 : <Cookie Name=1 for www.example.com/>
|
How can I add a cookie to an existing cookielib CookieJar instance in Python?
|
I have a CookieJar that's being used with Mechanize that I want to add a cookie to. How can I go about doing this?
make_cookie() and set_cookie() weren't clear enough for me.
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
|
[
"I managed to figure this out:\nimport mechanize\nimport cookielib\n\nbr = mechanize.Browser()\ncj = cookielib.LWPCookieJar()\nbr.set_cookiejar(cj)\nck = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)\ncj.set_cookie(ck)\nfor index, cookie in enumerate(cj):\n print index, ' : ', cookie\n\nOutput:\n0 : <Cookie Name=1 for www.example.com/>\n\n"
] |
[
37
] |
[] |
[] |
[
"cookiejar",
"cookielib",
"cookies",
"mechanize",
"python"
] |
stackoverflow_0002169281_cookiejar_cookielib_cookies_mechanize_python.txt
|
Q:
Ignoring case, punctuation, and whitespace in Strings
What is the most efficient way of ignoring case, punctuation, and whitespace in strings? These strings should be divided into words instead of characters should ignore the aforementioned details on comparisons, and slices of these word-strings should be as efficient as possible with speed in mind.
I was going to use case and punctuation insensitive strings for the following code, but after seeing how long it would take to evaluate class Slice: def __eq__(self, other): return self.root == other.root, I have decided to work with data = tuple(string.split()) instead. Having strings that are insensitive to case, punctuation, and spacing and that work over words instead of characters was too expensive into the computationally expensive algorithms already expressed in the code below.
class Slice:
def __init__(self, data, offset, length):
self.prefix = data[:offset]
self.root = data[offset:offset+length]
self.suffix = data[offset+length:]
def __eq__(self, other):
return self.root == other.root
def __len__(self):
return len(self.root)
################################################################################
class Match:
def __init__(self, data, key, prefix_tree, suffix_tree):
self.data = data
self.key = key
self.prefix_tree = prefix_tree
self.suffix_tree = suffix_tree
self.__value = len(key) + prefix_tree.value() + suffix_tree.value()
def value(self):
return self.__value
################################################################################
class Tree(tuple):
def __new__(cls, nodes):
tree = super().__new__(cls, nodes)
tree.__value = max(map(Match.value, tree)) if tree else 0
return tree
def value(self):
return self.__value
def find(self, value):
for index, match in enumerate(self):
if match.value() == value:
return index
raise ValueError()
################################################################################
def search(data, key):
length = 0
nodes = []
for d_block in shrink(data, len(key)):
block_len = len(d_block)
if length > block_len:
return Tree(nodes)
for k_block in slide(key, block_len):
if d_block == k_block:
length = block_len
prefix_tree = search(d_block.prefix, k_block.prefix)
suffix_tree = search(d_block.suffix, k_block.suffix)
match = Match(d_block, k_block, prefix_tree, suffix_tree)
nodes.append(match)
return Tree(nodes)
def shrink(data, max_len):
for length in range(min(len(data), max_len), 0, -1):
for block in slide(data, length):
yield block
def slide(data, length):
for offset in range(len(data) - length + 1):
yield Slice(data, offset, length)
################################################################################
def build_tree(nodes):
match = nodes[nodes.find(nodes.value())]
node = match.key
if match.prefix_tree:
node.prefix = build_tree(match.prefix_tree)
if match.suffix_tree:
node.suffix = build_tree(match.suffix_tree)
return node
def flatten_tree(node):
array = [0]
_flatten(node, array)
return tuple(array)
def _flatten(node, array):
if isinstance(node.prefix, Slice):
_flatten(node.prefix, array)
else:
array.append(node.prefix)
array[0] += 1
array.append((array[0], node.root))
if isinstance(node.suffix, Slice):
_flatten(node.suffix, array)
else:
array.append(node.suffix)
A:
If you want iteration on a String instance to iterate on its self.__string, as your __iter__ method indicates, the only sensible choice for length is also to return the length of __string -- it would be truly peculiar if len(x) and sum(1 for _ in x) resulted in different values.
I have to admit I don't understand the purpose of this class (and in particular why you made the terrible choice of having it old-style, and why you use such a contorted way to build __simple), but internal consistency is important anyway. So, either change __iter__, or make __len__ logically compatible with it.
Your slicing logic also totally escapes me -- why are you building the slice's __simple in a way that's likely to be different from what you'd get by rebuilding it from the slice's __string? E.g., if self.__string is '?Boh!' and therefore self.__simple is 'boh', why would you want self[1:-1] to have a __string of 'Boh' but with a __simple of 'o', so incompatible, different, and inconsistent from the __simple you'd get by recomputing it from the slice...?
I guess that's not germane to this Q about length, but I'm just curious about these many, extremely peculiar design choices that you're making...
A:
"What is the best way to go about fixing this problem?"
The best -- and only -- way is to define what this object "means" and what the length of this object "means".
The object appears to be a list of words. Nothing more. That seems to be the value in _string.
It's not clear what _simple is, other than an inaccessible filtered subset of the words in _string.
So what's the length? The length of the words or the length of the words in the filtered subset?
Only you can define what this class means. The meaning will then determine how to implement __len__. Until you define the meaning, it's impossible to determine how anything should be implemented.
|
Ignoring case, punctuation, and whitespace in Strings
|
What is the most efficient way of ignoring case, punctuation, and whitespace in strings? These strings should be divided into words instead of characters should ignore the aforementioned details on comparisons, and slices of these word-strings should be as efficient as possible with speed in mind.
I was going to use case and punctuation insensitive strings for the following code, but after seeing how long it would take to evaluate class Slice: def __eq__(self, other): return self.root == other.root, I have decided to work with data = tuple(string.split()) instead. Having strings that are insensitive to case, punctuation, and spacing and that work over words instead of characters was too expensive into the computationally expensive algorithms already expressed in the code below.
class Slice:
def __init__(self, data, offset, length):
self.prefix = data[:offset]
self.root = data[offset:offset+length]
self.suffix = data[offset+length:]
def __eq__(self, other):
return self.root == other.root
def __len__(self):
return len(self.root)
################################################################################
class Match:
def __init__(self, data, key, prefix_tree, suffix_tree):
self.data = data
self.key = key
self.prefix_tree = prefix_tree
self.suffix_tree = suffix_tree
self.__value = len(key) + prefix_tree.value() + suffix_tree.value()
def value(self):
return self.__value
################################################################################
class Tree(tuple):
def __new__(cls, nodes):
tree = super().__new__(cls, nodes)
tree.__value = max(map(Match.value, tree)) if tree else 0
return tree
def value(self):
return self.__value
def find(self, value):
for index, match in enumerate(self):
if match.value() == value:
return index
raise ValueError()
################################################################################
def search(data, key):
length = 0
nodes = []
for d_block in shrink(data, len(key)):
block_len = len(d_block)
if length > block_len:
return Tree(nodes)
for k_block in slide(key, block_len):
if d_block == k_block:
length = block_len
prefix_tree = search(d_block.prefix, k_block.prefix)
suffix_tree = search(d_block.suffix, k_block.suffix)
match = Match(d_block, k_block, prefix_tree, suffix_tree)
nodes.append(match)
return Tree(nodes)
def shrink(data, max_len):
for length in range(min(len(data), max_len), 0, -1):
for block in slide(data, length):
yield block
def slide(data, length):
for offset in range(len(data) - length + 1):
yield Slice(data, offset, length)
################################################################################
def build_tree(nodes):
match = nodes[nodes.find(nodes.value())]
node = match.key
if match.prefix_tree:
node.prefix = build_tree(match.prefix_tree)
if match.suffix_tree:
node.suffix = build_tree(match.suffix_tree)
return node
def flatten_tree(node):
array = [0]
_flatten(node, array)
return tuple(array)
def _flatten(node, array):
if isinstance(node.prefix, Slice):
_flatten(node.prefix, array)
else:
array.append(node.prefix)
array[0] += 1
array.append((array[0], node.root))
if isinstance(node.suffix, Slice):
_flatten(node.suffix, array)
else:
array.append(node.suffix)
|
[
"If you want iteration on a String instance to iterate on its self.__string, as your __iter__ method indicates, the only sensible choice for length is also to return the length of __string -- it would be truly peculiar if len(x) and sum(1 for _ in x) resulted in different values.\nI have to admit I don't understand the purpose of this class (and in particular why you made the terrible choice of having it old-style, and why you use such a contorted way to build __simple), but internal consistency is important anyway. So, either change __iter__, or make __len__ logically compatible with it.\nYour slicing logic also totally escapes me -- why are you building the slice's __simple in a way that's likely to be different from what you'd get by rebuilding it from the slice's __string? E.g., if self.__string is '?Boh!' and therefore self.__simple is 'boh', why would you want self[1:-1] to have a __string of 'Boh' but with a __simple of 'o', so incompatible, different, and inconsistent from the __simple you'd get by recomputing it from the slice...?\nI guess that's not germane to this Q about length, but I'm just curious about these many, extremely peculiar design choices that you're making...\n",
"\"What is the best way to go about fixing this problem?\"\nThe best -- and only -- way is to define what this object \"means\" and what the length of this object \"means\".\nThe object appears to be a list of words. Nothing more. That seems to be the value in _string.\nIt's not clear what _simple is, other than an inaccessible filtered subset of the words in _string.\nSo what's the length? The length of the words or the length of the words in the filtered subset?\nOnly you can define what this class means. The meaning will then determine how to implement __len__. Until you define the meaning, it's impossible to determine how anything should be implemented.\n"
] |
[
2,
2
] |
[] |
[] |
[
"filter",
"python",
"slice",
"state"
] |
stackoverflow_0002169170_filter_python_slice_state.txt
|
Q:
Importing _mysql in MySQLdb
Why is _mysql in the MySQLdb module a C file? When the module tries to import it, I get an import error. What should I do?
A:
It's the adaptor that sits between the Python MySQLdb module and the C libmysqlclient library. One of the most common reasons for it not loading is that the appropriate libmysqlclient library is not in place.
A:
Edit: This might be the answer to your question.
When I try to import _mysql, I get no error:
import _mysql
print(_mysql)
# <module '_mysql' from '/usr/lib/pymodules/python2.6/_mysql.so'>
It is importing the library /usr/lib/pymodules/python2.6/_mysql.so
If this is not what you are getting, it sounds like an installation error.
What OS are you using?
How did you install mysqldb?
|
Importing _mysql in MySQLdb
|
Why is _mysql in the MySQLdb module a C file? When the module tries to import it, I get an import error. What should I do?
|
[
"It's the adaptor that sits between the Python MySQLdb module and the C libmysqlclient library. One of the most common reasons for it not loading is that the appropriate libmysqlclient library is not in place.\n",
"Edit: This might be the answer to your question.\nWhen I try to import _mysql, I get no error:\nimport _mysql\nprint(_mysql)\n# <module '_mysql' from '/usr/lib/pymodules/python2.6/_mysql.so'>\n\nIt is importing the library /usr/lib/pymodules/python2.6/_mysql.so\nIf this is not what you are getting, it sounds like an installation error.\nWhat OS are you using?\nHow did you install mysqldb?\n"
] |
[
0,
0
] |
[] |
[] |
[
"c",
"mysql",
"python"
] |
stackoverflow_0002169449_c_mysql_python.txt
|
Q:
how to write a file correctly after editing
say i encrypt a .doc (or any other type) file and i decrypt it later. however, i cant open it because during the decryption process, [null]s and [DC1] and other highlighted chars were not put back into the file since they are not part of the ASCII characters. how are they written in other programs that compress/encrypt/edit/etc?
im doing this in python, so normally, without editing, i can do:
file1 = open(file,'rb').read()
file2 = open(new_file,'wb')
file2.write(file1)
but this doesnt work if i encrypt and decrypt
A:
Nulls and DC1's and so on are definitely part of the ASCII character set, so I don't know what you're talking about. So, for example, consider...:
>>> import pyDes
>>> f = open('afile', 'w')
>>> f.write('Nel mezzo del cammin di nostra vita\n')
>>> f.close()
>>> data = open('afile').read()
>>> encrypted = pyDes.des('mysecret').encrypt(data, padmode=pyDes.PAD_PKCS5)
>>> f = open('encryp', 'wb')
>>> f.write(encrypted)
>>> f.close()
>>> encdata = open('encryp', 'rb').read()
>>> decrypted = pyDes.des('mysecret').decrypt(encdata)
>>> decrypted
'Nel mezzo del cammin di nostra vita\n\x04\x04\x04\x04'
Whatever encryption you're using (pyDes or other) isn't this exactly the kind of thing you're claiming is NOT working...?!
If you're hoping to get help diagnosing the bugs in your code, you'd better post that buggy code, rather than generic descriptions that just don't give enough info to understand your bugs.
A:
What encryption are you using?
Proper encryption will also encrypt non ascii characters so they can be decrypted properly later
|
how to write a file correctly after editing
|
say i encrypt a .doc (or any other type) file and i decrypt it later. however, i cant open it because during the decryption process, [null]s and [DC1] and other highlighted chars were not put back into the file since they are not part of the ASCII characters. how are they written in other programs that compress/encrypt/edit/etc?
im doing this in python, so normally, without editing, i can do:
file1 = open(file,'rb').read()
file2 = open(new_file,'wb')
file2.write(file1)
but this doesnt work if i encrypt and decrypt
|
[
"Nulls and DC1's and so on are definitely part of the ASCII character set, so I don't know what you're talking about. So, for example, consider...:\n>>> import pyDes\n>>> f = open('afile', 'w')\n>>> f.write('Nel mezzo del cammin di nostra vita\\n')\n>>> f.close()\n>>> data = open('afile').read()\n>>> encrypted = pyDes.des('mysecret').encrypt(data, padmode=pyDes.PAD_PKCS5)\n>>> f = open('encryp', 'wb')\n>>> f.write(encrypted)\n>>> f.close()\n>>> encdata = open('encryp', 'rb').read()\n>>> decrypted = pyDes.des('mysecret').decrypt(encdata)\n>>> decrypted\n'Nel mezzo del cammin di nostra vita\\n\\x04\\x04\\x04\\x04'\n\nWhatever encryption you're using (pyDes or other) isn't this exactly the kind of thing you're claiming is NOT working...?!\nIf you're hoping to get help diagnosing the bugs in your code, you'd better post that buggy code, rather than generic descriptions that just don't give enough info to understand your bugs. \n",
"What encryption are you using?\nProper encryption will also encrypt non ascii characters so they can be decrypted properly later\n"
] |
[
4,
1
] |
[] |
[] |
[
"encryption",
"python"
] |
stackoverflow_0002169445_encryption_python.txt
|
Q:
Polymorphism - adding to existing methods while overwriting them
I want to be able to subclass a class, and define __init__ but still run the old __init__ as well.
To illustrate, say I have the following classes:
class A(object):
def __init__(self):
self.var1 = 1
class B(A):
def __init__(self)
self.var2 = 2
doInitForA()
And I want to be able to do this:
instB = B()
print (instB.var1) #1
print (instB.var2) #2
Edited as Ignacio Vazquez-Abrams suggested. (Is it possible to edit without bumping?)
A:
replace
doInitForA()
with
super(b, self).__init__()
A:
You might want to look at this question: Chain-calling parent constructors in python, specifically use the super(b, self).__init__() method.
A:
Either call a.__init__(self) or derive a from object and use super().
A:
class a:
def __init__(self):
self.var1 = 1
class b(a):
def __init__(self)
self.var2 = 2
a.__init__(self)
You can even write super().__init__() if you are using python 3.
See this question about the use of super().
A:
Call your father's c'tor from within your c'tor: a.__init__(self). Note that you need to pass self as first parameter. If the parent c'tor takes more parameters, pass them after self.
|
Polymorphism - adding to existing methods while overwriting them
|
I want to be able to subclass a class, and define __init__ but still run the old __init__ as well.
To illustrate, say I have the following classes:
class A(object):
def __init__(self):
self.var1 = 1
class B(A):
def __init__(self)
self.var2 = 2
doInitForA()
And I want to be able to do this:
instB = B()
print (instB.var1) #1
print (instB.var2) #2
Edited as Ignacio Vazquez-Abrams suggested. (Is it possible to edit without bumping?)
|
[
"replace \ndoInitForA()\n\nwith\nsuper(b, self).__init__()\n\n",
"You might want to look at this question: Chain-calling parent constructors in python, specifically use the super(b, self).__init__() method.\n",
"Either call a.__init__(self) or derive a from object and use super().\n",
"class a:\n def __init__(self):\n self.var1 = 1\n\nclass b(a):\n def __init__(self)\n self.var2 = 2\n a.__init__(self)\n\nYou can even write super().__init__() if you are using python 3.\nSee this question about the use of super().\n",
"Call your father's c'tor from within your c'tor: a.__init__(self). Note that you need to pass self as first parameter. If the parent c'tor takes more parameters, pass them after self.\n"
] |
[
6,
3,
0,
0,
0
] |
[] |
[] |
[
"methods",
"polymorphism",
"python"
] |
stackoverflow_0002169947_methods_polymorphism_python.txt
|
Q:
assigning points to bins
What is a good way to bin numerical values into a certain range? For example, suppose I have a list of values and I want to bin them into N bins by their range. Right now, I do something like this:
from scipy import *
num_bins = 3 # number of bins to use
values = # some array of integers...
min_val = min(values) - 1
max_val = max(values) + 1
my_bins = linspace(min_val, max_val, num_bins)
# assign point to my bins
for v in values:
best_bin = min_index(abs(my_bins - v))
where min_index returns the index of the minimum value. The idea is that you can find the bin the point falls into by seeing what bin it has the smallest difference with.
But I think this has weird edge cases. What I am looking for is a good representation of bins, ideally ones that are half closed half open (so that there is no way of assigning one point to two bins), i.e.
bin1 = [x1, x2)
bin2 = [x2, x3)
bin3 = [x3, x4)
etc...
what is a good way to do this in Python, using numpy/scipy? I am only concerned here with binning integer values.
thanks very much for your help.
A:
numpy.histogram() does exactly what you want.
The function signature is:
numpy.histogram(a, bins=10, range=None, normed=False, weights=None, new=None)
We're mostly interested in a and bins. a is the input data that needs to be binned. bins can be a number of bins (your num_bins), or it can be a sequence of scalars, which denote bin edges (half open).
import numpy
values = numpy.arange(10, dtype=int)
bins = numpy.arange(-1, 11)
freq, bins = numpy.histogram(values, bins)
# freq is now [0 1 1 1 1 1 1 1 1 1 1]
# bins is unchanged
To quote the documentation:
All but the last (righthand-most) bin is half-open. In other words, if bins is:
[1, 2, 3, 4]
then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.
Edit: You want to know the index in your bins of each element. For this, you can use numpy.digitize(). If your bins are going to be integral, you can use numpy.bincount() as well.
>>> values = numpy.random.randint(0, 20, 10)
>>> values
array([17, 14, 9, 7, 6, 9, 19, 4, 2, 19])
>>> bins = numpy.linspace(-1, 21, 23)
>>> bins
array([ -1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,
10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20.,
21.])
>>> pos = numpy.digitize(values, bins)
>>> pos
array([19, 16, 11, 9, 8, 11, 21, 6, 4, 21])
Since the interval is open on the upper limit, the indices are correct:
>>> (bins[pos-1] == values).all()
True
>>> import sys
>>> for n in range(len(values)):
... sys.stdout.write("%g <= %g < %g\n"
... %(bins[pos[n]-1], values[n], bins[pos[n]]))
17 <= 17 < 18
14 <= 14 < 15
9 <= 9 < 10
7 <= 7 < 8
6 <= 6 < 7
9 <= 9 < 10
19 <= 19 < 20
4 <= 4 < 5
2 <= 2 < 3
19 <= 19 < 20
A:
This is fairly straightforward in numpy using broadcasting--my example below is four lines of code (not counting first two lines to create bins and data points, which would of course ordinarily be supplied.)
import numpy as NP
# just creating 5 bins at random, each bin expressed as (x, y, z) although, this code
# is not limited by bin number or bin dimension
bins = NP.random.random_integers(10, 99, 15).reshape(5, 3)
# creating 30 random data points
data = NP.random.random_integers(10, 99, 90).reshape(30, 3)
# for each data point i want the nearest bin, but before i can generate a distance
# matrix, i need to 'conform' the array dimensions
# 'broadcasting' is an excellent and concise way to do this
bins = bins[:, NP.newaxis, :]
data2 = data[NP.newaxis, :, :]
# now i can calculate the distance matrix
dist_matrix = NP.sqrt(NP.sum((data - bins)**2, axis=-1))
bin_assignments = NP.argmin(dist_matrix, axis=0)
'bin_assignments' is a 1d array of indices comprised of integer values from 0 to 4, corresponding to the five bins--the bin assignments for each of the 30 original points in the 'data' matrix above.
|
assigning points to bins
|
What is a good way to bin numerical values into a certain range? For example, suppose I have a list of values and I want to bin them into N bins by their range. Right now, I do something like this:
from scipy import *
num_bins = 3 # number of bins to use
values = # some array of integers...
min_val = min(values) - 1
max_val = max(values) + 1
my_bins = linspace(min_val, max_val, num_bins)
# assign point to my bins
for v in values:
best_bin = min_index(abs(my_bins - v))
where min_index returns the index of the minimum value. The idea is that you can find the bin the point falls into by seeing what bin it has the smallest difference with.
But I think this has weird edge cases. What I am looking for is a good representation of bins, ideally ones that are half closed half open (so that there is no way of assigning one point to two bins), i.e.
bin1 = [x1, x2)
bin2 = [x2, x3)
bin3 = [x3, x4)
etc...
what is a good way to do this in Python, using numpy/scipy? I am only concerned here with binning integer values.
thanks very much for your help.
|
[
"numpy.histogram() does exactly what you want.\nThe function signature is:\nnumpy.histogram(a, bins=10, range=None, normed=False, weights=None, new=None)\n\nWe're mostly interested in a and bins. a is the input data that needs to be binned. bins can be a number of bins (your num_bins), or it can be a sequence of scalars, which denote bin edges (half open).\nimport numpy\nvalues = numpy.arange(10, dtype=int)\nbins = numpy.arange(-1, 11)\nfreq, bins = numpy.histogram(values, bins)\n# freq is now [0 1 1 1 1 1 1 1 1 1 1]\n# bins is unchanged\n\nTo quote the documentation:\n\nAll but the last (righthand-most) bin is half-open. In other words, if bins is:\n[1, 2, 3, 4]\n\nthen the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.\n\nEdit: You want to know the index in your bins of each element. For this, you can use numpy.digitize(). If your bins are going to be integral, you can use numpy.bincount() as well.\n>>> values = numpy.random.randint(0, 20, 10)\n>>> values\narray([17, 14, 9, 7, 6, 9, 19, 4, 2, 19])\n>>> bins = numpy.linspace(-1, 21, 23)\n>>> bins\narray([ -1., 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.,\n 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20.,\n 21.])\n>>> pos = numpy.digitize(values, bins)\n>>> pos\narray([19, 16, 11, 9, 8, 11, 21, 6, 4, 21])\n\nSince the interval is open on the upper limit, the indices are correct:\n>>> (bins[pos-1] == values).all()\nTrue\n>>> import sys\n>>> for n in range(len(values)):\n... sys.stdout.write(\"%g <= %g < %g\\n\"\n... %(bins[pos[n]-1], values[n], bins[pos[n]]))\n17 <= 17 < 18\n14 <= 14 < 15\n9 <= 9 < 10\n7 <= 7 < 8\n6 <= 6 < 7\n9 <= 9 < 10\n19 <= 19 < 20\n4 <= 4 < 5\n2 <= 2 < 3\n19 <= 19 < 20\n\n",
"This is fairly straightforward in numpy using broadcasting--my example below is four lines of code (not counting first two lines to create bins and data points, which would of course ordinarily be supplied.) \nimport numpy as NP\n# just creating 5 bins at random, each bin expressed as (x, y, z) although, this code\n# is not limited by bin number or bin dimension\nbins = NP.random.random_integers(10, 99, 15).reshape(5, 3) \n# creating 30 random data points\ndata = NP.random.random_integers(10, 99, 90).reshape(30, 3)\n# for each data point i want the nearest bin, but before i can generate a distance\n# matrix, i need to 'conform' the array dimensions\n# 'broadcasting' is an excellent and concise way to do this\nbins = bins[:, NP.newaxis, :]\ndata2 = data[NP.newaxis, :, :]\n# now i can calculate the distance matrix\ndist_matrix = NP.sqrt(NP.sum((data - bins)**2, axis=-1)) \nbin_assignments = NP.argmin(dist_matrix, axis=0)\n\n'bin_assignments' is a 1d array of indices comprised of integer values from 0 to 4, corresponding to the five bins--the bin assignments for each of the 30 original points in the 'data' matrix above.\n"
] |
[
27,
1
] |
[] |
[] |
[
"binning",
"numpy",
"python",
"scipy"
] |
stackoverflow_0002144443_binning_numpy_python_scipy.txt
|
Q:
Python2.6 and Snow Leopard. Problem installing appscript (and MANY other packages)
I've been having nothing but trouble with python2.6 and Snow Leopard. One major problem is 32 vs 64-bit libraries.
The other manifests itself like this:
tppllc-mbp15$ sudo easy_install-2.6 appscript
Searching for appscript
Reading http://pypi.python.org/simple/appscript/
Reading http://appscript.sourceforge.net
Best match: appscript 0.21.1
Downloading http://pypi.python.org/packages/source/a/appscript/appscript-0.21.1.tar.gz#md5=351f3e493f9259516fce6eecde155195
Processing appscript-0.21.1.tar.gz
Running appscript-0.21.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-DiXejT/appscript-0.21.1/egg-dist-tmp-brxccx
Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk
Please check your Xcode installation
ld: library not found for -lbundle1.o
collect2: ld returned 1 exit status
ld: library not found for -lbundle1.o
collect2: ld returned 1 exit status
lipo: can't open input file: /var/tmp//ccO2E68V.out (No such file or directory)
error: Setup script exited with error: command 'gcc-4.0' failed with exit status 1
Does anyone have any idea where that "Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk" is coming from? There's no mention of 10.4 in any of the files for this project.
appscript isn't the only project that fails, just one of many.
I tried reinstalling xcode, and my entire operating system--starting on a clean machine--and there are problems.
If I install the package under python2.5 it works. That's my solution for now: to stay with python 2.5
A:
It appears you have likely installed a python 2.6 from python.org or some other 3rd-party installer. The python.org python's are currently built only as 32-bit (i386 and ppc) and are compatible with OS X 10.3 through 10.6. To do that, they are built with the 10.4u SDK which is available via the 10.6 Xcode installer (on the 10.6 Installation DVD and elsewhere), however that SDK is not installed by default. Run the 10.6 Xcode installer again and select it. Then builds of python packages with C extension module should work fine.
Another solution is to just stick with the Apple-supplied Python 2.6.1 in 10.6 (which runs as 64-bit by default) in which case you need to fix your $PATH or be careful to use /usr/bin/easy_install-2.6.
|
Python2.6 and Snow Leopard. Problem installing appscript (and MANY other packages)
|
I've been having nothing but trouble with python2.6 and Snow Leopard. One major problem is 32 vs 64-bit libraries.
The other manifests itself like this:
tppllc-mbp15$ sudo easy_install-2.6 appscript
Searching for appscript
Reading http://pypi.python.org/simple/appscript/
Reading http://appscript.sourceforge.net
Best match: appscript 0.21.1
Downloading http://pypi.python.org/packages/source/a/appscript/appscript-0.21.1.tar.gz#md5=351f3e493f9259516fce6eecde155195
Processing appscript-0.21.1.tar.gz
Running appscript-0.21.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-DiXejT/appscript-0.21.1/egg-dist-tmp-brxccx
Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk
Please check your Xcode installation
ld: library not found for -lbundle1.o
collect2: ld returned 1 exit status
ld: library not found for -lbundle1.o
collect2: ld returned 1 exit status
lipo: can't open input file: /var/tmp//ccO2E68V.out (No such file or directory)
error: Setup script exited with error: command 'gcc-4.0' failed with exit status 1
Does anyone have any idea where that "Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk" is coming from? There's no mention of 10.4 in any of the files for this project.
appscript isn't the only project that fails, just one of many.
I tried reinstalling xcode, and my entire operating system--starting on a clean machine--and there are problems.
If I install the package under python2.5 it works. That's my solution for now: to stay with python 2.5
|
[
"It appears you have likely installed a python 2.6 from python.org or some other 3rd-party installer. The python.org python's are currently built only as 32-bit (i386 and ppc) and are compatible with OS X 10.3 through 10.6. To do that, they are built with the 10.4u SDK which is available via the 10.6 Xcode installer (on the 10.6 Installation DVD and elsewhere), however that SDK is not installed by default. Run the 10.6 Xcode installer again and select it. Then builds of python packages with C extension module should work fine.\nAnother solution is to just stick with the Apple-supplied Python 2.6.1 in 10.6 (which runs as 64-bit by default) in which case you need to fix your $PATH or be careful to use /usr/bin/easy_install-2.6.\n"
] |
[
1
] |
[] |
[] |
[
"macos",
"osx_snow_leopard",
"python"
] |
stackoverflow_0002169987_macos_osx_snow_leopard_python.txt
|
Q:
OpenGL frame buffer slow and spontaneously stalls. Can even cause a system crash when used extensively
Apparently frame buffers are fast and the best way to render offscreen to textures or to simply pre-create things.
My game however is not liking them at all. In the current code frame buffers are used often, sometimes each frame, several times. When used the game begins to slow down but not instantly. It seems to take time (Perhaps a built-up memory problem?). In some areas the frame buffer objects do not seem to slow the game down much accept occasionally the game will stall for a few seconds before continuing as normal.
I assume the Frame buffers are the problem because the game is fast in areas where they aren't used.
I'm using python with pyopengl. The OpenGL code is similar to the code in other language so I do not think python knowledge is significantly important.
Some things are rendered directly to the screen, other textures are rendered to other textures which is involved with the Surface class. This resembles pygame which is what I begun my game in before I changed my mind.
Here is the relevant code.
def create_texture(surface):
surface.texture = glGenTextures(1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glBindTexture(GL_TEXTURE_2D, surface.texture) #Binds the current 2D texture to the texture to be drawn
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) #Required to be set for maping the pixel data
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) #Similar as above
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface.surface_size[0], surface.surface_size[1], 0, GL_RGBA,GL_UNSIGNED_BYTE, surface.data) #Put surface pixel data into texture
if surface.data == None:
setup_framebuffer(surface)
c = [float(sc)/255.0 for sc in surface.colour] #Divide colours by 255 because OpenGL uses 0-1
if surface.background_alpha != None:
c[3] = float(surface.background_alpha)/255.0
glClearColor(*c)
glClear(GL_COLOR_BUFFER_BIT)
end_framebuffer()
Surface.texture_ready.append(surface)
def setup_framebuffer(surface):
#Create texture if not done already
if surface.texture == None:
create_texture(surface)
#Render child to parent
if surface.frame_buffer == None:
surface.frame_buffer = glGenFramebuffersEXT(1)
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0)
glPushAttrib(GL_VIEWPORT_BIT)
glViewport(0,0,surface._scale[0],surface._scale[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,surface._scale[0],0,surface._scale[1])
def end_framebuffer():
glPopAttrib()
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
def draw_texture(texture,offset,size,a,rounded,sides,angle,point):
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glColor4f(1,1,1,float(a)/255.0)
glBindTexture(GL_TEXTURE_2D, texture)
if rounded == 0:
if angle == 0:
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2i(*offset) #Top Left
glTexCoord2f(0.0, 1.0)
glVertex2i(offset[0],offset[1] + size[1]) #Bottom Left
glTexCoord2f(1.0, 1.0)
glVertex2i(offset[0] + size[0],offset[1] + size[1]) #Bottom, Right
glTexCoord2f(1.0, 0.0)
glVertex2i(offset[0] + size[0],offset[1]) #Top, Right
glEnd()
else:
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2f(*rotate_coordinate(offset,point,angle)) #Top Left
glTexCoord2f(0.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0],offset[1] + size[1]),point,angle)) #Bottom Left
glTexCoord2f(1.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1] + size[1]),point,angle)) #Bottom, Right
glTexCoord2f(1.0, 0.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1]),point,angle)) #Top, Right
glEnd()
else:
global arc_factors
arc = [[o*rounded for o in c] for c in arc_factors]
glBegin(GL_POLYGON)
if sides % 2:
for c in arc:
coordinates = (offset[0] + rounded - c[0],offset[1] + rounded - c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(0.0, 0.0)
glVertex2f(*rotate_coordinate(offset,point,angle)) #Top Left
if sides % 4 > 1:
for c in arc[::-1]:
coordinates = (offset[0] + size[0] - rounded + c[0],offset[1] + rounded - c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(1.0, 0.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1]),point,angle)) #Top, Right
if sides % 8 > 3:
for c in arc:
coordinates = (offset[0] + size[0] - rounded + c[0],offset[1] + size[1] - rounded + c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(1.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1] + size[1]),point,angle)) #Bottom, Right
if sides > 7:
for c in arc[::-1]:
coordinates = (offset[0] + rounded - c[0],offset[1] + size[1] - rounded + c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(0.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0],offset[1] + size[1]),point,angle)) #Bottom Left
glEnd()
def texture_to_texture(target,surface,offset,rounded,rotation,point):
#Create texture if not done already
if surface.texture == None:
create_texture(surface)
#Render child to parent
setup_framebuffer(target)
draw_texture(surface.texture,offset,surface._scale,surface.colour[3],rounded,surface.rounded_sides,rotation,point)
end_framebuffer()
def texture_to_screen(surface,offset,rotation,point):
if surface.texture == None:
create_texture(surface)
draw_texture(surface.texture,offset,surface._scale,surface.colour[3],surface.rounded,surface.rounded_sides,rotation,point)
class Surface():
texture_ready = []
def __init__(self,size,extra = None):
self._offset = (0,0)
self.children = []
self.blitted = False
self.last_offset = [0,0]
self.surface_size = list(size)
self.colour = [0,0,0,255]
self.data = None
self.rounded = 0
self.parent = None
self.parent_offset = (0,0)
self.texture = None
self.frame_buffer = None
self._scale = size
self.background_alpha = None
self.rounded_sides = 0
def blit(self,surface,offset,rotation = 0,point = (0,0)):
texture_to_texture(self,surface,offset,surface.rounded,rotation,point)
if surface not in self.children:
self.children.append(surface)
if surface.parent_offset != offset or not surface.blitted:
surface.parent_offset = offset
surface._offset = [offset[0] + self._offset[0],offset[1] + self._offset[1]]
surface.recursive_offset_change() #Add to the children's offsets
surface.blitted = True
def set_background_alpha(self,alpha):
self.background_alpha = float(alpha)/255.0
def recursive_offset_change(self):
for child in self.children:
child._offset = (self._offset[0] + child.parent_offset[0],self._offset[1] + child.parent_offset[1])
child.recursive_offset_change()
def get_offset(self):
return self._offset
def fill(self,colour):
colour = list(colour)
if len(colour) < 4:
colour.append(255)
self.children = []
self.textures = []
self.colour = colour
if self.texture != None:
glDeleteTextures([self.texture])
self.data = None
create_texture(self)
def get_size(self):
return self.surface_size
def get_width(self):
return self.surface_size[0]
def get_height(self):
return self.surface_size[1]
def round_corners(self,r,sides = 15):
self.rounded = r
self.rounded_sides = sides
def get_rect(self):
return Rect(self._offset,self.surface_size)
def scale(self,scale):
self._scale = scale
return self
def __del__(self):
if self.texture != None:
glDeleteTextures([self.texture])
if self.frame_buffer != None:
glDeleteFramebuffersEXT(1, [int(self.frame_buffer)])
class Game(Surface):
game_size = None
first_screen = None
screen = None
fs = False #Fullscreen false to start
clock = None
resize = True
game_gap = None
game_scaled = (0,0)
title = None
fps = -1
enter_fullscreen = False
exit_fullscreen = False
scale_to_screen = False
iconify = False
on_focus_fullscreen = False
f_key = False
fade = 0
p_key = False
music_stop = False
unfade = False
event_after_fade = -1
loaded = False
fade = 255
unfade = True
homedir = os.path.expanduser("~")
fade_screen = False
keys = []
events = []
sections = []
back_key = False
transfer_args = ()
mouse_pos = (0,0)
def __init__(self,title,game_size,on_exit = sys.exit):
self.keys = [False] * 323
self.events = []
pygame.font.init()
pygame.mixer.init()
self.title = title
self.game_size = game_size
self.first_screen = (1280,720) #Take 120 pixels from the height because the menu bar, window bar and dock takes space
glutInit(sys.argv)
glutInitWindowPosition(0,0)
glutInitWindowSize(*game_size)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
glutGameModeString("1280x720:32@60") #720 HD
glutCreateWindow(title)
glutSetIconTitle(title)
self.callbacks()
self.game_gap = (0,0)
self.on_exit = on_exit
self.mod_key = 1024 if sys.platform == "darwin" else 64
Surface.__init__(self,game_size)
self.screen_change = True
self.frames = [time.time()]
self.fps = 60
self.last_time = 0
self.fade_surface = Surface([1280,720])
def callbacks(self):
glutReshapeFunc(self.reshaped)
glutKeyboardFunc(self.keydown)
glutKeyboardUpFunc(self.keyup)
glutSpecialFunc(self.specialdown)
glutSpecialUpFunc(self.specialup)
glutDisplayFunc(self.game_loop)
glutIdleFunc(self.game_loop)
glutMouseFunc(self.mouse_func)
glutPassiveMotionFunc(self.mouse_move)
glutMotionFunc(self.mouse_move)
glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window
glEnable(GL_BLEND) #Enable alpha blending
glEnable(GL_TEXTURE_2D) #Enable 2D Textures
glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
def add_section(self,section_object):
self.sections.append(section_object)
def mouse_func(self,button, state, x, y):
self.events.append((state,button,x,y))
def mouse_move(self,x,y):
self.events.append((MOUSEMOTION,x - self.mouse_pos[0], y - self.mouse_pos[1]))
self.mouse_pos = (x,y)
def keydown(self,char,x,y):
#300 miliusecond delay, 50 milisecond repeat
self.change_keys(char,True)
def keyup(self,char,x,y):
self.change_keys(char,False)
def change_keys(self,char,bool):
char = ord(char)
#Switch backspace and delete
if char == 8:
char = 127
elif char == 127:
char = 8
self.keys[char] = bool
def specialdown(self,char,x,y):
if char == GLUT_KEY_UP:
self.keys[K_UP] = True
if char == GLUT_KEY_DOWN:
self.keys[K_DOWN] = True
if char == GLUT_KEY_LEFT:
self.keys[K_LEFT] = True
if char == GLUT_KEY_RIGHT:
self.keys[K_RIGHT] = True
def specialup(self,char,x,y):
if char == GLUT_KEY_UP:
self.keys[K_UP] = False
if char == GLUT_KEY_DOWN:
self.keys[K_DOWN] = False
if char == GLUT_KEY_LEFT:
self.keys[K_LEFT] = False
if char == GLUT_KEY_RIGHT:
self.keys[K_RIGHT] = False
def reshaped(self,w,h):
#Scale game to screen resolution, keeping aspect ratio
self.screen_change = True
self.game_scaled = get_resolution((w,h),self.game_size)
glutReshapeWindow(*self.game_scaled)
glViewport(0,0,self.game_scaled[0],self.game_scaled[1])
glutPositionWindow((1280- w)/2,(720 - h)/2)
def game_loop(self):
self.section.loop()
if self.unfade:
if self.fade == 255:
play_music(self.section.music)
if self.fade > 0:
self.fade -= 5
else:
self.music_stop = False
self.unfade = False
if self.fade_screen and not self.unfade: #Fade out
if self.fade == 0:
sound("/sounds/menu3/fade.ogg").play()
self.music_stop = True
pygame.mixer.music.fadeout(850)
if self.fade < 255:
self.fade += 5
else:
self.fade_screen = False
self.unfade = True
if self.fade_screen == False:
if self.event_after_fade != -1:
self.section = self.sections[self.event_after_fade]
self.section.transfer(*self.transfer_args)
self.transfer_args = ()
self.event_after_fade = -1
self.fade_surface.fill((0,0,0,self.fade))
self.blit(self.fade_surface,(0,0))
for event in self.events:
if event[1] == MUSICEND and self.music_stop == False:
play_music(self.section.music)
self.events = [] #Remove events
global draw_texture_time
#Updates screen properly
for event in self.events:
if event.type == QUIT:
self.on_exit()
if True:
if self.keys[K_f]:
if self.f_key == False:
self.f_key = True
if self.fs == False:
self.enter_fullscreen = True
else:
self.exit_fullscreen = True
else:
self.f_key = False
if self.on_focus_fullscreen and pygame.display.get_active():
self.on_focus_fullscreen = False
self.enter_fullscreen = True
pixel_data = []
if self.enter_fullscreen or self.exit_fullscreen:
for surface in Surface.texture_ready:
if surface.texture != None:
glBindTexture(GL_TEXTURE_2D, surface.texture)
glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE,surface.data)
surface.texture = None
if surface.frame_buffer != None:
pixel_data.append((surface,None))
glReadPixels(0,0,surface.surface_size[0],surface.surface_size[1],GL_BGRA,GL_UNSIGNED_BYTE,pixel_data[-1][1])
Surface.texture_ready = []
if self.enter_fullscreen:
glutEnterGameMode()
self.callbacks()
self.fs = True
self.enter_fullscreen = False
elif self.exit_fullscreen:
glutSetCursor(GLUT_CURSOR_INHERIT)
self.fs = False
glutLeaveGameMode()
self.callbacks()
self.exit_fullscreen = False
if self.iconify:
self.on_focus_fullscreen = True
if self.enter_fullscreen or self.exit_fullscreen:
for surface, data in pixel_data:
surface.frame_buffer = glGenFramebuffersEXT(1)
setup_framebuffer(surface)
glDrawPixels(surface.surface_size[0],surface.surface_size[1],GL_RGBA,GL_UNSIGNED_BYTE,data)
end_framebuffer()
if self.iconify:
pygame.display.iconify() #Minimise
self.iconify = False
glFlush()
glutSwapBuffers() #Flip buffer
glClear(GL_COLOR_BUFFER_BIT)
self.frames.append(time.time())
time_d = (self.frames[-1] - self.frames[-2])
if time_d < 0.01667:
time.sleep(0.01667 - time_d)
self.frames[-1] = time.time()
self.fps = len(self.frames)/(self.frames[-1] - self.frames[0])
if self.fps > 60:
self.fps = 60
self.frames = [frame for frame in self.frames if (self.frames[-1] - frame) < 1]
glutSetWindowTitle(self.title + " - " + str(int(self.fps)) + "fps")
def blit(self,surface,offset,rotation = 0,point = (0,0)):
if surface.get_offset() != offset or not surface.blitted:
surface._offset = offset
surface.recursive_offset_change() #Add to the children's offsets
surface.blitted = True
texture_to_screen(surface,offset,rotation,point)
def transfer_section(self,section,args=()):
self.transfer_args = args
self.event_after_fade = section
self.fade_screen = True
Bravo if anyone can help me with this. I spent ages getting the FBOs to work at all. It's so frustrating that they aren't working properly. If it comes to removing them, it's a nightmare all over again. But I must face whatever needs to be done to make the game fast.
A:
I haven't worked with OpenGL for about 14 years so I'm not much help with that. I'm just looking at the Python code. There's a few things you can do to clean the code up, like use ".width" instead of ".surface_size[0]". You do have a get_width(), but descriptors are your friends. You also have checks for "if self.data == None" but there's no place where the .data field is ever set to anything besides None. Oh, and a minor point - the better form of this test is "if self.data is None".
I'm going on the assumption that you're running out of some sort of resource. I tried to follow the glBindTexture/glDeleteTexture logic but it confused me. Why do you store all your pending surfaces into the class variable Surface.texture_ready list? That is, why isn't it an instance variable?
Your game loop goes through and glBindTexture:s the texture_ready elements, then resets the list to []. But only when entering/exiting full-screen mode. If you don't go to full screen, it seems that texture_ready gets longer and longer.
You might consider using one of the profiling tools to see where most of the time is being spent. Even something as simple as watching the line trace might be enough for you to spot where the slowdown is.
I'm afraid this isn't much help though, as I just don't know OpenGL.
|
OpenGL frame buffer slow and spontaneously stalls. Can even cause a system crash when used extensively
|
Apparently frame buffers are fast and the best way to render offscreen to textures or to simply pre-create things.
My game however is not liking them at all. In the current code frame buffers are used often, sometimes each frame, several times. When used the game begins to slow down but not instantly. It seems to take time (Perhaps a built-up memory problem?). In some areas the frame buffer objects do not seem to slow the game down much accept occasionally the game will stall for a few seconds before continuing as normal.
I assume the Frame buffers are the problem because the game is fast in areas where they aren't used.
I'm using python with pyopengl. The OpenGL code is similar to the code in other language so I do not think python knowledge is significantly important.
Some things are rendered directly to the screen, other textures are rendered to other textures which is involved with the Surface class. This resembles pygame which is what I begun my game in before I changed my mind.
Here is the relevant code.
def create_texture(surface):
surface.texture = glGenTextures(1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glBindTexture(GL_TEXTURE_2D, surface.texture) #Binds the current 2D texture to the texture to be drawn
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) #Required to be set for maping the pixel data
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) #Similar as above
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface.surface_size[0], surface.surface_size[1], 0, GL_RGBA,GL_UNSIGNED_BYTE, surface.data) #Put surface pixel data into texture
if surface.data == None:
setup_framebuffer(surface)
c = [float(sc)/255.0 for sc in surface.colour] #Divide colours by 255 because OpenGL uses 0-1
if surface.background_alpha != None:
c[3] = float(surface.background_alpha)/255.0
glClearColor(*c)
glClear(GL_COLOR_BUFFER_BIT)
end_framebuffer()
Surface.texture_ready.append(surface)
def setup_framebuffer(surface):
#Create texture if not done already
if surface.texture == None:
create_texture(surface)
#Render child to parent
if surface.frame_buffer == None:
surface.frame_buffer = glGenFramebuffersEXT(1)
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer)
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0)
glPushAttrib(GL_VIEWPORT_BIT)
glViewport(0,0,surface._scale[0],surface._scale[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,surface._scale[0],0,surface._scale[1])
def end_framebuffer():
glPopAttrib()
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
def draw_texture(texture,offset,size,a,rounded,sides,angle,point):
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() #Loads model matrix
glColor4f(1,1,1,float(a)/255.0)
glBindTexture(GL_TEXTURE_2D, texture)
if rounded == 0:
if angle == 0:
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2i(*offset) #Top Left
glTexCoord2f(0.0, 1.0)
glVertex2i(offset[0],offset[1] + size[1]) #Bottom Left
glTexCoord2f(1.0, 1.0)
glVertex2i(offset[0] + size[0],offset[1] + size[1]) #Bottom, Right
glTexCoord2f(1.0, 0.0)
glVertex2i(offset[0] + size[0],offset[1]) #Top, Right
glEnd()
else:
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2f(*rotate_coordinate(offset,point,angle)) #Top Left
glTexCoord2f(0.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0],offset[1] + size[1]),point,angle)) #Bottom Left
glTexCoord2f(1.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1] + size[1]),point,angle)) #Bottom, Right
glTexCoord2f(1.0, 0.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1]),point,angle)) #Top, Right
glEnd()
else:
global arc_factors
arc = [[o*rounded for o in c] for c in arc_factors]
glBegin(GL_POLYGON)
if sides % 2:
for c in arc:
coordinates = (offset[0] + rounded - c[0],offset[1] + rounded - c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(0.0, 0.0)
glVertex2f(*rotate_coordinate(offset,point,angle)) #Top Left
if sides % 4 > 1:
for c in arc[::-1]:
coordinates = (offset[0] + size[0] - rounded + c[0],offset[1] + rounded - c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(1.0, 0.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1]),point,angle)) #Top, Right
if sides % 8 > 3:
for c in arc:
coordinates = (offset[0] + size[0] - rounded + c[0],offset[1] + size[1] - rounded + c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(1.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0] + size[0],offset[1] + size[1]),point,angle)) #Bottom, Right
if sides > 7:
for c in arc[::-1]:
coordinates = (offset[0] + rounded - c[0],offset[1] + size[1] - rounded + c[1])
glTexCoord2f((coordinates[0]-offset[0])/size[0],(coordinates[1]-offset[1])/size[1])
glVertex2f(*coordinates)
else:
glTexCoord2f(0.0, 1.0)
glVertex2f(*rotate_coordinate((offset[0],offset[1] + size[1]),point,angle)) #Bottom Left
glEnd()
def texture_to_texture(target,surface,offset,rounded,rotation,point):
#Create texture if not done already
if surface.texture == None:
create_texture(surface)
#Render child to parent
setup_framebuffer(target)
draw_texture(surface.texture,offset,surface._scale,surface.colour[3],rounded,surface.rounded_sides,rotation,point)
end_framebuffer()
def texture_to_screen(surface,offset,rotation,point):
if surface.texture == None:
create_texture(surface)
draw_texture(surface.texture,offset,surface._scale,surface.colour[3],surface.rounded,surface.rounded_sides,rotation,point)
class Surface():
texture_ready = []
def __init__(self,size,extra = None):
self._offset = (0,0)
self.children = []
self.blitted = False
self.last_offset = [0,0]
self.surface_size = list(size)
self.colour = [0,0,0,255]
self.data = None
self.rounded = 0
self.parent = None
self.parent_offset = (0,0)
self.texture = None
self.frame_buffer = None
self._scale = size
self.background_alpha = None
self.rounded_sides = 0
def blit(self,surface,offset,rotation = 0,point = (0,0)):
texture_to_texture(self,surface,offset,surface.rounded,rotation,point)
if surface not in self.children:
self.children.append(surface)
if surface.parent_offset != offset or not surface.blitted:
surface.parent_offset = offset
surface._offset = [offset[0] + self._offset[0],offset[1] + self._offset[1]]
surface.recursive_offset_change() #Add to the children's offsets
surface.blitted = True
def set_background_alpha(self,alpha):
self.background_alpha = float(alpha)/255.0
def recursive_offset_change(self):
for child in self.children:
child._offset = (self._offset[0] + child.parent_offset[0],self._offset[1] + child.parent_offset[1])
child.recursive_offset_change()
def get_offset(self):
return self._offset
def fill(self,colour):
colour = list(colour)
if len(colour) < 4:
colour.append(255)
self.children = []
self.textures = []
self.colour = colour
if self.texture != None:
glDeleteTextures([self.texture])
self.data = None
create_texture(self)
def get_size(self):
return self.surface_size
def get_width(self):
return self.surface_size[0]
def get_height(self):
return self.surface_size[1]
def round_corners(self,r,sides = 15):
self.rounded = r
self.rounded_sides = sides
def get_rect(self):
return Rect(self._offset,self.surface_size)
def scale(self,scale):
self._scale = scale
return self
def __del__(self):
if self.texture != None:
glDeleteTextures([self.texture])
if self.frame_buffer != None:
glDeleteFramebuffersEXT(1, [int(self.frame_buffer)])
class Game(Surface):
game_size = None
first_screen = None
screen = None
fs = False #Fullscreen false to start
clock = None
resize = True
game_gap = None
game_scaled = (0,0)
title = None
fps = -1
enter_fullscreen = False
exit_fullscreen = False
scale_to_screen = False
iconify = False
on_focus_fullscreen = False
f_key = False
fade = 0
p_key = False
music_stop = False
unfade = False
event_after_fade = -1
loaded = False
fade = 255
unfade = True
homedir = os.path.expanduser("~")
fade_screen = False
keys = []
events = []
sections = []
back_key = False
transfer_args = ()
mouse_pos = (0,0)
def __init__(self,title,game_size,on_exit = sys.exit):
self.keys = [False] * 323
self.events = []
pygame.font.init()
pygame.mixer.init()
self.title = title
self.game_size = game_size
self.first_screen = (1280,720) #Take 120 pixels from the height because the menu bar, window bar and dock takes space
glutInit(sys.argv)
glutInitWindowPosition(0,0)
glutInitWindowSize(*game_size)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)
glutGameModeString("1280x720:32@60") #720 HD
glutCreateWindow(title)
glutSetIconTitle(title)
self.callbacks()
self.game_gap = (0,0)
self.on_exit = on_exit
self.mod_key = 1024 if sys.platform == "darwin" else 64
Surface.__init__(self,game_size)
self.screen_change = True
self.frames = [time.time()]
self.fps = 60
self.last_time = 0
self.fade_surface = Surface([1280,720])
def callbacks(self):
glutReshapeFunc(self.reshaped)
glutKeyboardFunc(self.keydown)
glutKeyboardUpFunc(self.keyup)
glutSpecialFunc(self.specialdown)
glutSpecialUpFunc(self.specialup)
glutDisplayFunc(self.game_loop)
glutIdleFunc(self.game_loop)
glutMouseFunc(self.mouse_func)
glutPassiveMotionFunc(self.mouse_move)
glutMotionFunc(self.mouse_move)
glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window
glEnable(GL_BLEND) #Enable alpha blending
glEnable(GL_TEXTURE_2D) #Enable 2D Textures
glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glMatrixMode(GL_PROJECTION)
glLoadIdentity() #Load the projection matrix
gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
def add_section(self,section_object):
self.sections.append(section_object)
def mouse_func(self,button, state, x, y):
self.events.append((state,button,x,y))
def mouse_move(self,x,y):
self.events.append((MOUSEMOTION,x - self.mouse_pos[0], y - self.mouse_pos[1]))
self.mouse_pos = (x,y)
def keydown(self,char,x,y):
#300 miliusecond delay, 50 milisecond repeat
self.change_keys(char,True)
def keyup(self,char,x,y):
self.change_keys(char,False)
def change_keys(self,char,bool):
char = ord(char)
#Switch backspace and delete
if char == 8:
char = 127
elif char == 127:
char = 8
self.keys[char] = bool
def specialdown(self,char,x,y):
if char == GLUT_KEY_UP:
self.keys[K_UP] = True
if char == GLUT_KEY_DOWN:
self.keys[K_DOWN] = True
if char == GLUT_KEY_LEFT:
self.keys[K_LEFT] = True
if char == GLUT_KEY_RIGHT:
self.keys[K_RIGHT] = True
def specialup(self,char,x,y):
if char == GLUT_KEY_UP:
self.keys[K_UP] = False
if char == GLUT_KEY_DOWN:
self.keys[K_DOWN] = False
if char == GLUT_KEY_LEFT:
self.keys[K_LEFT] = False
if char == GLUT_KEY_RIGHT:
self.keys[K_RIGHT] = False
def reshaped(self,w,h):
#Scale game to screen resolution, keeping aspect ratio
self.screen_change = True
self.game_scaled = get_resolution((w,h),self.game_size)
glutReshapeWindow(*self.game_scaled)
glViewport(0,0,self.game_scaled[0],self.game_scaled[1])
glutPositionWindow((1280- w)/2,(720 - h)/2)
def game_loop(self):
self.section.loop()
if self.unfade:
if self.fade == 255:
play_music(self.section.music)
if self.fade > 0:
self.fade -= 5
else:
self.music_stop = False
self.unfade = False
if self.fade_screen and not self.unfade: #Fade out
if self.fade == 0:
sound("/sounds/menu3/fade.ogg").play()
self.music_stop = True
pygame.mixer.music.fadeout(850)
if self.fade < 255:
self.fade += 5
else:
self.fade_screen = False
self.unfade = True
if self.fade_screen == False:
if self.event_after_fade != -1:
self.section = self.sections[self.event_after_fade]
self.section.transfer(*self.transfer_args)
self.transfer_args = ()
self.event_after_fade = -1
self.fade_surface.fill((0,0,0,self.fade))
self.blit(self.fade_surface,(0,0))
for event in self.events:
if event[1] == MUSICEND and self.music_stop == False:
play_music(self.section.music)
self.events = [] #Remove events
global draw_texture_time
#Updates screen properly
for event in self.events:
if event.type == QUIT:
self.on_exit()
if True:
if self.keys[K_f]:
if self.f_key == False:
self.f_key = True
if self.fs == False:
self.enter_fullscreen = True
else:
self.exit_fullscreen = True
else:
self.f_key = False
if self.on_focus_fullscreen and pygame.display.get_active():
self.on_focus_fullscreen = False
self.enter_fullscreen = True
pixel_data = []
if self.enter_fullscreen or self.exit_fullscreen:
for surface in Surface.texture_ready:
if surface.texture != None:
glBindTexture(GL_TEXTURE_2D, surface.texture)
glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE,surface.data)
surface.texture = None
if surface.frame_buffer != None:
pixel_data.append((surface,None))
glReadPixels(0,0,surface.surface_size[0],surface.surface_size[1],GL_BGRA,GL_UNSIGNED_BYTE,pixel_data[-1][1])
Surface.texture_ready = []
if self.enter_fullscreen:
glutEnterGameMode()
self.callbacks()
self.fs = True
self.enter_fullscreen = False
elif self.exit_fullscreen:
glutSetCursor(GLUT_CURSOR_INHERIT)
self.fs = False
glutLeaveGameMode()
self.callbacks()
self.exit_fullscreen = False
if self.iconify:
self.on_focus_fullscreen = True
if self.enter_fullscreen or self.exit_fullscreen:
for surface, data in pixel_data:
surface.frame_buffer = glGenFramebuffersEXT(1)
setup_framebuffer(surface)
glDrawPixels(surface.surface_size[0],surface.surface_size[1],GL_RGBA,GL_UNSIGNED_BYTE,data)
end_framebuffer()
if self.iconify:
pygame.display.iconify() #Minimise
self.iconify = False
glFlush()
glutSwapBuffers() #Flip buffer
glClear(GL_COLOR_BUFFER_BIT)
self.frames.append(time.time())
time_d = (self.frames[-1] - self.frames[-2])
if time_d < 0.01667:
time.sleep(0.01667 - time_d)
self.frames[-1] = time.time()
self.fps = len(self.frames)/(self.frames[-1] - self.frames[0])
if self.fps > 60:
self.fps = 60
self.frames = [frame for frame in self.frames if (self.frames[-1] - frame) < 1]
glutSetWindowTitle(self.title + " - " + str(int(self.fps)) + "fps")
def blit(self,surface,offset,rotation = 0,point = (0,0)):
if surface.get_offset() != offset or not surface.blitted:
surface._offset = offset
surface.recursive_offset_change() #Add to the children's offsets
surface.blitted = True
texture_to_screen(surface,offset,rotation,point)
def transfer_section(self,section,args=()):
self.transfer_args = args
self.event_after_fade = section
self.fade_screen = True
Bravo if anyone can help me with this. I spent ages getting the FBOs to work at all. It's so frustrating that they aren't working properly. If it comes to removing them, it's a nightmare all over again. But I must face whatever needs to be done to make the game fast.
|
[
"I haven't worked with OpenGL for about 14 years so I'm not much help with that. I'm just looking at the Python code. There's a few things you can do to clean the code up, like use \".width\" instead of \".surface_size[0]\". You do have a get_width(), but descriptors are your friends. You also have checks for \"if self.data == None\" but there's no place where the .data field is ever set to anything besides None. Oh, and a minor point - the better form of this test is \"if self.data is None\".\nI'm going on the assumption that you're running out of some sort of resource. I tried to follow the glBindTexture/glDeleteTexture logic but it confused me. Why do you store all your pending surfaces into the class variable Surface.texture_ready list? That is, why isn't it an instance variable?\nYour game loop goes through and glBindTexture:s the texture_ready elements, then resets the list to []. But only when entering/exiting full-screen mode. If you don't go to full screen, it seems that texture_ready gets longer and longer.\nYou might consider using one of the profiling tools to see where most of the time is being spent. Even something as simple as watching the line trace might be enough for you to spot where the slowdown is.\nI'm afraid this isn't much help though, as I just don't know OpenGL.\n"
] |
[
0
] |
[] |
[] |
[
"fbo",
"framebuffer",
"opengl",
"performance",
"python"
] |
stackoverflow_0002169868_fbo_framebuffer_opengl_performance_python.txt
|
Q:
Python: Analysis on CSV files 100,000 lines x 40 columns
I have about a 100 csv files each 100,000 x 40 rows columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for the analysis.
I was wondering what issues should I expect with such large files? I've already checked for erroneous data. What are your recommendations on doing statistical analysis? would it be better if I just split the files and do the whole thing in Excel?
A:
I've found that Python + CSV is probably the fastest, and simplest way to do some kinds of statistical processing.
We do a fair amount of reformatting and correcting for odd data errors, so Python helps us.
The availability of Python's functional programming features makes this particularly simple. You can do sampling with tools like this.
def someStatFunction( source ):
for row in source:
...some processing...
def someFilterFunction( source ):
for row in source:
if someFunction( row ):
yield row
# All rows
with open( "someFile", "rb" ) as source:
rdr = csv.reader( source )
someStatFunction( rdr )
# Filtered by someFilterFunction applied to each row
with open( "someFile", "rb" ) as source:
rdr = csv.reader( source )
someStatFunction( someFilterFunction( rdr ) )
I really like being able to compose more complex functions from simpler functions.
A:
For massive datasets you might be interested in ROOT. It can be used to analyze and very effectively store petabytes of data. It also come with some basic and more advanced statistics tools.
While it is written to be used with C++, there are also pretty complete python bindings. They don't make it extremely easy to get direct access to the raw data (e.g. to use them in R or numpy) -- but it is definitely possible (I do it all the time).
A:
Python is very nice for such kind of data processing, especially if your samples are "rows" and you can process each such row independently:
row1
row2
row3
etc.
In fact your program can have very small memory footprint, thanks to generators and generator expressions, about which you can read here: http://www.dabeaz.com/generators/ (it's not basic stuff but some mind-twisting applications of generators).
Regarding S.Lott's answer, you probably want to avoid filter() being applied to sequence of rows - it might explode your computer if you pass to it sequence that is long enough (try: filter(None, itertools.count()) - after saving all you data :-)). It's much better to replace filter with something like this:
def filter_generator(func, sequence):
for item in sequence:
if (func is None and item) or func(item):
yield item
or shorter:
filtered_sequence = (item for item in sequence if (func is None and item) or func(item))
This can be further optimized by extracting condition before the loop, but this is an excersise for the reader :-)
A:
I've been having great success using Python and CSV file reading and generation. Using a modest Core 2 Duo laptop I have been able to store close to the same amount of data as you and process it in memory in a few minutes. My main advice in doing this is to split up your jobs so that you can do things in separate steps since batching all your jobs at once can be a pain when you want only one feature to execute. Come up with a good battle rhythm that allows you to take advantage of your resources as much as possible.
Excel is nice for smaller batches of data, but check out matplotlib for doing graphs and charts normally reserved for Excel.
A:
In general, don't worry too much about the size. If your files get bigger by a factor of 2-3, you might start running out of memory on a 32-bit system. I figure that if each field of the table is 100 bytes, i.e., each row is 4000 bytes, you'll be using roughly 400 MB of RAM to store the data in memory and if you add about as much for processing, you'll still only be using 800 or so MB. These calculations are very back of the envelope and extremely generous (you'll only use this much memory if you have a lot of long strings or humongous integers in your data, since the maximum you'll use for standard datatypes is 8 bytes for a float or a long).
If you do start running out of memory, 64-bit might be the way to go. But other than that, Python will handle large amounts of data with aplomb, especially when combined with numpy/scipy. Using Numpy arrays will almost always be faster than using native lists as well. Matplotlib will take care of most plotting needs and can certainly handle the simple plots you've described.
Finally, if you find something that Python can't do, but already have a codebase written in it, take a look at RPy.
|
Python: Analysis on CSV files 100,000 lines x 40 columns
|
I have about a 100 csv files each 100,000 x 40 rows columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for the analysis.
I was wondering what issues should I expect with such large files? I've already checked for erroneous data. What are your recommendations on doing statistical analysis? would it be better if I just split the files and do the whole thing in Excel?
|
[
"I've found that Python + CSV is probably the fastest, and simplest way to do some kinds of statistical processing. \nWe do a fair amount of reformatting and correcting for odd data errors, so Python helps us.\nThe availability of Python's functional programming features makes this particularly simple. You can do sampling with tools like this.\ndef someStatFunction( source ):\n for row in source:\n ...some processing...\n\ndef someFilterFunction( source ):\n for row in source:\n if someFunction( row ):\n yield row\n\n# All rows\nwith open( \"someFile\", \"rb\" ) as source:\n rdr = csv.reader( source )\n someStatFunction( rdr )\n\n# Filtered by someFilterFunction applied to each row\nwith open( \"someFile\", \"rb\" ) as source:\n rdr = csv.reader( source )\n someStatFunction( someFilterFunction( rdr ) )\n\nI really like being able to compose more complex functions from simpler functions.\n",
"For massive datasets you might be interested in ROOT. It can be used to analyze and very effectively store petabytes of data. It also come with some basic and more advanced statistics tools.\nWhile it is written to be used with C++, there are also pretty complete python bindings. They don't make it extremely easy to get direct access to the raw data (e.g. to use them in R or numpy) -- but it is definitely possible (I do it all the time).\n",
"Python is very nice for such kind of data processing, especially if your samples are \"rows\" and you can process each such row independently:\n row1\n row2\n row3\n etc.\n\nIn fact your program can have very small memory footprint, thanks to generators and generator expressions, about which you can read here: http://www.dabeaz.com/generators/ (it's not basic stuff but some mind-twisting applications of generators).\nRegarding S.Lott's answer, you probably want to avoid filter() being applied to sequence of rows - it might explode your computer if you pass to it sequence that is long enough (try: filter(None, itertools.count()) - after saving all you data :-)). It's much better to replace filter with something like this:\n def filter_generator(func, sequence):\n for item in sequence:\n if (func is None and item) or func(item):\n yield item\n\nor shorter:\n filtered_sequence = (item for item in sequence if (func is None and item) or func(item))\n\nThis can be further optimized by extracting condition before the loop, but this is an excersise for the reader :-)\n",
"I've been having great success using Python and CSV file reading and generation. Using a modest Core 2 Duo laptop I have been able to store close to the same amount of data as you and process it in memory in a few minutes. My main advice in doing this is to split up your jobs so that you can do things in separate steps since batching all your jobs at once can be a pain when you want only one feature to execute. Come up with a good battle rhythm that allows you to take advantage of your resources as much as possible.\nExcel is nice for smaller batches of data, but check out matplotlib for doing graphs and charts normally reserved for Excel.\n",
"In general, don't worry too much about the size. If your files get bigger by a factor of 2-3, you might start running out of memory on a 32-bit system. I figure that if each field of the table is 100 bytes, i.e., each row is 4000 bytes, you'll be using roughly 400 MB of RAM to store the data in memory and if you add about as much for processing, you'll still only be using 800 or so MB. These calculations are very back of the envelope and extremely generous (you'll only use this much memory if you have a lot of long strings or humongous integers in your data, since the maximum you'll use for standard datatypes is 8 bytes for a float or a long). \nIf you do start running out of memory, 64-bit might be the way to go. But other than that, Python will handle large amounts of data with aplomb, especially when combined with numpy/scipy. Using Numpy arrays will almost always be faster than using native lists as well. Matplotlib will take care of most plotting needs and can certainly handle the simple plots you've described. \nFinally, if you find something that Python can't do, but already have a codebase written in it, take a look at RPy.\n"
] |
[
13,
2,
1,
1,
1
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0002142415_numpy_python.txt
|
Q:
List multiplication
I have a list L = [a, b, c] and I want to generate a list of tuples :
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
I tried doing L * L but it didn't work. Can someone tell me how to get this in python.
A:
You can do it with a list comprehension:
[ (x,y) for x in L for y in L]
edit
You can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns a generator instead of a list, so you may need to convert it (depending on what you want to do with it).
A:
The itertools module contains a number of helpful functions for this sort of thing. It looks like you may be looking for product:
>>> import itertools
>>> L = [1,2,3]
>>> itertools.product(L,L)
<itertools.product object at 0x83788>
>>> list(_)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
A:
Take a look at the itertools module, which provides a product member.
L =[1,2,3]
import itertools
res = list(itertools.product(L,L))
print(res)
Gives:
[(1,1),(1,2),(1,3),(2,1), .... and so on]
A:
Two main alternatives:
>>> L = ['a', 'b', 'c']
>>> import itertools
>>> list(itertools.product(L, L))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>> [(one, two) for one in L for two in L]
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
>>>
the former one needs Python 2.6 or better -- the latter works in just about any Python version you might be tied to.
A:
x = [a,b,c]
y = []
for item in x:
for item2 in x:
y.append((item, item2))
Maybe not the Pythonic way but working
A:
Ok I tried :
L2 = [(x,y) for x in L for x in L] and this got L square.
Is this the best pythonic way to do this? I would expect L * L to work in python.
A:
The most old fashioned way to do it would be:
def perm(L):
result = []
for i in L:
for j in L:
result.append((i,j))
return result
This has a runtime of O(n^2) and is therefore quite slow, but you could consider it to be "vintage" style code.
|
List multiplication
|
I have a list L = [a, b, c] and I want to generate a list of tuples :
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
I tried doing L * L but it didn't work. Can someone tell me how to get this in python.
|
[
"You can do it with a list comprehension:\n[ (x,y) for x in L for y in L]\n\nedit\nYou can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns a generator instead of a list, so you may need to convert it (depending on what you want to do with it).\n",
"The itertools module contains a number of helpful functions for this sort of thing. It looks like you may be looking for product:\n>>> import itertools\n>>> L = [1,2,3]\n>>> itertools.product(L,L)\n<itertools.product object at 0x83788>\n>>> list(_)\n[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]\n\n",
"Take a look at the itertools module, which provides a product member.\nL =[1,2,3]\n\nimport itertools\nres = list(itertools.product(L,L))\nprint(res)\n\nGives:\n[(1,1),(1,2),(1,3),(2,1), .... and so on]\n\n",
"Two main alternatives:\n>>> L = ['a', 'b', 'c']\n>>> import itertools\n>>> list(itertools.product(L, L))\n[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]\n>>> [(one, two) for one in L for two in L]\n[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]\n>>> \n\nthe former one needs Python 2.6 or better -- the latter works in just about any Python version you might be tied to.\n",
"x = [a,b,c]\ny = []\nfor item in x:\n for item2 in x:\n y.append((item, item2))\nMaybe not the Pythonic way but working\n",
"Ok I tried :\nL2 = [(x,y) for x in L for x in L] and this got L square.\nIs this the best pythonic way to do this? I would expect L * L to work in python.\n",
"The most old fashioned way to do it would be:\ndef perm(L):\n result = []\n for i in L:\n for j in L:\n result.append((i,j))\n return result\n\nThis has a runtime of O(n^2) and is therefore quite slow, but you could consider it to be \"vintage\" style code.\n"
] |
[
22,
15,
7,
3,
0,
0,
0
] |
[] |
[] |
[
"cartesian_product",
"list",
"python"
] |
stackoverflow_0002169838_cartesian_product_list_python.txt
|
Q:
Getting Django comments to be able to use bold and italic style
So I'm trying to get rich text to work for the cheeserater program where I added a commenting system using the tinyMCE editor in the textarea. This is what it looks like:
<table><td align=left>
{% get_comment_list for package as comment_list %}
{% for comment in comment_list %}
{{ comment.comment|safe }}<br>
{% endfor %}
</table>
The underline and text size works, but the bold and italic styles don't. For example, I underlined and bolded 'omg', bolded 'wtf', bolded and italicized 'lol'.
<p><strong><span style="text-decoration: underline;">omg</span></strong><strong> wtf <em>lol</em></strong></p>
It displays as the 'omg' underlined, but 'wtf' and 'lol' has their format unchanged.
A:
Those tags work fine here. Check that you don't have a stylesheet causing those tags to use an unadorned style.
|
Getting Django comments to be able to use bold and italic style
|
So I'm trying to get rich text to work for the cheeserater program where I added a commenting system using the tinyMCE editor in the textarea. This is what it looks like:
<table><td align=left>
{% get_comment_list for package as comment_list %}
{% for comment in comment_list %}
{{ comment.comment|safe }}<br>
{% endfor %}
</table>
The underline and text size works, but the bold and italic styles don't. For example, I underlined and bolded 'omg', bolded 'wtf', bolded and italicized 'lol'.
<p><strong><span style="text-decoration: underline;">omg</span></strong><strong> wtf <em>lol</em></strong></p>
It displays as the 'omg' underlined, but 'wtf' and 'lol' has their format unchanged.
|
[
"Those tags work fine here. Check that you don't have a stylesheet causing those tags to use an unadorned style.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"html",
"python",
"tinymce"
] |
stackoverflow_0002170111_django_html_python_tinymce.txt
|
Q:
Python: Optimizing a tree evaluator
I know tree is a well studied structure.
I'm writing a program that randomly generates many expression trees and then sorts and selects by a fitness attribute.
I have a class MakeTreeInOrder() that turns the tree into a string that 'eval' can evaluate.
but it gets called many many times, and should be optimized for time.
below is a function that builds a tree that adds successive numbers to use as a test.
I was wondering if there is an optimized way to evaluate an expression that is in a tree structure. I figured that
that it's used quite a bit and somebodys already done this.
import itertools
from collections import namedtuple
#Further developing Torsten Marek's second suggestion
KS = itertools.count()
Node = namedtuple("Node", ["cargo", "args"])
def build_nodes (depth = 5):
if (depth <= 0):
this_node = Node((str(KS.next())), [None, None])
return this_node
else:
this_node = Node('+', [])
this_node.args.extend(
build_nodes(depth = depth - (i + 1))
for i in range(2))
return this_node
The following is the code that I think can be made a lot faster. And I was hoping for some ideas.
class MakeTreeInOrder(object):
def __init__(self, node):
object.__init__(self)
self.node = node
self.str = ''
def makeit(self, nnode = ''):
if nnode == '':
nnode = self.node
if nnode == None: return
self.str +='('
self.makeit(nnode.args[0])
self.str += nnode.cargo
self.makeit(nnode.args[1])
self.str+=')'
return self.str
def Main():
this_tree = build_nodes()
expression_generator = MakeTreeInOrder(this_tree)
this_expression = expression_generator.makeit()
print this_expression
print eval(this_expression)
if __name__ == '__main__':
rresult = Main()
A:
Adding a touch of object orientation here makes things simpler. Have subclasses of Node for each thing in your tree, and use an 'eval' method to evaluate them.
import random
class ArithmeticOperatorNode(object):
def __init__(self, operator, *args):
self.operator = operator
self.children = args
def eval(self):
if self.operator == '+':
return sum(x.eval() for x in self.children)
assert False, 'Unknown arithmetic operator ' + self.operator
def __str__(self):
return '(%s)' % (' ' + self.operator + ' ').join(str(x) for x in self.children)
class ConstantNode(object):
def __init__(self, constant):
self.constant = constant
def eval(self):
return self.constant
def __str__(self):
return str(self.constant)
def build_tree(n):
if n == 0:
return ConstantNode(random.randrange(100))
else:
left = build_tree(n - 1)
right = build_tree(n - 1)
return ArithmeticOperatorNode('+', left, right)
node = build_tree(5)
print node
print node.eval()
To evaluate the tree, just call .eval() on the top level node.
node = build_tree(5)
print node.eval()
I also added a __str__ method to convert the tree to a string so you can see how this generalizes to other tree functions. It just does '+' at the moment, but hopefully it's clear how to extend this to the full range of arithmetic operations.
A:
Your example imports numpy and random but never uses them. It also has a "for i in range(2))" with no body. This is clearly not valid Python code.
You don't define what 'cargo' and the nodes are supposed to contain. It appears that 'cargo' is a number, since it comes from itertools.count().next(). But that makes no sense since you want the result to be a eval'able Python string.
If you are doing a one-time evaluation of the tree then the fastest solution would be to evaluate it directly in-place, but without an actual example of the data you're working with, I can't show an example.
If you want to make it even faster then look further upstream. Why do you generate the tree and then evaluate it? Can't you evaluate the components directly in the code which currently generates the tree structure? If you have operators like "+" and "*" then consider using operator.add and operator.mul instead, which can work directly on the data without using an intermediate step.
==update==
This builds on Paul Hankin's answer. What I've done is taken away the intermediate tree structure and just evaluate the expression directly.
def build_tree2(n):
if n == 0:
return random.randrange(100)
else:
left = build_tree2(n-1)
right = build_tree2(n-1)
return left+right
That clocks at about 5 times faster than Paul's solution.
It may be that you need to know the actual tree structure of the best solution, or the top k of N, where k << N. If that's the case then you can post-hoc regenerate those trees if you also keep track of the RNG state used to generate the results. For example:
def build_tree3(n, rng=random._inst):
state = rng.getstate()
return _build_tree3(n, rng.randrange), state
def _build_tree3(n, randrange):
if n == 0:
return randrange(100)
else:
left = _build_tree3(n-1, randrange)
right = _build_tree3(n-1, randrange)
return left+right
Once you've found the best values, use the key to regenerate the tree
# Build Paul's tree data structure given a specific RNG
def build_tree4(n, rng):
if n == 0:
return ConstantNode(rng.randrange(100))
else:
left = build_tree4(n-1, rng)
right = build_tree4(n-1, rng)
return ArithmeticOperatorNode("+", left, right)
# This is a O(n log(n)) way to get the best k.
# An O(k log(k)) time solution is possible.
rng = random.Random()
best_5 = sorted(build_tree3(8, rng) for i in range(10000))[:5]
for value, state in best_5:
rng.setstate(state)
tree = build_tree4(8, rng)
print tree.eval(), "should be", value
print " ", str(tree)[:50] + " ..."
Here's what it looks like when I run it
10793 should be 10793
((((((((92 + 75) + (35 + 69)) + ((39 + 79) + (6 + ...
10814 should be 10814
((((((((50 + 63) + (6 + 21)) + ((75 + 98) + (76 + ...
10892 should be 10892
((((((((51 + 25) + (5 + 32)) + ((40 + 71) + (17 + ...
11070 should be 11070
((((((((7 + 83) + (77 + 56)) + ((16 + 29) + (2 + 1 ...
11125 should be 11125
((((((((69 + 80) + (11 + 64)) + ((33 + 21) + (95 + ...
|
Python: Optimizing a tree evaluator
|
I know tree is a well studied structure.
I'm writing a program that randomly generates many expression trees and then sorts and selects by a fitness attribute.
I have a class MakeTreeInOrder() that turns the tree into a string that 'eval' can evaluate.
but it gets called many many times, and should be optimized for time.
below is a function that builds a tree that adds successive numbers to use as a test.
I was wondering if there is an optimized way to evaluate an expression that is in a tree structure. I figured that
that it's used quite a bit and somebodys already done this.
import itertools
from collections import namedtuple
#Further developing Torsten Marek's second suggestion
KS = itertools.count()
Node = namedtuple("Node", ["cargo", "args"])
def build_nodes (depth = 5):
if (depth <= 0):
this_node = Node((str(KS.next())), [None, None])
return this_node
else:
this_node = Node('+', [])
this_node.args.extend(
build_nodes(depth = depth - (i + 1))
for i in range(2))
return this_node
The following is the code that I think can be made a lot faster. And I was hoping for some ideas.
class MakeTreeInOrder(object):
def __init__(self, node):
object.__init__(self)
self.node = node
self.str = ''
def makeit(self, nnode = ''):
if nnode == '':
nnode = self.node
if nnode == None: return
self.str +='('
self.makeit(nnode.args[0])
self.str += nnode.cargo
self.makeit(nnode.args[1])
self.str+=')'
return self.str
def Main():
this_tree = build_nodes()
expression_generator = MakeTreeInOrder(this_tree)
this_expression = expression_generator.makeit()
print this_expression
print eval(this_expression)
if __name__ == '__main__':
rresult = Main()
|
[
"Adding a touch of object orientation here makes things simpler. Have subclasses of Node for each thing in your tree, and use an 'eval' method to evaluate them.\nimport random\n\nclass ArithmeticOperatorNode(object):\n def __init__(self, operator, *args):\n self.operator = operator\n self.children = args\n def eval(self):\n if self.operator == '+':\n return sum(x.eval() for x in self.children)\n assert False, 'Unknown arithmetic operator ' + self.operator\n def __str__(self):\n return '(%s)' % (' ' + self.operator + ' ').join(str(x) for x in self.children)\n\nclass ConstantNode(object):\n def __init__(self, constant):\n self.constant = constant\n def eval(self):\n return self.constant\n def __str__(self):\n return str(self.constant)\n\ndef build_tree(n):\n if n == 0:\n return ConstantNode(random.randrange(100))\n else:\n left = build_tree(n - 1)\n right = build_tree(n - 1)\n return ArithmeticOperatorNode('+', left, right)\n\nnode = build_tree(5)\nprint node\nprint node.eval()\n\nTo evaluate the tree, just call .eval() on the top level node.\nnode = build_tree(5)\nprint node.eval()\n\nI also added a __str__ method to convert the tree to a string so you can see how this generalizes to other tree functions. It just does '+' at the moment, but hopefully it's clear how to extend this to the full range of arithmetic operations.\n",
"Your example imports numpy and random but never uses them. It also has a \"for i in range(2))\" with no body. This is clearly not valid Python code.\nYou don't define what 'cargo' and the nodes are supposed to contain. It appears that 'cargo' is a number, since it comes from itertools.count().next(). But that makes no sense since you want the result to be a eval'able Python string.\nIf you are doing a one-time evaluation of the tree then the fastest solution would be to evaluate it directly in-place, but without an actual example of the data you're working with, I can't show an example.\nIf you want to make it even faster then look further upstream. Why do you generate the tree and then evaluate it? Can't you evaluate the components directly in the code which currently generates the tree structure? If you have operators like \"+\" and \"*\" then consider using operator.add and operator.mul instead, which can work directly on the data without using an intermediate step.\n==update==\nThis builds on Paul Hankin's answer. What I've done is taken away the intermediate tree structure and just evaluate the expression directly.\ndef build_tree2(n):\n if n == 0:\n return random.randrange(100)\n else:\n left = build_tree2(n-1)\n right = build_tree2(n-1)\n return left+right\n\nThat clocks at about 5 times faster than Paul's solution.\nIt may be that you need to know the actual tree structure of the best solution, or the top k of N, where k << N. If that's the case then you can post-hoc regenerate those trees if you also keep track of the RNG state used to generate the results. For example:\ndef build_tree3(n, rng=random._inst):\n state = rng.getstate()\n return _build_tree3(n, rng.randrange), state\n\ndef _build_tree3(n, randrange):\n if n == 0:\n return randrange(100)\n else:\n left = _build_tree3(n-1, randrange)\n right = _build_tree3(n-1, randrange)\n return left+right\n\nOnce you've found the best values, use the key to regenerate the tree\n# Build Paul's tree data structure given a specific RNG\ndef build_tree4(n, rng):\n if n == 0:\n return ConstantNode(rng.randrange(100))\n else:\n left = build_tree4(n-1, rng)\n right = build_tree4(n-1, rng)\n return ArithmeticOperatorNode(\"+\", left, right)\n\n# This is a O(n log(n)) way to get the best k.\n# An O(k log(k)) time solution is possible.\nrng = random.Random()\nbest_5 = sorted(build_tree3(8, rng) for i in range(10000))[:5]\nfor value, state in best_5:\n rng.setstate(state)\n tree = build_tree4(8, rng)\n print tree.eval(), \"should be\", value\n print \" \", str(tree)[:50] + \" ...\"\n\nHere's what it looks like when I run it\n10793 should be 10793\n ((((((((92 + 75) + (35 + 69)) + ((39 + 79) + (6 + ...\n10814 should be 10814\n ((((((((50 + 63) + (6 + 21)) + ((75 + 98) + (76 + ...\n10892 should be 10892\n ((((((((51 + 25) + (5 + 32)) + ((40 + 71) + (17 + ...\n11070 should be 11070\n ((((((((7 + 83) + (77 + 56)) + ((16 + 29) + (2 + 1 ...\n11125 should be 11125\n ((((((((69 + 80) + (11 + 64)) + ((33 + 21) + (95 + ...\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"optimization",
"python"
] |
stackoverflow_0002169682_optimization_python.txt
|
Q:
Why (dictionary.keys()).sort() is not working in python?
I'm new to Python and can't understand why a thing like this does not work.
I can't find the issue raised elsewhere either.
toto = {'a':1, 'c':2 , 'b':3}
toto.keys().sort() #does not work (yields none)
(toto.keys()).sort() #does not work (yields none)
eval('toto.keys()').sort() #does not work (yields none)
Yet if I inspect the type I see that I invoke sort() on a list, so what is the problem..
toto.keys().__class__ # yields <type 'list'>
The only way I have this to work is by adding some temporary variable, which is ugly
temp = toto.keys()
temp.sort()
What am I missing here, there must be a nicer way to do it.
A:
sort() sorts the list in place. It returns None to prevent you from thinking that it's leaving the original list alone and returning a sorted copy of it.
A:
sorted(toto.keys())
Should do what you want. The sort method you're using sorts in place and returns None.
A:
sort() method sort in place, returning none. You have to use sorted(toto.keys()) which returns a new iterable, sorted.
|
Why (dictionary.keys()).sort() is not working in python?
|
I'm new to Python and can't understand why a thing like this does not work.
I can't find the issue raised elsewhere either.
toto = {'a':1, 'c':2 , 'b':3}
toto.keys().sort() #does not work (yields none)
(toto.keys()).sort() #does not work (yields none)
eval('toto.keys()').sort() #does not work (yields none)
Yet if I inspect the type I see that I invoke sort() on a list, so what is the problem..
toto.keys().__class__ # yields <type 'list'>
The only way I have this to work is by adding some temporary variable, which is ugly
temp = toto.keys()
temp.sort()
What am I missing here, there must be a nicer way to do it.
|
[
"sort() sorts the list in place. It returns None to prevent you from thinking that it's leaving the original list alone and returning a sorted copy of it.\n",
"sorted(toto.keys())\n\nShould do what you want. The sort method you're using sorts in place and returns None.\n",
"sort() method sort in place, returning none. You have to use sorted(toto.keys()) which returns a new iterable, sorted.\n"
] |
[
6,
6,
1
] |
[] |
[] |
[
"python",
"sorting"
] |
stackoverflow_0002170632_python_sorting.txt
|
Q:
Pylons and AuthKit OpenID problem
I have troubles setting up the support for openID authentication, using authkit and pylons.
I set up everything as described in the cookbook, but still get the following error:
File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 480, in __call__
return self.app(environ, start_response)
File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 218, in __call__
self.session_middleware
AuthKitConfigError: The session middleware 'beaker.session' is not present. Have you set up the session middleware?
(The full traceback is quite uninformative, just a chain of middleware calls)
My config is the following:
authkit.setup.method = openid, cookie
# TODO authkit.openid.template.file =
authkit.cookie.params.httponly = true
authkit.openid.store.type = file
authkit.openid.store.config = %(here)s/data
authkit.openid.session.middleware = beaker.session
authkit.openid.session.key = authkit_openid
authkit.openid.baseurl = http://mysite.moc
authkit.openid.path.signedin = /main/cabinet
authkit.openid.authenticate.user.encrypt = authkit.users:md5
The beaker middleware is definitely loaded, here is my make_app function (yes, the pylons version check is true):
| # Configure the Pylons environment
| load_environment(global_conf, app_conf)
|
| # The Pylons WSGI app
| app = PylonsApp()
| app = UserMiddleware(app)
|
| if pylons.__version__ >= "0.9.7":
|- from beaker.middleware import SessionMiddleware
|| from routes.middleware import RoutesMiddleware
|| app = RoutesMiddleware(app, config['routes.map'])
|| app = SessionMiddleware(app, app_conf)
|
|
| if asbool(full_stack):
| # Handle Python exceptions
|
|- app = authkit.authenticate.middleware(app, app_conf)
|| # Display error documents for 401, 403, 404 status codes (and
|| # 500 when debug is disabled)
|| if pylons.__version__ >= "0.9.7":
||- app = ErrorHandler(app, global_conf,
23- **config['pylons.errorware'])
||| from pylons.middleware import StatusCodeRedirect
||| if asbool(config['debug']):
23- app = StatusCodeRedirect(app)
||| else:
23- app = StatusCodeRedirect(app, [401, 403, 404, 500])
|| else:
||- app = ErrorHandler(app, global_conf, error_template = error_template,
23- **config['pylons.errorware'])
||| app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf)
|
| # Establish the Registry for this application
| app = RegistryManager(app)
|
| # Static files
| javascripts_app = StaticJavascripts()
| static_app = StaticURLParser(config['pylons.paths']['static_files'])
| app = Cascade([static_app, javascripts_app, app])
| return app
Does anyone have any idea, what is going on here?
A:
Take this line in your middleware.py:
app = authkit.authenticate.middleware(app, app_conf)
And move it immediately below this line:
app = PylonsApp()
|
Pylons and AuthKit OpenID problem
|
I have troubles setting up the support for openID authentication, using authkit and pylons.
I set up everything as described in the cookbook, but still get the following error:
File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 480, in __call__
return self.app(environ, start_response)
File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 218, in __call__
self.session_middleware
AuthKitConfigError: The session middleware 'beaker.session' is not present. Have you set up the session middleware?
(The full traceback is quite uninformative, just a chain of middleware calls)
My config is the following:
authkit.setup.method = openid, cookie
# TODO authkit.openid.template.file =
authkit.cookie.params.httponly = true
authkit.openid.store.type = file
authkit.openid.store.config = %(here)s/data
authkit.openid.session.middleware = beaker.session
authkit.openid.session.key = authkit_openid
authkit.openid.baseurl = http://mysite.moc
authkit.openid.path.signedin = /main/cabinet
authkit.openid.authenticate.user.encrypt = authkit.users:md5
The beaker middleware is definitely loaded, here is my make_app function (yes, the pylons version check is true):
| # Configure the Pylons environment
| load_environment(global_conf, app_conf)
|
| # The Pylons WSGI app
| app = PylonsApp()
| app = UserMiddleware(app)
|
| if pylons.__version__ >= "0.9.7":
|- from beaker.middleware import SessionMiddleware
|| from routes.middleware import RoutesMiddleware
|| app = RoutesMiddleware(app, config['routes.map'])
|| app = SessionMiddleware(app, app_conf)
|
|
| if asbool(full_stack):
| # Handle Python exceptions
|
|- app = authkit.authenticate.middleware(app, app_conf)
|| # Display error documents for 401, 403, 404 status codes (and
|| # 500 when debug is disabled)
|| if pylons.__version__ >= "0.9.7":
||- app = ErrorHandler(app, global_conf,
23- **config['pylons.errorware'])
||| from pylons.middleware import StatusCodeRedirect
||| if asbool(config['debug']):
23- app = StatusCodeRedirect(app)
||| else:
23- app = StatusCodeRedirect(app, [401, 403, 404, 500])
|| else:
||- app = ErrorHandler(app, global_conf, error_template = error_template,
23- **config['pylons.errorware'])
||| app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf)
|
| # Establish the Registry for this application
| app = RegistryManager(app)
|
| # Static files
| javascripts_app = StaticJavascripts()
| static_app = StaticURLParser(config['pylons.paths']['static_files'])
| app = Cascade([static_app, javascripts_app, app])
| return app
Does anyone have any idea, what is going on here?
|
[
"Take this line in your middleware.py:\napp = authkit.authenticate.middleware(app, app_conf)\n\nAnd move it immediately below this line:\napp = PylonsApp()\n\n"
] |
[
4
] |
[] |
[] |
[
"authkit",
"openid",
"pylons",
"python"
] |
stackoverflow_0002095120_authkit_openid_pylons_python.txt
|
Q:
Python __init__ argument problem
I have some trouble understanding what happens with class init arguments that are lists
like:
class A(object):
def __init__(self, argument=[]):
self.argument = argument[:]
or:
def __init__(self,argument=None):
self.arguments = arguments or []
or:
def __init__(self, argument=[]):
self.argument = argument
This can't be done because the default value for every A object would point to the same piece of memory. I can't really understand what happens here and how it happens.
A:
This is a well known python gotcha.
Basically, the default for that argument is created when the method is first defined, and since it is a mutable object (in this case, a list), it just referes to the same object even after it has changed, and even in subsequent calls to the method.
The usual way to deal with cases like that is to treat it like in your second example:
def __init__(self, arguments=None):
self.arguments = arguments or []
But if what you want to do is have a list with all your arguments you could just use Python's argument unpacking.
It works like this:
def my_function(*args):
print args
then, you will have in your method access to a tuple with all the arguments passed. So if you called your function like this:
>>> my_function(1, 2, 3)
Your output would look like:
(1, 2, 3)
The cool thing is, you can always use it in the oposite way, so, lets suppose you have a list (or tuple), and you want to pass every item in the list as a positional argument to your function. You would do this:
>>> my_list = [1, 2, 3]
>>> my_function(*my_list)
And, as far as your function is concerned, it is the same as the previous call.
You should read the documentation that I pointed to, as well as the section that goes a little more deeply on defining functions.
A:
The list is created when the definition is run, not when the method is executed.
A:
I think the question is somewhat unclear, but what I understand from it is that you are wondering how passing a class init a list doesn't make the internal object the same one you pass it, but rather a copy. If this is not the question, tell me, and I'll delete this answer.
Briefly, here's how it works: nothing is stored as a name by value in Python. Everything is stored internally as a pointer to a Python object. When you do:
a = [1,2,3]
b = a
You're not setting b to the value of a. You're setting b to reference the same object. So the statement:
a is b
Is true, as the names reference the same object.
a = [1,2,3]
b = [1,2,3]
a is b
This will return false. The reason is that now you have created two different objects. So the line:
self.argument = argument[:]
is a (necessary) way of making a copy of self.argument so that it doesn't reference the same object.
|
Python __init__ argument problem
|
I have some trouble understanding what happens with class init arguments that are lists
like:
class A(object):
def __init__(self, argument=[]):
self.argument = argument[:]
or:
def __init__(self,argument=None):
self.arguments = arguments or []
or:
def __init__(self, argument=[]):
self.argument = argument
This can't be done because the default value for every A object would point to the same piece of memory. I can't really understand what happens here and how it happens.
|
[
"This is a well known python gotcha.\nBasically, the default for that argument is created when the method is first defined, and since it is a mutable object (in this case, a list), it just referes to the same object even after it has changed, and even in subsequent calls to the method.\nThe usual way to deal with cases like that is to treat it like in your second example:\ndef __init__(self, arguments=None): \n self.arguments = arguments or []\n\nBut if what you want to do is have a list with all your arguments you could just use Python's argument unpacking.\nIt works like this:\ndef my_function(*args):\n print args\n\nthen, you will have in your method access to a tuple with all the arguments passed. So if you called your function like this:\n>>> my_function(1, 2, 3)\n\nYour output would look like:\n(1, 2, 3)\n\nThe cool thing is, you can always use it in the oposite way, so, lets suppose you have a list (or tuple), and you want to pass every item in the list as a positional argument to your function. You would do this:\n>>> my_list = [1, 2, 3]\n>>> my_function(*my_list)\n\nAnd, as far as your function is concerned, it is the same as the previous call.\nYou should read the documentation that I pointed to, as well as the section that goes a little more deeply on defining functions.\n",
"The list is created when the definition is run, not when the method is executed.\n",
"I think the question is somewhat unclear, but what I understand from it is that you are wondering how passing a class init a list doesn't make the internal object the same one you pass it, but rather a copy. If this is not the question, tell me, and I'll delete this answer.\nBriefly, here's how it works: nothing is stored as a name by value in Python. Everything is stored internally as a pointer to a Python object. When you do:\na = [1,2,3]\nb = a\n\nYou're not setting b to the value of a. You're setting b to reference the same object. So the statement:\na is b\n\nIs true, as the names reference the same object.\na = [1,2,3]\nb = [1,2,3]\na is b\n\nThis will return false. The reason is that now you have created two different objects. So the line:\nself.argument = argument[:]\n\nis a (necessary) way of making a copy of self.argument so that it doesn't reference the same object.\n"
] |
[
6,
4,
1
] |
[] |
[] |
[
"class",
"equality",
"identity",
"list",
"python"
] |
stackoverflow_0002170684_class_equality_identity_list_python.txt
|
Q:
Using Python Reg Exp to read data from file
I'm having trouble using python reg exp to read data from a file.
The file has data I want and some info I'm not interested in. An example of the info I'm interested in is below. The number of rows will vary
FREQ VM(VOUT)
1.000E+00 4.760E+01
1.002E+00 4.749E+01
Y
I want to create a list of tuples like:
[(1.000, 47.6),(1.002, 47.49)]
I'm trying to read the file till I find the 'FREQ VM(VOUT)' line and read the data points till I hit the 'Y'.
I have 2 questions:
Is it possible to get all the points with one expression or do I need to loop through each line and look for the start end? I can't seem to get the the reg exp to work when I try to find the section and read the points in a single expression.
How do I parse a number that is in engineering notation?
I couldn't find an example that was very close to what I'm doing. If it is out there, please point me to it.
A:
I think this will get you what you want. As long as the file is consistent.
from csv import reader
with open('file') as f:
listoftuples = [(float(row[0]), float(row[1]))
for row in reader(f, delimiter=' ')
if row and row[0] != 'FREQ']
If you want it to break at 'Y', then do this less elegant thingy:
from csv import reader
l = []
with open('file') as f:
for row in reader(f, delimiter=' '):
if row[0] == 'Y':
break
if row and row[0] != 'FREQ':
l.append((floar(row[0]), float(row[1])))
A:
import decimal
flag=0
result=[]
for line in open("file"):
line=line.rstrip()
if line == "Y": flag=0
if line.startswith("FREQ VM"):
flag=1
continue
if flag and line:
result.append(map(decimal.Decimal,line.split()))
print result
A:
Not nearly as elegant as Tor's answer. No regexps either. Bring on the downvotes!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import decimal
import os
def main():
we_care = False # start off not caring
list_of_tuples = []
f = open('test.txt','r')
for line in f:
if line.startswith('FREQ'):
we_care = True # we found what we want; now we care
continue
if we_care:
try:
x,y = (decimal.Decimal(x)
for x in line.rstrip(os.linesep).split())
list_of_tuples.append((x,y))
except ValueError:
pass # we get here when a line doesn't contain two floats
except decimal.InvalidOperation:
pass # we get here when a line contains a non-decimal
if line.startswith('Y'):
break # break out of processing once you've got your data
return list_of_tuples
if __name__ == "__main__":
print main()
Returns:
[(Decimal('1.000'), Decimal('47.60')), (Decimal('1.002'), Decimal('47.49'))]
|
Using Python Reg Exp to read data from file
|
I'm having trouble using python reg exp to read data from a file.
The file has data I want and some info I'm not interested in. An example of the info I'm interested in is below. The number of rows will vary
FREQ VM(VOUT)
1.000E+00 4.760E+01
1.002E+00 4.749E+01
Y
I want to create a list of tuples like:
[(1.000, 47.6),(1.002, 47.49)]
I'm trying to read the file till I find the 'FREQ VM(VOUT)' line and read the data points till I hit the 'Y'.
I have 2 questions:
Is it possible to get all the points with one expression or do I need to loop through each line and look for the start end? I can't seem to get the the reg exp to work when I try to find the section and read the points in a single expression.
How do I parse a number that is in engineering notation?
I couldn't find an example that was very close to what I'm doing. If it is out there, please point me to it.
|
[
"I think this will get you what you want. As long as the file is consistent.\nfrom csv import reader\nwith open('file') as f:\n listoftuples = [(float(row[0]), float(row[1])) \n for row in reader(f, delimiter=' ') \n if row and row[0] != 'FREQ']\n\nIf you want it to break at 'Y', then do this less elegant thingy:\nfrom csv import reader\nl = []\nwith open('file') as f:\n for row in reader(f, delimiter=' '):\n if row[0] == 'Y':\n break\n if row and row[0] != 'FREQ':\n l.append((floar(row[0]), float(row[1])))\n\n",
"import decimal\nflag=0\nresult=[]\nfor line in open(\"file\"):\n line=line.rstrip()\n if line == \"Y\": flag=0\n if line.startswith(\"FREQ VM\"):\n flag=1\n continue\n if flag and line:\n result.append(map(decimal.Decimal,line.split()))\nprint result\n\n",
"Not nearly as elegant as Tor's answer. No regexps either. Bring on the downvotes!\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport decimal\nimport os\n\ndef main():\n we_care = False # start off not caring \n\n list_of_tuples = []\n\n f = open('test.txt','r')\n\n for line in f:\n if line.startswith('FREQ'):\n we_care = True # we found what we want; now we care\n continue\n if we_care:\n try:\n x,y = (decimal.Decimal(x) \n for x in line.rstrip(os.linesep).split())\n list_of_tuples.append((x,y))\n except ValueError:\n pass # we get here when a line doesn't contain two floats\n except decimal.InvalidOperation:\n pass # we get here when a line contains a non-decimal\n if line.startswith('Y'):\n break # break out of processing once you've got your data\n return list_of_tuples\n\nif __name__ == \"__main__\":\n print main()\n\nReturns: \n[(Decimal('1.000'), Decimal('47.60')), (Decimal('1.002'), Decimal('47.49'))]\n\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002170461_python_regex.txt
|
Q:
Trouble with MySQL UPDATE syntax with the module mysqldb in Python
I am attempting to execute the following query via the mysqldb module in python:
for i in self.p.parameter_type:
cursor.execute("""UPDATE parameters SET %s = %s WHERE parameter_set_name = %s""" % (i,
float(getattr(self.p, i)), self.list_box_parameter.GetStringSelection()))
I keep getting the error: "Unknown column 'M1' in 'where clause'". I want to update columns i with the value getattr(self.p, i), but only in rows that have the column parameter_set_name equal to self.list_box_parameter.GetStringSelection(). The error suggests that my query is looking for columns by the name 'M1' in the WHERE clause. Why is the above query incorrect and how can I correct it?
A:
i see now, i think you need to enclose parameter_set_name = %s in quotes such as:
parameter_set_name = "%s"
otherwise it's trying to acces column M1
so:
cursor.execute("""UPDATE parameters SET %s = %s WHERE parameter_set_name = \"%s\" """ % (i, float(getattr(self.p, i)), self.list_box_parameter.GetStringSelection()))
A:
It looks like query is formed with wrong syntax.
Could you display string parameter of cursor.execute?
|
Trouble with MySQL UPDATE syntax with the module mysqldb in Python
|
I am attempting to execute the following query via the mysqldb module in python:
for i in self.p.parameter_type:
cursor.execute("""UPDATE parameters SET %s = %s WHERE parameter_set_name = %s""" % (i,
float(getattr(self.p, i)), self.list_box_parameter.GetStringSelection()))
I keep getting the error: "Unknown column 'M1' in 'where clause'". I want to update columns i with the value getattr(self.p, i), but only in rows that have the column parameter_set_name equal to self.list_box_parameter.GetStringSelection(). The error suggests that my query is looking for columns by the name 'M1' in the WHERE clause. Why is the above query incorrect and how can I correct it?
|
[
"i see now, i think you need to enclose parameter_set_name = %s in quotes such as:\nparameter_set_name = \"%s\"\n\notherwise it's trying to acces column M1\nso:\ncursor.execute(\"\"\"UPDATE parameters SET %s = %s WHERE parameter_set_name = \\\"%s\\\" \"\"\" % (i, float(getattr(self.p, i)), self.list_box_parameter.GetStringSelection()))\n\n",
"It looks like query is formed with wrong syntax.\nCould you display string parameter of cursor.execute?\n"
] |
[
1,
0
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0002171072_mysql_python.txt
|
Q:
no module names _mysql; where is _mysql
import MySQLdb
and
traceback:
Traceback (most recent call last):
File "D:\zjm_code\sphinx_test\a.py", line 1, in <module>
import MySQLdb
File "D:\zjm_code\sphinx_test\MySQLdb\__init__.py", line 19, in <module>
import _mysql
ImportError: No module named _mysql
A:
You need to install MySQLdb correctly. It consists of the python module and platform-dependent library (_mysql.dll in your case). Use the win32 installer from the project page instead of installing just by unpacking sources.
|
no module names _mysql; where is _mysql
|
import MySQLdb
and
traceback:
Traceback (most recent call last):
File "D:\zjm_code\sphinx_test\a.py", line 1, in <module>
import MySQLdb
File "D:\zjm_code\sphinx_test\MySQLdb\__init__.py", line 19, in <module>
import _mysql
ImportError: No module named _mysql
|
[
"You need to install MySQLdb correctly. It consists of the python module and platform-dependent library (_mysql.dll in your case). Use the win32 installer from the project page instead of installing just by unpacking sources.\n"
] |
[
3
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0002171078_mysql_python.txt
|
Q:
Python - Display string containing entity references as normal text
I have a Python string "''Grassmere''"
as retrieved from a website.
I would like to have the ' displayed as the correct ascii symbol (') but for some reason python insists on just printing the ascii code.
A:
Batteries are included for this one
>>> import xmllib
>>> X=xmllib.XMLParser()
>>> X.translate_references("''Grassmere''")
"''Grassmere''"
A:
Or without additional modules:
re.sub("&#(\d+);", lambda m: chr(int(m.group(1))), "''Grassmere''")
|
Python - Display string containing entity references as normal text
|
I have a Python string "''Grassmere''"
as retrieved from a website.
I would like to have the ' displayed as the correct ascii symbol (') but for some reason python insists on just printing the ascii code.
|
[
"Batteries are included for this one\n>>> import xmllib\n>>> X=xmllib.XMLParser()\n>>> X.translate_references(\"''Grassmere''\")\n\"''Grassmere''\"\n\n",
"Or without additional modules:\nre.sub(\"&#(\\d+);\", lambda m: chr(int(m.group(1))), \"''Grassmere''\")\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002171084_python.txt
|
Q:
Django and NoneType object is not callable
I have such model:
class Body(models.Model):
point = models.TextField()
description = models.TextField(blank = True)
order = models.IntegerField(default = 0, blank = True)
When I am adding in django admin interface a new record I am getting
'NoneType' object is not callable
with TemplateSyntaxError message. So, record is successfully created but I can't see the list of records in django admin panel.
http://dpaste.com/hold/152729/ this is the link to the traceback from django
What should I do?
A:
I've found that
order = models.IntegerField(default = 0, blank = True)
was the reason of my problem. When I've changed 'order' name to something else I've got my problem fixed. :)
|
Django and NoneType object is not callable
|
I have such model:
class Body(models.Model):
point = models.TextField()
description = models.TextField(blank = True)
order = models.IntegerField(default = 0, blank = True)
When I am adding in django admin interface a new record I am getting
'NoneType' object is not callable
with TemplateSyntaxError message. So, record is successfully created but I can't see the list of records in django admin panel.
http://dpaste.com/hold/152729/ this is the link to the traceback from django
What should I do?
|
[
"I've found that \norder = models.IntegerField(default = 0, blank = True)\n\nwas the reason of my problem. When I've changed 'order' name to something else I've got my problem fixed. :)\n"
] |
[
5
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002170303_django_python.txt
|
Q:
where is SeparatedValuesField in my code, i used sphinx
from django.db import models
from djangosphinx import SphinxSearch
# A sample model from iBegin
class City(models.Model):
name = models.CharField(max_length=32)
aliases = SeparatedValuesField(blank=True, null=True)#<-------this
slug = models.SlugField(blank=True)
country = models.ForeignKey(Country)
state = models.ForeignKey(State, blank=True, null=True)
listings = models.PositiveIntegerField(editable=False, default=0)
latitude = models.DecimalField(max_digits=9, decimal_places=6, editable=False, default=0, blank=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6, editable=False, default=0, blank=True)
date_added = CreatedDateTimeField(editable=False)
date_changed = ModifiedDateTimeField(editable=False)
class Meta:
unique_together = (('country', 'state', 'slug'), ('country', 'state', 'name'))
db_table = 'cities'
search = SphinxSearch(
index='cities', # defaults to cities either way
weights={ # individual field weighting, this is optional
'name': 100,
'aliases': 90,
}
)
when i 'python manage.py syncdb'
it print :
File "D:\zjm_code\sphinx_test\models.py", line 7, in City
aliases = SeparatedValuesField(blank=True, null=True)
NameError: name 'SeparatedValuesField' is not defined
what is the SeparatedValuesField ?
A:
Google finds this page, from the same (non-responsive here) blog.
A:
It seems to be a user-defined custom form field, one possible definition is on Django Snippets: http://www.djangosnippets.org/snippets/497/
The blog doesn't seem to be available right now, but perhaps the author has mentioned or used this snippet previously.
|
where is SeparatedValuesField in my code, i used sphinx
|
from django.db import models
from djangosphinx import SphinxSearch
# A sample model from iBegin
class City(models.Model):
name = models.CharField(max_length=32)
aliases = SeparatedValuesField(blank=True, null=True)#<-------this
slug = models.SlugField(blank=True)
country = models.ForeignKey(Country)
state = models.ForeignKey(State, blank=True, null=True)
listings = models.PositiveIntegerField(editable=False, default=0)
latitude = models.DecimalField(max_digits=9, decimal_places=6, editable=False, default=0, blank=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6, editable=False, default=0, blank=True)
date_added = CreatedDateTimeField(editable=False)
date_changed = ModifiedDateTimeField(editable=False)
class Meta:
unique_together = (('country', 'state', 'slug'), ('country', 'state', 'name'))
db_table = 'cities'
search = SphinxSearch(
index='cities', # defaults to cities either way
weights={ # individual field weighting, this is optional
'name': 100,
'aliases': 90,
}
)
when i 'python manage.py syncdb'
it print :
File "D:\zjm_code\sphinx_test\models.py", line 7, in City
aliases = SeparatedValuesField(blank=True, null=True)
NameError: name 'SeparatedValuesField' is not defined
what is the SeparatedValuesField ?
|
[
"Google finds this page, from the same (non-responsive here) blog.\n",
"It seems to be a user-defined custom form field, one possible definition is on Django Snippets: http://www.djangosnippets.org/snippets/497/\nThe blog doesn't seem to be available right now, but perhaps the author has mentioned or used this snippet previously.\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"django_sphinx",
"python"
] |
stackoverflow_0002171314_django_django_sphinx_python.txt
|
Q:
What Is The Best Way To Play Audio Through Qt?
I am building an application in pyQt4 and I want it to be able to play audio files. I was considering doing this through pyMedia as I could not get anywhere with the documentation, although the QAudio classes did initially look promising. It is important that the solution be cross-platform. Does anyone have any suggestions?
A:
As alex said, Phonon looks like your best bet because you can use it with Pyqt. You can find lots of examples of using phonon using google. This one, http://forum.kde.org/viewtopic.php?f=14&t=84275, for example is a command line tool to play audio using phonon. You might also want to take a look at the QSound class. QAudioInput looks interesting for adding support for a mike.
I hope this helps.
P.S.:
The riverbank site does mention the phonon module :)
I found a question on using Phonon + Pyqt - Play mp3 using Python, PyQt, and Phonon
A:
Use Phonon ( http://phonon.kde.org/ ). I used it from Java with success, so I expect it will work even better in Python/Linux.
This might also help:
http://0pointer.de/blog/projects/guide-to-sound-apis.html
|
What Is The Best Way To Play Audio Through Qt?
|
I am building an application in pyQt4 and I want it to be able to play audio files. I was considering doing this through pyMedia as I could not get anywhere with the documentation, although the QAudio classes did initially look promising. It is important that the solution be cross-platform. Does anyone have any suggestions?
|
[
"As alex said, Phonon looks like your best bet because you can use it with Pyqt. You can find lots of examples of using phonon using google. This one, http://forum.kde.org/viewtopic.php?f=14&t=84275, for example is a command line tool to play audio using phonon. You might also want to take a look at the QSound class. QAudioInput looks interesting for adding support for a mike.\nI hope this helps.\nP.S.: \n\nThe riverbank site does mention the phonon module :)\nI found a question on using Phonon + Pyqt - Play mp3 using Python, PyQt, and Phonon\n\n",
"Use Phonon ( http://phonon.kde.org/ ). I used it from Java with success, so I expect it will work even better in Python/Linux.\nThis might also help:\nhttp://0pointer.de/blog/projects/guide-to-sound-apis.html\n"
] |
[
2,
1
] |
[] |
[] |
[
"audio",
"pyqt4",
"python"
] |
stackoverflow_0002171232_audio_pyqt4_python.txt
|
Q:
How to change caps lock status without key press
I am using a python program that is activate when pressing Caps Lock key and I want to be able to turn on/off the caps lock status when the program is active.
I tried to send keys with virtkey but it obviously don't work since the keys just activate the app and don't change the caps lock status. So what is the best way to achieve this with python?
I'm using Ubuntu
A:
On Linux:
import fcntl
import os
KDSETLED = 0x4B32
console_fd = os.open('/dev/console', os.O_NOCTTY)
# Turn on caps lock
fcntl.ioctl(console_fd, KDSETLED, 0x04)
# Turn off caps lock
fcntl.ioctl(console_fd, KDSETLED, 0)
Source: Benji York - Stack Overflow: Change keyboard locks in Python
On Windows:
You should be able to use SendKeys for this, as in the following example:
import SendKeys
SendKeys.SendKeys("""
{CAPSLOCK}
""")
A:
Use sendkeys to change the status and keyboardleds to change the LED indicators.
sendkeys:
From another SO dicussion:
import SendKeys
SendKeys.SendKeys("""
{CAPSLOCK}
{SCROLLOCK}
{NUMLOCK}
""")
keyboardleds:
This package seems to work only for POSIX (which is OK if you're using Ubuntu), and you can read more here.
|
How to change caps lock status without key press
|
I am using a python program that is activate when pressing Caps Lock key and I want to be able to turn on/off the caps lock status when the program is active.
I tried to send keys with virtkey but it obviously don't work since the keys just activate the app and don't change the caps lock status. So what is the best way to achieve this with python?
I'm using Ubuntu
|
[
"On Linux:\nimport fcntl\nimport os\n\nKDSETLED = 0x4B32\n\nconsole_fd = os.open('/dev/console', os.O_NOCTTY)\n\n# Turn on caps lock\nfcntl.ioctl(console_fd, KDSETLED, 0x04)\n\n# Turn off caps lock\nfcntl.ioctl(console_fd, KDSETLED, 0)\n\nSource: Benji York - Stack Overflow: Change keyboard locks in Python\n\nOn Windows: \nYou should be able to use SendKeys for this, as in the following example: \nimport SendKeys\n\nSendKeys.SendKeys(\"\"\"\n{CAPSLOCK}\n\"\"\")\n\n",
"Use sendkeys to change the status and keyboardleds to change the LED indicators.\nsendkeys:\nFrom another SO dicussion:\nimport SendKeys\n\nSendKeys.SendKeys(\"\"\"\n{CAPSLOCK}\n{SCROLLOCK}\n{NUMLOCK}\n\"\"\")\n\nkeyboardleds:\nThis package seems to work only for POSIX (which is OK if you're using Ubuntu), and you can read more here.\n"
] |
[
6,
2
] |
[] |
[] |
[
"capslock",
"keyboard",
"python"
] |
stackoverflow_0002171408_capslock_keyboard_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.