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: Turbogears2 and py.test I'm switching our testing environment from Nose to py.test for testing a Turbogears2 web application. Currently, when Nose runs it gathers information from a testing configuration file (test.ini) that holds all the testing variables the application needs. And it seems to do so in an automatic way (I'm simply running nosetests and everything gets loaded) The problem relies in the inability for py.test to be pointed at the right INI configuration file so that I can get the app loaded with the variables I need. Currently, the failing point is pylons.app_globals which is simply non-existent when running py.test (hence everything fails). I have been through the Turbogears documentation but they only mention Nose/nosetests and nothing else. Is there a way to be able to lead the application with the testing variables I rely upon with py.test ? A: As far as py.test's part is concerned, you can implement something like this: # content of conftest.py def pytest_sessionstart(): # setup resources before any test is executed def pytest_sessionfinish(): # teardown resources after the last test has executed Such a conftest.py file should currently best live at your checkout root directory as py-1.3.4 will only run this hook if it sees it early enough. I also looked a bit around TurboGears but didn't erasily found the mechanism how/which test.ini is actually loaded. I can update the answer if somebody can provide this information. HTH. Holger
Turbogears2 and py.test
I'm switching our testing environment from Nose to py.test for testing a Turbogears2 web application. Currently, when Nose runs it gathers information from a testing configuration file (test.ini) that holds all the testing variables the application needs. And it seems to do so in an automatic way (I'm simply running nosetests and everything gets loaded) The problem relies in the inability for py.test to be pointed at the right INI configuration file so that I can get the app loaded with the variables I need. Currently, the failing point is pylons.app_globals which is simply non-existent when running py.test (hence everything fails). I have been through the Turbogears documentation but they only mention Nose/nosetests and nothing else. Is there a way to be able to lead the application with the testing variables I rely upon with py.test ?
[ "As far as py.test's part is concerned, you can implement something like this:\n# content of conftest.py\ndef pytest_sessionstart():\n # setup resources before any test is executed\n\ndef pytest_sessionfinish():\n # teardown resources after the last test has executed\n\nSuch a conftest.py file should currentl...
[ 1 ]
[]
[]
[ "pytest", "python", "testing", "turbogears", "unit_testing" ]
stackoverflow_0003835078_pytest_python_testing_turbogears_unit_testing.txt
Q: google storage api put file problem in python I'm trying to upload a file to Google storage, but my code freezes and does not respond. Please help me. Mycode : def PutFile(self,filename): conn = httplib.HTTPConnection("%s.commondatastorage.googleapis.com" % self.bucket) conn.set_debuglevel(2) dd = "%s" % datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT") strToSign = "PUT\n"+"\nimage/jpeg\n"+dd+"\nx-goog-acl:public-read\n/%s/x.jpg" % self.bucket f = open(filename,"r") m = hashlib.md5() m.update(f.read()) h = m.hexdigest() sig = base64.b64encode(hmac.new(self.secret, strToSign, hashlib.sha1).digest()) total = os.path.getsize(filename) header = {"Date":dd,"x-goog-acl":"public-read","Content-MD5":h,'Content-Length':total,'Content-Type':'image/jpeg','Authorization':"GOOG1 %s:%s" % (self.key,sig)} r1 = conn.getresponse() print r1.status, r1.reason print r1.read() conn.close() A: i resolve my problem myself :) my code : conn = httplib.HTTPConnection("mustafa-yontar.commondatastorage.googleapis.com") conn.set_debuglevel(2) f = open(filename,"r") m = hashlib.md5() m.update(f.read()) h = m.hexdigest() has = h dd = "%s" % datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT") strToSign = "PUT\n"+h+"\n\n"+dd+"\nx-goog-acl:public-read\n/mustafa-yontar/x.jpg" sig = base64.b64encode(hmac.new(self.secret, strToSign, hashlib.sha1).digest()) total = os.path.getsize(filename) header = {"Date":dd,"x-goog-acl":"public-read","Content-MD5":h,'Content-Length':total,'Authorization':"GOOG1 %s:%s" % (self.key,sig)} conn.putrequest('PUT', "/x.jpg") for h in header: conn.putheader(h, header[h]) conn.endheaders() bytess = open('x.jpg', 'rb').read() f = StringIO(bytess) f.seek(0) while True: bytes = f.read(1024) if not bytes: break length = len(bytes) conn.send('%X\r\n' % length) conn.send(bytes + '\r\n') conn.send('0\r\n\r\n') #errcode, errmsg, headers = conn.getresponse() #h.close() #conn.request("PUT","/mustafa-yontar/x.jpg",f.read(),header) r1 = conn.getresponse() print r1.status, r1.reason print r1.read() conn.close() print has A: I know this is a bit more of a comment than an answer to your issue, but I'm putting this in an answer because I can't comment yet. It would really help if you could narrow down the place in your function where it hangs. Although adding print functions/statements will change the state of memory slightly it could be worth a try here, as a likely source of hanging is the network calls you are making. Also - sounds simple, but are you sure that you are on the network and able to access the Google storage site?
google storage api put file problem in python
I'm trying to upload a file to Google storage, but my code freezes and does not respond. Please help me. Mycode : def PutFile(self,filename): conn = httplib.HTTPConnection("%s.commondatastorage.googleapis.com" % self.bucket) conn.set_debuglevel(2) dd = "%s" % datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT") strToSign = "PUT\n"+"\nimage/jpeg\n"+dd+"\nx-goog-acl:public-read\n/%s/x.jpg" % self.bucket f = open(filename,"r") m = hashlib.md5() m.update(f.read()) h = m.hexdigest() sig = base64.b64encode(hmac.new(self.secret, strToSign, hashlib.sha1).digest()) total = os.path.getsize(filename) header = {"Date":dd,"x-goog-acl":"public-read","Content-MD5":h,'Content-Length':total,'Content-Type':'image/jpeg','Authorization':"GOOG1 %s:%s" % (self.key,sig)} r1 = conn.getresponse() print r1.status, r1.reason print r1.read() conn.close()
[ "i resolve my problem myself :) my code :\n conn = httplib.HTTPConnection(\"mustafa-yontar.commondatastorage.googleapis.com\")\n conn.set_debuglevel(2)\n f = open(filename,\"r\")\n m = hashlib.md5()\n m.update(f.read())\n h = m.hexdigest()\n has = h\n dd = \"%...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003822385_python.txt
Q: Python and executing php files? Possible Duplicate: Start local PHP script w/ local Python script How do you execute a php file and then view the output of it? os.system("php ./index.php") Does not work only returns 0 A: What you need is the os.popen function. It runs the command and returns the stdout pipe for that commands output. You can also capture the stdin, stderr by using os.popen2, popen3 import os outp = os.popen('php ./index.php') text = outp.read() # this will block until php finishes # and returns with all output in text print text A: If you're working under Windows, you can use os.startfile().
Python and executing php files?
Possible Duplicate: Start local PHP script w/ local Python script How do you execute a php file and then view the output of it? os.system("php ./index.php") Does not work only returns 0
[ "What you need is the os.popen function. It runs the command and returns the stdout pipe for that commands output. You can also capture the stdin, stderr by using os.popen2, popen3\nimport os\n\noutp = os.popen('php ./index.php')\ntext = outp.read() # this will block until php finishes\n # and ret...
[ 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003837605_php_python.txt
Q: Popen.communicate() throws OSError: "[Errno 10] No child processes" I'm trying to start up a child process and get its output on Linux from Python using the subprocess module: #!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() However, I experience some flakiness: sometimes, p.communicate() would throw OSError: [Errno 10] No child processes What can cause this exception? Is there any non-determinism or race condition here that can cause flakiness? A: Are you intercepting SIGCHLD in the script? If you are then Popen will not run as expected since it relies on it's own handler for that signal. You can check for SIGCHLD handlers by commenting out the Popen call and then running: strace python <your_script.py> | grep SIGCHLD if you see something similar to: rt_sigaction(SIGCHLD, ...) then, you are in trouble. You need to disable the handler prior to calling Popen and then resetting it after communicate is done (this might introduce a race conditions so beware). signal.signal(SIGCHLD, handler) ... signal.signal(SIGCHLD, signal.SIG_DFL) ''' now you can go wild with Popen. WARNING!!! during this time no signals will be delivered to handler ''' ... signal.signal(SIGCHLD, handler) There is a python bug reported on this and as far as I see it hasn't been resolved yet: http://bugs.python.org/issue9127 Hope that helps. A: You might be running into the bug mentioned here: http://bugs.python.org/issue1731717 A: I'm not able to reproduce this on my Python (2.4.6-1ubuntu3). How are you running your script? How often does this occur? A: I ran into this problem using Python 2.6.4 which I built into my home directory (because I don't want to upgrade the "built-in" Python on the machine). I worked around it by replacing subprocess.Popen() with (the deprecated) os.popen3().
Popen.communicate() throws OSError: "[Errno 10] No child processes"
I'm trying to start up a child process and get its output on Linux from Python using the subprocess module: #!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() However, I experience some flakiness: sometimes, p.communicate() would throw OSError: [Errno 10] No child processes What can cause this exception? Is there any non-determinism or race condition here that can cause flakiness?
[ "Are you intercepting SIGCHLD in the script? If you are then Popen will not run as expected since it relies on it's own handler for that signal. \nYou can check for SIGCHLD handlers by commenting out the Popen call and then running:\nstrace python <your_script.py> | grep SIGCHLD\n\nif you see something similar to:\...
[ 7, 3, 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001008858_linux_python.txt
Q: Python : No translation file found for domain using custom locale folder I have the following structure : / |- main.py |- brainz | |- __init__.py | |- Brainz.py |- datas |- locale |- en_US |- LC_MESSAGES |- brainz.mo |- brainz.po In my __init__.py there is the following lines : import locale import gettext import os current_locale, encoding = locale.getdefaultlocale() locale_path = '../datas/locale/' + current_locale + '/LC_MESSAGES/' language = gettext.translation ( 'brainz', locale_path ) language.install() But when I try to run my program I got this error : Traceback (most recent call last): File "main.py", line 3, in <module> from brainz.Brainz import * File "/home/damien/BrainZ/brainz/__init__.py", line 11, in <module> language = gettext.translation ( 'brainz', locale_path ) File "/usr/lib/python2.6/gettext.py", line 484, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'brainz' I don't understand which path is expected by gettext.translation as I give a complete path to the .mo file. Could someone explain me what I have to do to load my translation files correctly ? Thanks, Damien A: I think your __init__.py should be something like: import locale import gettext import os current_locale, encoding = locale.getdefaultlocale() locale_path = 'datas/locale/' language = gettext.translation ('brainz', locale_path, [current_locale] ) language.install()
Python : No translation file found for domain using custom locale folder
I have the following structure : / |- main.py |- brainz | |- __init__.py | |- Brainz.py |- datas |- locale |- en_US |- LC_MESSAGES |- brainz.mo |- brainz.po In my __init__.py there is the following lines : import locale import gettext import os current_locale, encoding = locale.getdefaultlocale() locale_path = '../datas/locale/' + current_locale + '/LC_MESSAGES/' language = gettext.translation ( 'brainz', locale_path ) language.install() But when I try to run my program I got this error : Traceback (most recent call last): File "main.py", line 3, in <module> from brainz.Brainz import * File "/home/damien/BrainZ/brainz/__init__.py", line 11, in <module> language = gettext.translation ( 'brainz', locale_path ) File "/usr/lib/python2.6/gettext.py", line 484, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'brainz' I don't understand which path is expected by gettext.translation as I give a complete path to the .mo file. Could someone explain me what I have to do to load my translation files correctly ? Thanks, Damien
[ "I think your __init__.py should be something like:\nimport locale\nimport gettext\nimport os\n\ncurrent_locale, encoding = locale.getdefaultlocale()\n\nlocale_path = 'datas/locale/'\nlanguage = gettext.translation ('brainz', locale_path, [current_locale] )\nlanguage.install()\n\n" ]
[ 10 ]
[]
[]
[ "gettext", "python" ]
stackoverflow_0003837683_gettext_python.txt
Q: How to create a simple Gradient Descent algorithm I'm studying simple machine learning algorithms, beginning with a simple gradient descent, but I've got some trouble trying to implement it in python. Here is the example I'm trying to reproduce, I've got data about houses with the (living area (in feet2), and number of bedrooms) with the resulting price : Living area (feet2) : 2104 #bedrooms : 3 Price (1000$s) : 400 I'm trying to do a simple regression using the gradient descent method, but my algorithm won't work... The form of the algorithm is not using vectors on purpose (I'm trying to understand it step by step). i = 1 import sys derror=sys.maxint error = 0 step = 0.0001 dthresh = 0.1 import random theta1 = random.random() theta2 = random.random() theta0 = random.random() while derror>dthresh: diff = 400 - theta0 - 2104 * theta1 - 3 * theta2 theta0 = theta0 + step * diff * 1 theta1 = theta1 + step * diff * 2104 theta2 = theta2 + step * diff * 3 hserror = diff**2/2 derror = abs(error - hserror) error = hserror print 'iteration : %d, error : %s' % (i, error) i+=1 I understand the math, I'm constructing a predicting function with and being the variables (living area, number of bedrooms) and the estimated price. I'm using the cost function ( ) (for one point) : This is a usual problem, but I'm more of a software engineer and I'm learning one step at a time, can you tell me what's wrong ? I got it working with this code : data = {(2104, 3) : 400, (1600,3) : 330, (2400, 3) : 369, (1416, 2) : 232, (3000, 4) : 540} for x in range(10): i = 1 import sys derror=sys.maxint error = 0 step = 0.00000001 dthresh = 0.0000000001 import random theta1 = random.random()*100 theta2 = random.random()*100 theta0 = random.random()*100 while derror>dthresh: diff = 400 - (theta0 + 2104 * theta1 + 3 * theta2) theta0 = theta0 + step * diff * 1 theta1 = theta1 + step * diff * 2104 theta2 = theta2 + step * diff * 3 hserror = diff**2/2 derror = abs(error - hserror) error = hserror #print 'iteration : %d, error : %s, derror : %s' % (i, error, derror) i+=1 print ' theta0 : %f, theta1 : %f, theta2 : %f' % (theta0, theta1, theta2) print ' done : %f' %(theta0 + 2104 * theta1 + 3*theta2) which ends up with answers like this : theta0 : 48.412337, theta1 : 0.094492, theta2 : 50.925579 done : 400.000043 theta0 : 0.574007, theta1 : 0.185363, theta2 : 3.140553 done : 400.000042 theta0 : 28.588457, theta1 : 0.041746, theta2 : 94.525769 done : 400.000043 theta0 : 42.240593, theta1 : 0.096398, theta2 : 51.645989 done : 400.000043 theta0 : 98.452431, theta1 : 0.136432, theta2 : 4.831866 done : 400.000043 theta0 : 18.022160, theta1 : 0.148059, theta2 : 23.487524 done : 400.000043 theta0 : 39.461977, theta1 : 0.097899, theta2 : 51.519412 done : 400.000042 theta0 : 40.979868, theta1 : 0.040312, theta2 : 91.401406 done : 400.000043 theta0 : 15.466259, theta1 : 0.111276, theta2 : 50.136221 done : 400.000043 theta0 : 72.380926, theta1 : 0.013814, theta2 : 99.517853 done : 400.000043 A: First issue is that running this with only one piece of data gives you an underdetermined system... this means it may have an infinite number of solutions. With three variables, you'd expect to have at least 3 data points, preferably much higher. Secondly using gradient descent where the step size is a scaled version of the gradient is not guaranteed to converge except in a small neighbourhood of the solution. You can fix that by switching to either a fixed size step in the direction of the negative gradient (slow) or a linesearch in the direction of the negative gradient ( faster, but slightly more complicated) So for fixed step size instead of theta0 = theta0 - step * dEdtheta0 theta1 = theta1 - step * dEdtheta1 theta2 = theta2 - step * dEdtheta2 You do this n = max( [ dEdtheta1, dEdtheta1, dEdtheta2 ] ) theta0 = theta0 - step * dEdtheta0 / n theta1 = theta1 - step * dEdtheta1 / n theta2 = theta2 - step * dEdtheta2 / n It also looks like you may have a sign error in your steps. I'm also not sure that derror is a good stopping criteria. (But stopping criteria are notoriously hard to get "right") My final point is that gradient descent is horribly slow for parameter fitting. You probably want to use conjugate-gradient or Levenberg-Marquadt methods instead. I suspect that both of these methods already exist for python in the numpy or scipy packages (which aren't part of python by default but are pretty easy to install)
How to create a simple Gradient Descent algorithm
I'm studying simple machine learning algorithms, beginning with a simple gradient descent, but I've got some trouble trying to implement it in python. Here is the example I'm trying to reproduce, I've got data about houses with the (living area (in feet2), and number of bedrooms) with the resulting price : Living area (feet2) : 2104 #bedrooms : 3 Price (1000$s) : 400 I'm trying to do a simple regression using the gradient descent method, but my algorithm won't work... The form of the algorithm is not using vectors on purpose (I'm trying to understand it step by step). i = 1 import sys derror=sys.maxint error = 0 step = 0.0001 dthresh = 0.1 import random theta1 = random.random() theta2 = random.random() theta0 = random.random() while derror>dthresh: diff = 400 - theta0 - 2104 * theta1 - 3 * theta2 theta0 = theta0 + step * diff * 1 theta1 = theta1 + step * diff * 2104 theta2 = theta2 + step * diff * 3 hserror = diff**2/2 derror = abs(error - hserror) error = hserror print 'iteration : %d, error : %s' % (i, error) i+=1 I understand the math, I'm constructing a predicting function with and being the variables (living area, number of bedrooms) and the estimated price. I'm using the cost function ( ) (for one point) : This is a usual problem, but I'm more of a software engineer and I'm learning one step at a time, can you tell me what's wrong ? I got it working with this code : data = {(2104, 3) : 400, (1600,3) : 330, (2400, 3) : 369, (1416, 2) : 232, (3000, 4) : 540} for x in range(10): i = 1 import sys derror=sys.maxint error = 0 step = 0.00000001 dthresh = 0.0000000001 import random theta1 = random.random()*100 theta2 = random.random()*100 theta0 = random.random()*100 while derror>dthresh: diff = 400 - (theta0 + 2104 * theta1 + 3 * theta2) theta0 = theta0 + step * diff * 1 theta1 = theta1 + step * diff * 2104 theta2 = theta2 + step * diff * 3 hserror = diff**2/2 derror = abs(error - hserror) error = hserror #print 'iteration : %d, error : %s, derror : %s' % (i, error, derror) i+=1 print ' theta0 : %f, theta1 : %f, theta2 : %f' % (theta0, theta1, theta2) print ' done : %f' %(theta0 + 2104 * theta1 + 3*theta2) which ends up with answers like this : theta0 : 48.412337, theta1 : 0.094492, theta2 : 50.925579 done : 400.000043 theta0 : 0.574007, theta1 : 0.185363, theta2 : 3.140553 done : 400.000042 theta0 : 28.588457, theta1 : 0.041746, theta2 : 94.525769 done : 400.000043 theta0 : 42.240593, theta1 : 0.096398, theta2 : 51.645989 done : 400.000043 theta0 : 98.452431, theta1 : 0.136432, theta2 : 4.831866 done : 400.000043 theta0 : 18.022160, theta1 : 0.148059, theta2 : 23.487524 done : 400.000043 theta0 : 39.461977, theta1 : 0.097899, theta2 : 51.519412 done : 400.000042 theta0 : 40.979868, theta1 : 0.040312, theta2 : 91.401406 done : 400.000043 theta0 : 15.466259, theta1 : 0.111276, theta2 : 50.136221 done : 400.000043 theta0 : 72.380926, theta1 : 0.013814, theta2 : 99.517853 done : 400.000043
[ "First issue is that running this with only one piece of data gives you an underdetermined system... this means it may have an infinite number of solutions. With three variables, you'd expect to have at least 3 data points, preferably much higher.\nSecondly using gradient descent where the step size is a scaled ver...
[ 8 ]
[]
[]
[ "machine_learning", "python" ]
stackoverflow_0003837692_machine_learning_python.txt
Q: Set producer value for PDFs created by QPrinter I'm currently producing PDFs using python and PyQT. I'd like to change the "Producer" value of the PDF's document information, currently it is set to "Qt 4.6.2 (C) 2010 Nokia Corporation and/or its subsidiary(-ies)". I've looked through the QPrinter reference, and nothing obvious stuck out that I could set. How do I change the document information? A: You could use pdftk to change the metadata of your PDFs: echo "InfoKey: Producer" > producerinfo echo "InfoValue: my program" >> producerinfo pdftk file.pdf update_info producerinfo output newfile.pdf rm producerinfo
Set producer value for PDFs created by QPrinter
I'm currently producing PDFs using python and PyQT. I'd like to change the "Producer" value of the PDF's document information, currently it is set to "Qt 4.6.2 (C) 2010 Nokia Corporation and/or its subsidiary(-ies)". I've looked through the QPrinter reference, and nothing obvious stuck out that I could set. How do I change the document information?
[ "You could use pdftk to change the metadata of your PDFs:\necho \"InfoKey: Producer\" > producerinfo\necho \"InfoValue: my program\" >> producerinfo\npdftk file.pdf update_info producerinfo output newfile.pdf\nrm producerinfo\n\n" ]
[ 2 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0003835921_pyqt_python_qt.txt
Q: how to run python inside netbeans? I installed the plugin for python and it detects the python code, but how do I run it from Netbeans? A: You need to install python first. Then Netbeans will detect the installation and you can run it from there. More info here: http://wiki.netbeans.org/Python
how to run python inside netbeans?
I installed the plugin for python and it detects the python code, but how do I run it from Netbeans?
[ "You need to install python first.\nThen Netbeans will detect the installation and you can run it from there. More info here: http://wiki.netbeans.org/Python\n" ]
[ 1 ]
[]
[]
[ "netbeans", "python" ]
stackoverflow_0003838875_netbeans_python.txt
Q: Python: pytz returning unusable __repr__() I understand that repr()'s purpose is to return a string, that can be used to be evaluated as a python command and return the same object. Unfortunately, pytz does not seem to be very friendly with this function, although it should be quite easy, since pytz instances are created with a single call: import datetime, pytz now = datetime.datetime.now(pytz.timezone('Europe/Berlin')) repr(now) returns: datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>) which cannot be simply copied to another ipython windows and evaluated, because it returns a Syntax Error on the tzinfo attribute. Is there any simple way to let it print: datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=pytz.timezone('Europe/Berlin')) when the 'Europe/Berlin' string is already clearly visible in the original output of repr()? A: import datetime import pytz import pytz.tzinfo def tzinfo_repr(self): return 'pytz.timezone({z})'.format(z=self.zone) pytz.tzinfo.DstTzInfo.__repr__=tzinfo_repr berlin=pytz.timezone('Europe/Berlin') now = datetime.datetime.now(berlin) print(repr(now)) # datetime.datetime(2010, 10, 1, 14, 39, 4, 456039, tzinfo=pytz.timezone("Europe/Berlin")) Note that pytz.timezone("Europe/Berlin") in the summer can mean something different than pytz.timezone("Europe/Berlin")) in the winter, due to daylight savings time. So the monkeypatched __repr__ is not a correct representation of self for all time. But it should work (except for extreme corner cases) during the time it takes to copy and paste into IPython. An alternative approach would be to subclass datetime.tzinfo: class MyTimezone(datetime.tzinfo): def __init__(self,zone): self.timezone=pytz.timezone(zone) def __repr__(self): return 'MyTimezone("{z}")'.format(z=self.timezone.zone) def utcoffset(self, dt): return self.timezone._utcoffset def tzname(self, dt): return self.timezone._tzname def dst(self, dt): return self.timezone._dst berlin=MyTimezone('Europe/Berlin') now = datetime.datetime.now(berlin) print(repr(now)) # datetime.datetime(2010, 10, 1, 19, 2, 58, 702758, tzinfo=MyTimezone("Europe/Berlin"))
Python: pytz returning unusable __repr__()
I understand that repr()'s purpose is to return a string, that can be used to be evaluated as a python command and return the same object. Unfortunately, pytz does not seem to be very friendly with this function, although it should be quite easy, since pytz instances are created with a single call: import datetime, pytz now = datetime.datetime.now(pytz.timezone('Europe/Berlin')) repr(now) returns: datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>) which cannot be simply copied to another ipython windows and evaluated, because it returns a Syntax Error on the tzinfo attribute. Is there any simple way to let it print: datetime.datetime(2010, 10, 1, 13, 2, 17, 659333, tzinfo=pytz.timezone('Europe/Berlin')) when the 'Europe/Berlin' string is already clearly visible in the original output of repr()?
[ "import datetime\nimport pytz\nimport pytz.tzinfo\n\ndef tzinfo_repr(self):\n return 'pytz.timezone({z})'.format(z=self.zone)\npytz.tzinfo.DstTzInfo.__repr__=tzinfo_repr\n\nberlin=pytz.timezone('Europe/Berlin')\nnow = datetime.datetime.now(berlin)\nprint(repr(now))\n# datetime.datetime(2010, 10, 1, 14, 39, 4, 45...
[ 1 ]
[]
[]
[ "instance", "python", "pytz", "representation" ]
stackoverflow_0003838578_instance_python_pytz_representation.txt
Q: Django : load a restricted set of fields of objects loaded using a foreign key I have the following code, using Django ORM routes =Routes.objects.filter(scheduleid=schedule.id).only('externalid') t_list = [(route.externalid, route.vehicle.name) for route in routes]) and it is very slow, because the vehicle objects are huge (dozens of fields, and I cannot change that, it is coming from a legacy database). A lot of time is devoted to create the Vehicle objects, while I only need the name field of this object. Is there a more efficient way to obtain t_list ? I am looking for something like only() for accessing objects through a foreign key. EDIT : the solution is the following : routes=Routes.objects.filter(scheduleid=schedule.id).select_related("vehicle") routes= routes.only('externalid','vehicle__name') Does there exist something similar ? A: You should be able to do this, I think. Warning: not tested Tested using local models. Generated query looked good. routes = Routes.objects.select_related('vehicle').filter(**conditions).only( 'externalid', 'vehicle__name') For this to work there should be a vehicle foreign key field declared in Routes model. This is 'cause select_related() only follows forward relationships. A: You can try following: Routes.objects.filter(scheduleid__id=schedule.id).values('externalid', 'vehicle__name')
Django : load a restricted set of fields of objects loaded using a foreign key
I have the following code, using Django ORM routes =Routes.objects.filter(scheduleid=schedule.id).only('externalid') t_list = [(route.externalid, route.vehicle.name) for route in routes]) and it is very slow, because the vehicle objects are huge (dozens of fields, and I cannot change that, it is coming from a legacy database). A lot of time is devoted to create the Vehicle objects, while I only need the name field of this object. Is there a more efficient way to obtain t_list ? I am looking for something like only() for accessing objects through a foreign key. EDIT : the solution is the following : routes=Routes.objects.filter(scheduleid=schedule.id).select_related("vehicle") routes= routes.only('externalid','vehicle__name') Does there exist something similar ?
[ "You should be able to do this, I think. Warning: not tested Tested using local models. Generated query looked good.\nroutes = Routes.objects.select_related('vehicle').filter(**conditions).only(\n 'externalid', 'vehicle__name')\n\nFor this to work there should be a vehicle foreign key field declared in R...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003838833_django_django_models_python.txt
Q: Parsing Windows Event Logs, is it possible? I am doing a little research into the feasibility of a project I have in mind. It involves doing a little forensic work on images of hard drives, and I have been looking for information on how to analyze saved windows event log files. I do not require the ability to monitor current events, I simply want to be able to view events which have been created, and record the time and application/process which created those events. However I do not have much experience in the inner workings of the windows system specifics, and am wondering if this is possible? The plan is to create images of a hard drive, and then do the analysis on a second machine. Ideally this would be done in either Java or Python, as they are my most proficient languages. The main concerns I have are as follows: Is this information encrypted in anyway? Are there any existing API for parsing this data directly? Is there information available regarding the format in which these logs are stored, and how does it differ from windows versions? This must be possible from analyzing the drive itself, as ideally the installation of windows on the drive would not be running, (as it would be a mounted image on another system) The closest thing I could find in my searches is http://www.j-interop.org/ but that seems to be aimed at remote clients. Ideally nothing would have to be installed on the imaged drive. The other solution which seemed to also pop up is the JNI library, but that also seems to be more so in the area of monitoring a running system. Any help at all is greatly appreciated. :) A: You can use Microsoft's LogParser, a command line tool, to extract data from the event logs into CSV or various other formats. The default mode extracts from the event log on the running system, but according to the documentation you can also tell it to query against a group of EVT files. In your case, you could point it at the EVT files from the system under investigation. A: Saved windows event log files are called backups. You can use JNA to open and read them. Start with this article that describes how to read event logs in Java. EventLogIterator iter = new EventLogIterator("Application"); while(iter.hasNext()) { EventLogRecord record = iter.next(); System.out.println(record.getRecordNumber() + ": Event ID: " + record.getEventId() + ", Event Type: " + record.getType() + ", Event Source: " + record.getSource()); }
Parsing Windows Event Logs, is it possible?
I am doing a little research into the feasibility of a project I have in mind. It involves doing a little forensic work on images of hard drives, and I have been looking for information on how to analyze saved windows event log files. I do not require the ability to monitor current events, I simply want to be able to view events which have been created, and record the time and application/process which created those events. However I do not have much experience in the inner workings of the windows system specifics, and am wondering if this is possible? The plan is to create images of a hard drive, and then do the analysis on a second machine. Ideally this would be done in either Java or Python, as they are my most proficient languages. The main concerns I have are as follows: Is this information encrypted in anyway? Are there any existing API for parsing this data directly? Is there information available regarding the format in which these logs are stored, and how does it differ from windows versions? This must be possible from analyzing the drive itself, as ideally the installation of windows on the drive would not be running, (as it would be a mounted image on another system) The closest thing I could find in my searches is http://www.j-interop.org/ but that seems to be aimed at remote clients. Ideally nothing would have to be installed on the imaged drive. The other solution which seemed to also pop up is the JNI library, but that also seems to be more so in the area of monitoring a running system. Any help at all is greatly appreciated. :)
[ "You can use Microsoft's LogParser, a command line tool, to extract data from the event logs into CSV or various other formats. The default mode extracts from the event log on the running system, but according to the documentation you can also tell it to query against a group of EVT files. In your case, you coul...
[ 3, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002907640_java_python.txt
Q: how to include python modules in linux? I found this xgoogle python modules http://github.com/pkrumins/xgoogle, very interesting. How exactly should i include or install these files in linux?? if i want to do something like this using xgoogle python module? >>from xgoogle.search import GoogleSearch I know that we can use from, import to use modules, but to include an external module, what should i do? Should i need to install module or what? A: You could either do the usual install dance: python setup.py install or simply include the files in a known directory and include that directory in the PYTHONPATH: $ export PYTHONPATH=/contains/modules:$PYTHONPATH Here's a detailed documentation on Installing Python Modules: http://docs.python.org/install/ A: You can install it with other python libraries / modules, or just put it in the same repository than your project.
how to include python modules in linux?
I found this xgoogle python modules http://github.com/pkrumins/xgoogle, very interesting. How exactly should i include or install these files in linux?? if i want to do something like this using xgoogle python module? >>from xgoogle.search import GoogleSearch I know that we can use from, import to use modules, but to include an external module, what should i do? Should i need to install module or what?
[ "You could either do the usual install dance:\npython setup.py install\n\nor simply include the files in a known directory and include that directory in the PYTHONPATH:\n$ export PYTHONPATH=/contains/modules:$PYTHONPATH\n\nHere's a detailed documentation on Installing Python Modules: http://docs.python.org/install/...
[ 5, 0 ]
[]
[]
[ "linux", "module", "python", "xgoogle" ]
stackoverflow_0003839334_linux_module_python_xgoogle.txt
Q: How to check if a QWidget is already showing? I'm developing a plugin UI for an existing application using PyQt4. The window is created using uic.loadUi() on the press of a button in the main window. The problem is that if I press the button again (while the window is showing) the window is re-created and unsaved changes are lost. I don't want to make the window modal. Which options do I have to cope with this problem? I guess it would be related to checking whether the QWidget is already showing. A: You should initializer a pointer to the QWidget (member variable) to 0. When the button is pressed, check if the pointer is 0 - if it is, load and show the widget, and assign the pointer variable to point to the new widget. If the pointer is not null when the button is pressed, call widget->raise() and widget->activateWindow(). Disabled buttons can be frustrating to users, as can buttons which appear to do nothing because e.g. their effect is hidden. A: I would have thought that this would be handled more by your application logic than anything else. The main window should disable the button after it has been clicked and then re-enable it again when the window is closed. Connect up a closing signal on the secondary window to a slot on the main window to notify the main window when the secondary window is being closed.
How to check if a QWidget is already showing?
I'm developing a plugin UI for an existing application using PyQt4. The window is created using uic.loadUi() on the press of a button in the main window. The problem is that if I press the button again (while the window is showing) the window is re-created and unsaved changes are lost. I don't want to make the window modal. Which options do I have to cope with this problem? I guess it would be related to checking whether the QWidget is already showing.
[ "You should initializer a pointer to the QWidget (member variable) to 0.\nWhen the button is pressed, check if the pointer is 0 - if it is, load and show the widget, and assign the pointer variable to point to the new widget. If the pointer is not null when the button is pressed, call widget->raise() and widget->ac...
[ 2, 0 ]
[]
[]
[ "pyqt4", "python", "qt4", "user_interface" ]
stackoverflow_0003839426_pyqt4_python_qt4_user_interface.txt
Q: compress a string in python 3? I don't understand in 2.X it worked : import zlib zlib.compress('Hello, world') now i have a : zlib.compress("Hello world!") TypeError: must be bytes or buffer, not str How can i compress my string ? Regards Bussiere A: This is meant to enforce that you actually have a defined encoding. zlib.compress("Hello, world".encode("utf-8")) b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' zlib.compress("Hello, world".encode("ascii")) b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaI\x01\x00\x1b\xd4\x04i' The same string could describe different byte sequences otherwise. But it is actually a byte sequence that will be encoded by zlib. >>> zlib.compress("Hello, wørld".encode("utf-16")) b'x\x9c\xfb\xff\xcf\x83!\x95!\x07\x08\xf3\x19t\x18\x14\x18\xca\x19~0\x14\x01y)\x0c\x00n\xa6\x06\xef' >>> zlib.compress("Hello, wørld".encode("utf-8")) b"x\x9c\xf3H\xcd\xc9\xc9\xd7Q(?\xbc\xa3('\x05\x00#\x7f\x05u" A: In python 2.x strings are bytes string by default. In python 3.x they are unicode strings. Compressing needs a byte string.
compress a string in python 3?
I don't understand in 2.X it worked : import zlib zlib.compress('Hello, world') now i have a : zlib.compress("Hello world!") TypeError: must be bytes or buffer, not str How can i compress my string ? Regards Bussiere
[ "This is meant to enforce that you actually have a defined encoding.\nzlib.compress(\"Hello, world\".encode(\"utf-8\"))\nb'x\\x9c\\xf3H\\xcd\\xc9\\xc9\\xd7Q(\\xcf/\\xcaI\\x01\\x00\\x1b\\xd4\\x04i'\nzlib.compress(\"Hello, world\".encode(\"ascii\"))\nb'x\\x9c\\xf3H\\xcd\\xc9\\xc9\\xd7Q(\\xcf/\\xcaI\\x01\\x00\\x1b\\xd...
[ 21, 20 ]
[]
[]
[ "compression", "python", "python_3.x", "string", "zlib" ]
stackoverflow_0003839323_compression_python_python_3.x_string_zlib.txt
Q: Tkinter coordinates start at 3? I have the following code: from Tkinter import * master = Tk() canvas = Canvas(master, width=640, height=480, bd=0) canvas.pack() line_coords = (3, 3, 3, 100) canvas.create_line(*line_coords, fill='red') mainloop() This will draw a line in the top-left corner. Why is it that if I change line_coords to (2, 2, 2, 100) the line does not render? It's as if the coordinate system starts at (3, 3). A: Canvas coordinates unequivocally start at zero, and the window frame has nothing to do with your problem. The problem is that the default highlightthickness for a canvas on your system is 3, and that is what is obscuring your line. Try setting the highlightthickness to zero and you'll see your line even if the x coordinate is 0. Unfortunately, both the borderwidth and highlightthickness encroach on the coordinate system of the canvas. A: the coordinate system may start at the top left corner including the operating system's title bar and border, so you have to render to the right and down a bit. It's usually an operating system dependent thing.
Tkinter coordinates start at 3?
I have the following code: from Tkinter import * master = Tk() canvas = Canvas(master, width=640, height=480, bd=0) canvas.pack() line_coords = (3, 3, 3, 100) canvas.create_line(*line_coords, fill='red') mainloop() This will draw a line in the top-left corner. Why is it that if I change line_coords to (2, 2, 2, 100) the line does not render? It's as if the coordinate system starts at (3, 3).
[ "Canvas coordinates unequivocally start at zero, and the window frame has nothing to do with your problem. \nThe problem is that the default highlightthickness for a canvas on your system is 3, and that is what is obscuring your line. Try setting the highlightthickness to zero and you'll see your line even if the x...
[ 3, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003835610_python_tkinter.txt
Q: Python set intersection question I have three sets: s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] # true, 16 and 14 s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] # false I want a function that will return True if every set in the list intersects with at least one other set in the list. Is there a built-in for this or a simple list comprehension? A: all(any(a & b for a in s if a is not b) for b in s) A: Here's a very simple solution that's very efficient for large inputs: def g(s): import collections count = collections.defaultdict(int) for a in s: for x in a: count[x] += 1 return all(any(count[x] > 1 for x in a) for a in s) A: It's a little verbose but I think it's a pretty efficient solution. It takes advantage of the fact that when two sets intersect, we can mark them both as connected. It does this by keeping a list of flags as long as the list of sets. when set i and set j intersect, it sets the flag for both of them. It then loops over the list of sets and only tries to find a intersection for sets that haven't already been intersected. After reading the comments, I think this is what @Victor was talking about. s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] # true, 16 and 14 s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] # false def connected(sets): L = len(sets) if not L: return True if L == 1: return False passed = [False] * L i = 0 while True: while passed[i]: i += 1 if i == L: return True for j, s in enumerate(sets): if j == i: continue if sets[i] & s: passed[i] = passed[j] = True break else: return False print connected(s0) print connected(s1) I decided that an empty list of sets is connected (If you produce an element of the list, I can produce an element that it intersects ;). A list with only one element is dis-connected trivially. It's one line to change in either case if you disagree. A: Here's a more efficient (if much more complicated) solution, that performs a linear number of intersections and a number of unions of order O( n*log(n) ), where n is the length of s: def f(s): import math j = int(math.log(len(s) - 1, 2)) + 1 unions = [set()] * (j + 1) for i, a in enumerate(s): unions[:j] = [set.union(set(), *s[i+2**k:i+2**(k+1)]) for k in range(j)] if not (a & set.union(*unions)): return False j = int(math.log(i ^ (i + 1), 2)) unions[j] = set.union(a, *unions[:j]) return True Note that this solution only works on Python >= 2.6. A: As usual I'd like to give the inevitable itertools solution ;-) from itertools import combinations, groupby from operator import itemgetter def any_intersects( sets ): # we are doing stuff with combinations of sets combined = combinations(sets,2) # group these combinations by their first set grouped = (g for k,g in groupby( combined, key=itemgetter(0))) # are any intersections in each group intersected = (any((a&b) for a,b in group) for group in grouped) return all( intersected ) s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] print any_intersects( s0 ) # True print any_intersects( s1 ) # False This is really lazy and will only do the intersections that are required. It can also be a very confusing and unreadable oneliner ;-) A: To answer your question, no, there isn't a built-in or simple list comprehension that does what you want. Here's another itertools based solution that is very efficient -- surprisingly about twice as fast as @THC4k's itertools answer using groupby() in timing tests using your sample input. It could probably be optimized a bit further, but is very readable as presented. Like @AaronMcSmooth, I arbitrarily decided what to return when there are no or is only one set in the input list. from itertools import combinations def all_intersect(sets): N = len(sets) if not N: return True if N == 1: return False intersected = [False] * N for i,j in combinations(xrange(N), 2): if not intersected[i] or not intersected[j]: if sets[i] & sets[j]: intersected[i] = intersected[j] = True return all(intersected) A: This strategy isn't likely to be as efficient as @Victor's suggestion, but might be more efficient than jchl's answer due to increased use of set arithmetic (union). s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] def freeze(list_of_sets): """Transform a list of sets into a frozenset of frozensets.""" return frozenset(frozenset(set_) for set_ in list_of_sets) def all_sets_have_relatives(set_of_sets): """Check if all sets have another set that they intersect with. >>> all_sets_have_relatives(s0) # true, 16 and 14 True >>> all_sets_have_relatives(s1) # false False """ set_of_sets = freeze(set_of_sets) def has_relative(set_): return set_ & frozenset.union(*(set_of_sets - set((set_,)))) return all(has_relative(set) for set in set_of_sets) A: This may give better performance depending on the distribution of the sets. def all_intersect(s): count = 0 for x, a in enumerate(s): for y, b in enumerate(s): if a & b and x!=y: count += 1 break return count == len(s)
Python set intersection question
I have three sets: s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] # true, 16 and 14 s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] # false I want a function that will return True if every set in the list intersects with at least one other set in the list. Is there a built-in for this or a simple list comprehension?
[ "all(any(a & b for a in s if a is not b) for b in s)\n\n", "Here's a very simple solution that's very efficient for large inputs:\ndef g(s):\n import collections\n count = collections.defaultdict(int)\n for a in s:\n for x in a:\n count[x] += 1\n return all(any(count[x] > 1 for x in ...
[ 14, 5, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0003837426_python_set.txt
Q: Trouble importing BeautifulSoup in python I've unpacked BeautifulSoup into c:\python2.6\lib\site-packages, which is in sys.path, but when I enter import BeautifulSoup I get an import error saying no such module exists. Obviously I'm doing something stupid... what is it? A: You might have more than one python version installed? Check the version you are running. Also, I found using easy_install worked well for installing BeautifulSoup.
Trouble importing BeautifulSoup in python
I've unpacked BeautifulSoup into c:\python2.6\lib\site-packages, which is in sys.path, but when I enter import BeautifulSoup I get an import error saying no such module exists. Obviously I'm doing something stupid... what is it?
[ "You might have more than one python version installed? Check the version you are running.\nAlso, I found using easy_install worked well for installing BeautifulSoup.\n" ]
[ 2 ]
[]
[]
[ "importerror", "module", "python" ]
stackoverflow_0003840177_importerror_module_python.txt
Q: Numpy csv script gives 'ValueError: setting an array element with a sequence' I have a python script that successfully loads a csv file into a 2d numpy array and which then successfully extracts the value of a desired cell based on its column and row header values. For diagnostic purposes, I have the script print the contents of the data matrix before it is put into a numpy array. The script works when the data from the underlying csv file contains values for all rows/columns. The problem is that it throws an error when I run the script on a csv file that apparently has a couple of empty rows/columns at the end of the csv file. I tried to address this by opening up the csv file in Notepad++ and deleting as much as it would let me delete from the end of the file. Notepad++ let me delete one row at the end, but did not indicate that there were any empty columns. Upon deeper examination of the relationship between the python printout and the structure of my underlying data, I see that the python print command is saying that there are two empty columns at the end of the array. In any event, after editing the csv file, I still got the same data printed out when I ran the script, and it still threw the same error, as if I had not deleted the empty line from the end of the csv file. I checked that I had saved the csv file, opened and closed the csv file a couple of times, and closed and re-opened python a couple of times, but the error still persists: Here is my question: How do I modify the script below to avoid this error? Here is the function I was referring to above: def GetHSD_alpha(NumberOfColumnMeans,dfResid): dirname=os.path.dirname(os.getcwd()) resources=os.path.join(dirname,'resources') inputfile=os.path.join(resources,'CriticalValuesOfTukeysHSD_a_0_01.csv') separator=',' ColumnIndex=NumberOfColumnMeans RowIndex=dfResid cast = p.cast data = [[] for dummy in xrange(13)] for line in open(inputfile, 'r'): fields = line.strip().split(separator) for i, number in enumerate(fields): data[i].append(number) print 'data HSD alpha is: ',data time.sleep(2) CriticalValuesArray=p.array(data) HSD_alpha_0_01=CriticalValuesArray[ColumnIndex,RowIndex] return HSD_alpha_0_01 Also, for reference, here is an ABBREVIATED version of the result of printing the data that throws the error. Notice the empty elements at the end, which I cannot seem to manually eliminate from my csv file before running the script: data HSD alpha is: [['', '5', '6', '7'], ['2', '5.7', '5.24', '4.95'], ['3', '6.98', '6.33', '5.92'], ['11', '10.48', '9.3', '8.55'], [], []] Also for reference, here is the ABBREVIATED version of the result of printing data from another csv file that I imported into the script for diagnostic purposes. The data corresponding from the printout below did NOT cause the script to throw an error: data HSD alpha is: [['', '1', '2', '3'], ['1', '4052', '98.49', '34.12'], ['2', '4999', '99.01', '30.81'], ['3', '5403', '99.17', '29.46']] Again, when I open the underlying csv files in Notepad++, there do not seem to be any empty columns or rows, and I have checked those data files carefully. Finally, I imagine that the number of empty rows/columns may vary, so any solution would need to be able to handle variables numbers of empty rows/columns. Thank you in advance. A: found the answer. I needed to change the following line of code: data = [[] for dummy in xrange(11)] xrange needed to be set to 11 and not to 13. simple answer, but it took a lot of digging. this thread is answered/finished now. A: why do you write your own csv loader? numpy.loadtxt? or in your case with missing values: numpy.genfromtxt
Numpy csv script gives 'ValueError: setting an array element with a sequence'
I have a python script that successfully loads a csv file into a 2d numpy array and which then successfully extracts the value of a desired cell based on its column and row header values. For diagnostic purposes, I have the script print the contents of the data matrix before it is put into a numpy array. The script works when the data from the underlying csv file contains values for all rows/columns. The problem is that it throws an error when I run the script on a csv file that apparently has a couple of empty rows/columns at the end of the csv file. I tried to address this by opening up the csv file in Notepad++ and deleting as much as it would let me delete from the end of the file. Notepad++ let me delete one row at the end, but did not indicate that there were any empty columns. Upon deeper examination of the relationship between the python printout and the structure of my underlying data, I see that the python print command is saying that there are two empty columns at the end of the array. In any event, after editing the csv file, I still got the same data printed out when I ran the script, and it still threw the same error, as if I had not deleted the empty line from the end of the csv file. I checked that I had saved the csv file, opened and closed the csv file a couple of times, and closed and re-opened python a couple of times, but the error still persists: Here is my question: How do I modify the script below to avoid this error? Here is the function I was referring to above: def GetHSD_alpha(NumberOfColumnMeans,dfResid): dirname=os.path.dirname(os.getcwd()) resources=os.path.join(dirname,'resources') inputfile=os.path.join(resources,'CriticalValuesOfTukeysHSD_a_0_01.csv') separator=',' ColumnIndex=NumberOfColumnMeans RowIndex=dfResid cast = p.cast data = [[] for dummy in xrange(13)] for line in open(inputfile, 'r'): fields = line.strip().split(separator) for i, number in enumerate(fields): data[i].append(number) print 'data HSD alpha is: ',data time.sleep(2) CriticalValuesArray=p.array(data) HSD_alpha_0_01=CriticalValuesArray[ColumnIndex,RowIndex] return HSD_alpha_0_01 Also, for reference, here is an ABBREVIATED version of the result of printing the data that throws the error. Notice the empty elements at the end, which I cannot seem to manually eliminate from my csv file before running the script: data HSD alpha is: [['', '5', '6', '7'], ['2', '5.7', '5.24', '4.95'], ['3', '6.98', '6.33', '5.92'], ['11', '10.48', '9.3', '8.55'], [], []] Also for reference, here is the ABBREVIATED version of the result of printing data from another csv file that I imported into the script for diagnostic purposes. The data corresponding from the printout below did NOT cause the script to throw an error: data HSD alpha is: [['', '1', '2', '3'], ['1', '4052', '98.49', '34.12'], ['2', '4999', '99.01', '30.81'], ['3', '5403', '99.17', '29.46']] Again, when I open the underlying csv files in Notepad++, there do not seem to be any empty columns or rows, and I have checked those data files carefully. Finally, I imagine that the number of empty rows/columns may vary, so any solution would need to be able to handle variables numbers of empty rows/columns. Thank you in advance.
[ "found the answer.\nI needed to change the following line of code:\ndata = [[] for dummy in xrange(11)]\n\nxrange needed to be set to 11 and not to 13.\nsimple answer, but it took a lot of digging.\nthis thread is answered/finished now.\n", "why do you write your own csv loader?\nnumpy.loadtxt? or in your case wi...
[ 3, 0 ]
[]
[]
[ "arrays", "csv", "numpy", "python" ]
stackoverflow_0003835083_arrays_csv_numpy_python.txt
Q: Running a command on Window minimization in Tkinter I have a Tkinter window whenever the minimize button is pressed I'd like to run a command, how do I do this? I know w.protocol("WM_DELETE_WINDOW", w.command) will run a command on exit. A: You can bind to the <Unmap> event. For example, run the following code and then minimize the main window. The tool window should disappear when the main window is minimized. import Tkinter as tk class App: def __init__(self): self.root = tk.Tk() tk.Label(self.root, text="main window").pack() self.t = tk.Toplevel() tk.Label(self.t, text="tool window").pack() self.root.bind("<Unmap>", self.OnUnmap) self.root.bind("<Map>", self.OnMap) self.root.mainloop() def OnMap(self, event): # show the tool window self.t.wm_deiconify() def OnUnmap(self, event): # withdraw the tool window self.t.wm_withdraw() if __name__ == "__main__": app=App()
Running a command on Window minimization in Tkinter
I have a Tkinter window whenever the minimize button is pressed I'd like to run a command, how do I do this? I know w.protocol("WM_DELETE_WINDOW", w.command) will run a command on exit.
[ "You can bind to the <Unmap> event. \nFor example, run the following code and then minimize the main window. The tool window should disappear when the main window is minimized.\nimport Tkinter as tk\n\nclass App:\n def __init__(self):\n self.root = tk.Tk()\n tk.Label(self.root, text=\"main window\"...
[ 5 ]
[]
[]
[ "python", "tkinter", "windows_7" ]
stackoverflow_0003836489_python_tkinter_windows_7.txt
Q: What's the best way to transfer data with a remote application across the internet? I'm making a relatively simple program which will also be running on a few friends computers and they need to share some information. They will need to exchange ips in case they are changed via dhcp and maybe a few other things in the future, but right now that's it (this will likely be used to update the program if I ever change it too I figure). If there's a better way, without having a middleman server, to keep them from losing the ip that would be helpful too, but worst case I can just call them up and ask since this would so rarely happen, if ever. Our isps renew every 30 days I believe, and they often keep the same one anyways, so I doubt that'll ever be an issue, but if so it's so rare it'd be a minor inconvenience. I haven't done much network programming/scripting before so I'm not sure where to approach this from. I've used urllib/urllib2, and mechanize, but I'm guessing those, while they could work, are not an elegant solution. I was thinking the pcs would just communicate via a specified port and just listen through there, but I don't know what module would handle such a thing. Thanks friends. A: If change of IP address is your main concern, a service like dyndns.com would certainly be helpful. (You can get automatic clients as well, which will update your DNS entry when your IP address changes.) After this for data transfer, you're probably better off using existing protocols (e.g. HTTP, FTP, ...). There's plenty of existing HTTP server libraries out there for example. Perhaps something based on this would be of interest: http://docs.python.org/library/basehttpserver.html
What's the best way to transfer data with a remote application across the internet?
I'm making a relatively simple program which will also be running on a few friends computers and they need to share some information. They will need to exchange ips in case they are changed via dhcp and maybe a few other things in the future, but right now that's it (this will likely be used to update the program if I ever change it too I figure). If there's a better way, without having a middleman server, to keep them from losing the ip that would be helpful too, but worst case I can just call them up and ask since this would so rarely happen, if ever. Our isps renew every 30 days I believe, and they often keep the same one anyways, so I doubt that'll ever be an issue, but if so it's so rare it'd be a minor inconvenience. I haven't done much network programming/scripting before so I'm not sure where to approach this from. I've used urllib/urllib2, and mechanize, but I'm guessing those, while they could work, are not an elegant solution. I was thinking the pcs would just communicate via a specified port and just listen through there, but I don't know what module would handle such a thing. Thanks friends.
[ "If change of IP address is your main concern, a service like dyndns.com would certainly be helpful. (You can get automatic clients as well, which will update your DNS entry when your IP address changes.)\nAfter this for data transfer, you're probably better off using existing protocols (e.g. HTTP, FTP, ...). There...
[ 2 ]
[]
[]
[ "network_programming", "networking", "python" ]
stackoverflow_0003840284_network_programming_networking_python.txt
Q: Cairo context and persistence? I am just getting started using pycairo, and I ran into the following interesting error. The program I write creates a simple gtk window, draws a rectangle on it, and then has a callback to draw a random line on any kind of keyboard input. However, it seems that with each keyboard input, I have to create a new context, or I get an error at the moment the program receives first keyboard input (specifically, on the .stroke() line). Error is as follows, if it matters. 'BadDrawable (invalid Pixmap or Window parameter)'. (Details: serial 230 error_code 9 request_code 53 minor_code 0) #! /usr/bin/env python import pygtk pygtk.require('2.0') import gtk, gobject, cairo, math, random # Create a GTK+ widget on which we will draw using Cairo class Screen(gtk.DrawingArea): # Draw in response to an expose-event __gsignals__ = { "expose-event": "override" } # Handle the expose-event by drawing def do_expose_event(self, event): # Create the cairo context self.cr = self.window.cairo_create() # Restrict Cairo to the exposed area; avoid extra work self.cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) self.cr.clip() self.draw(*self.window.get_size()) def key_press_event(self, *args): # print args self.cr = self.window.cairo_create() # This is the line I have to add # in order to make this function not throw the error. Note that cr is only # given as attribute of self in order to stop it going out of scope when this line # doesn't exist self.cr.set_source_rgb(random.random(), random.random(), random.random()) self.cr.move_to(*[z/2.0 for z in self.window.get_size()]) self.cr.line_to(*[z*random.random() for z in self.window.get_size()]) self.cr.stroke() def draw(self, width, height): # Fill the background with gray self.cr.set_source_rgb(.5,.5,.5) self.cr.rectangle(0, 0, width,height) self.cr.fill() self.cr.set_source_rgb(1,0,0) self.cr.arc(width/2.0, height/2.0, min(width,height)/2.0 - 20.0, 0.0, 2.0*math.pi) self.cr.stroke() #create a gtk window, attach to exit button, and whatever is passed as arg becomes the body of the window. AWESOME def run(Widget): window = gtk.Window() widget = Widget() window.connect("delete-event", gtk.main_quit) window.connect('key-press-event',widget.key_press_event) widget.show() window.add(widget) window.present() gtk.main() if __name__ == "__main__": run(Screen) Thanks for your help! (Update: I was playing around, and I realized the following: when I resize the window, all new objects that were added get deleted (or at least don't appear anymore?) ) A: Cairo drawings don't persist at all. (It's best not to think of them as "objects" -- it's not like a canvas library where you can move them around or transform them after you've drawn them.) You have to do all drawing in the expose handler, or it will, as you have found out, disappear whenever the window is redrawn. The cairo context doesn't persist because of double buffering: see the note in the C documentation, which unfortunately I couldn't find anywhere in the PyGTK documentation. In the above code, you should generate the coordinates and color of your random line in the keypress handler and save them in an array. Then in the expose handler, draw each line in the array in order. A: while you have to create context on every run, you can achieve the persistence you are looking for by disabling the double buffering of the widget. here's an example using hamster graphics library that just does that: https://github.com/projecthamster/experiments/blob/master/many_lines.py A: Many flavors of persistence to discuss: Drawings on some surfaces don't persist: GUI surfaces. You should redraw them in the expose callback. PyCairo objects shouldn't be treated as persistent objects, only as an interface to functions of the Cairo library in C. The contents (paths and fills) of Cairo contexts don't persist beyond a stroke() or fill() operation. A context for a GUI surface doesn't persist between expose events (because of double buffering?) (I don't know whether a context persists for other surfaces i.e. devices.) So you can't use a cairo context to store the attributes of a viewport (a window onto a document i.e. model in user coordinates.) Visual persistence is the tendency of the human eye to see light after it has ceased. Ghosts and flicker are its symptoms in animation or video. Disabling double buffering lets you see things as they are drawn, that is, enabling animation within one expose event ( the simulation of the symptoms of visual persistence.) Disabling double buffering doesn't make a context on a GUI surface persistent between expose events. The persistence of memory is the ur real persistence, or should I say surreal.
Cairo context and persistence?
I am just getting started using pycairo, and I ran into the following interesting error. The program I write creates a simple gtk window, draws a rectangle on it, and then has a callback to draw a random line on any kind of keyboard input. However, it seems that with each keyboard input, I have to create a new context, or I get an error at the moment the program receives first keyboard input (specifically, on the .stroke() line). Error is as follows, if it matters. 'BadDrawable (invalid Pixmap or Window parameter)'. (Details: serial 230 error_code 9 request_code 53 minor_code 0) #! /usr/bin/env python import pygtk pygtk.require('2.0') import gtk, gobject, cairo, math, random # Create a GTK+ widget on which we will draw using Cairo class Screen(gtk.DrawingArea): # Draw in response to an expose-event __gsignals__ = { "expose-event": "override" } # Handle the expose-event by drawing def do_expose_event(self, event): # Create the cairo context self.cr = self.window.cairo_create() # Restrict Cairo to the exposed area; avoid extra work self.cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) self.cr.clip() self.draw(*self.window.get_size()) def key_press_event(self, *args): # print args self.cr = self.window.cairo_create() # This is the line I have to add # in order to make this function not throw the error. Note that cr is only # given as attribute of self in order to stop it going out of scope when this line # doesn't exist self.cr.set_source_rgb(random.random(), random.random(), random.random()) self.cr.move_to(*[z/2.0 for z in self.window.get_size()]) self.cr.line_to(*[z*random.random() for z in self.window.get_size()]) self.cr.stroke() def draw(self, width, height): # Fill the background with gray self.cr.set_source_rgb(.5,.5,.5) self.cr.rectangle(0, 0, width,height) self.cr.fill() self.cr.set_source_rgb(1,0,0) self.cr.arc(width/2.0, height/2.0, min(width,height)/2.0 - 20.0, 0.0, 2.0*math.pi) self.cr.stroke() #create a gtk window, attach to exit button, and whatever is passed as arg becomes the body of the window. AWESOME def run(Widget): window = gtk.Window() widget = Widget() window.connect("delete-event", gtk.main_quit) window.connect('key-press-event',widget.key_press_event) widget.show() window.add(widget) window.present() gtk.main() if __name__ == "__main__": run(Screen) Thanks for your help! (Update: I was playing around, and I realized the following: when I resize the window, all new objects that were added get deleted (or at least don't appear anymore?) )
[ "Cairo drawings don't persist at all. (It's best not to think of them as \"objects\" -- it's not like a canvas library where you can move them around or transform them after you've drawn them.) You have to do all drawing in the expose handler, or it will, as you have found out, disappear whenever the window is redr...
[ 2, 1, 0 ]
[]
[]
[ "cairo", "gtk", "pycairo", "pygtk", "python" ]
stackoverflow_0003513172_cairo_gtk_pycairo_pygtk_python.txt
Q: vlc python bindings - how to receive keyboard input? I'm trying to use VLC's python bindings to create my own little video player. The demo implementation is quite simple and nice, but it requires all the keyboard commands to be typed into the console from which the script was run. Is there any way I can handle keyboard input also when the video player itself has focus? Specifically, I care about controlling the video while in fullscreen mode. Perhaps there's a way to keep the keyboard focus in the console (or maybe another window) while showing the video? I'm using Windows XP, if that has any relevance. A: The best way to control VLC from Python is to talk via the web interface. I tried to get the VLC Python bindings to work and it was more trouble than it's worth, especially for cross-platform stuff. Just use wireshark or something similar to see what the web interface commands look like(they're very simple). I'm using twisted to do the HTTP GETs but you could use the built-in urllib2. A: looks like there's no native way. you could fake it by adding "global" key bindings or by capturing events like "MediaPlayerForward" and just remember "oh that means they probably hit the space bar" (or what not) and respond accordingly. GL! -r A: Ok here is their official answer: http://forum.videolan.org/viewtopic.php?f=32&t=82807
vlc python bindings - how to receive keyboard input?
I'm trying to use VLC's python bindings to create my own little video player. The demo implementation is quite simple and nice, but it requires all the keyboard commands to be typed into the console from which the script was run. Is there any way I can handle keyboard input also when the video player itself has focus? Specifically, I care about controlling the video while in fullscreen mode. Perhaps there's a way to keep the keyboard focus in the console (or maybe another window) while showing the video? I'm using Windows XP, if that has any relevance.
[ "The best way to control VLC from Python is to talk via the web interface. I tried to get the VLC Python bindings to work and it was more trouble than it's worth, especially for cross-platform stuff. Just use wireshark or something similar to see what the web interface commands look like(they're very simple). I'...
[ 1, 1, 0 ]
[]
[]
[ "event_handling", "python", "vlc", "windows" ]
stackoverflow_0002643244_event_handling_python_vlc_windows.txt
Q: Optimize two simple nested loops I have been trying to optimize the two following nested loops: def startbars(query_name, commodity_name): global h_list nc, s, h_list = [], {}, {} query = """ SELECT wbcode, Year, """+query_name+""" FROM innovotable WHERE commodity='"""+commodity_name+"""' and """+query_name+""" != 'NULL' """ rows = cursor.execute(query) for row in rows: n = float(row[2]) s[str(row[0])+str(row[1])] = n nc.append(n) for iso in result: try: for an_year in xrange(1961, 2031, 1): skey = iso+str(an_year) h_list[skey] = 8.0 / max(nc) * s[skey] except: pass Any ideas? Thanks. A: Your code isn't complete which makes it hard to give good advice but: Inner loop doesn't depend on outer-loop, so pull it out of the outer loop. max(nc) is a constant after first loop, so pull it out of the loops. Also you need to know how slow the current code is, and how fast you need it to be, otherwise your optimisations maybe misplaced. Your datastructures are all messed up. Maybe something list this would be faster: def startbars(query_name, commodity_name): assert query_name in INNOVOTABLE_FIELD_NAMES ## TODO: Replace with proper SQL query query = """ SELECT wbcode, Year, """+query_name+""" FROM innovotable WHERE commodity='"""+commodity_name+"""' and """+query_name+""" != 'NULL' """ rows = cursor.execute(query) mapYearToWbcodeToField = {} nc = [] global h_list h_list = {} for row in rows: n = float(row[2]) wbCodeToField = mapYearToWbcodeToField.setdefault(int(row[1]),{}) wbCodeToField[str(row[0])] = n nc.append(n) constant = 8.0 / max(nc) for (an_year,wbCodeToField) in mapYearToWbcodeToField.iteritems(): if an_year < 1961 or an_year > 2031: continue for (wbCode,value) in wbCodeToField.iteritems(): if wbCode not in result: continue skey = wbCode+str(an_year) h_list[skey] = constant * value Or moving all checks into the first loop: def startbars(query_name, commodity_name): assert query_name in INNOVOTABLE_FIELD_NAMES ## TODO: Replace with proper SQL query query = """ SELECT wbcode, Year, """+query_name+""" FROM innovotable WHERE commodity='"""+commodity_name+"""' and """+query_name+""" != 'NULL' """ rows = cursor.execute(query) data = [] maxField = None for row in rows: an_year = int(row[1]) if an_year < 1961 or an_year > 2031: continue wbCode = str(row[0]) if wbCode not in result: continue n = float(row[2]) data.append((wbCode+str(an_year),n)) if maxField is None or n > maxField: maxField = n constant = 8.0 / maxField global h_list h_list = {} for (skey,n) in data: h_list[skey] = constant * n
Optimize two simple nested loops
I have been trying to optimize the two following nested loops: def startbars(query_name, commodity_name): global h_list nc, s, h_list = [], {}, {} query = """ SELECT wbcode, Year, """+query_name+""" FROM innovotable WHERE commodity='"""+commodity_name+"""' and """+query_name+""" != 'NULL' """ rows = cursor.execute(query) for row in rows: n = float(row[2]) s[str(row[0])+str(row[1])] = n nc.append(n) for iso in result: try: for an_year in xrange(1961, 2031, 1): skey = iso+str(an_year) h_list[skey] = 8.0 / max(nc) * s[skey] except: pass Any ideas? Thanks.
[ "Your code isn't complete which makes it hard to give good advice but:\n\nInner loop doesn't depend on outer-loop, so pull it out of the outer loop.\nmax(nc) is a constant after first loop, so pull it out of the loops.\n\nAlso you need to know how slow the current code is, and how fast you need it to be, otherwise ...
[ 5 ]
[]
[]
[ "nested_loops", "optimizer_hints", "python" ]
stackoverflow_0003841051_nested_loops_optimizer_hints_python.txt
Q: Monitor Synchronization: Implementing multiple condition variables I am implementing monitor synchronization. I was wondering how does implementing multiple condition variables works. So a condition variable has method wait() which puts it on the wait queue for a specific lock tied to this condition variable. So if I have multiple condition variables, do each wait call create its own separate wait queue? For eg, if I have: lock = Lock() A = Condition(lock) B = Condition(lock) C = Condition(lock) def foo: with lock: while true: A.wait() def bar: with lock: while true: B.wait() def notifyA with lock: A.notifyAll() So my question is that when we do A.notifyAll(), does it only wake up stuff in the A.wait queue or this there a combined queue for associated with the lock. A: A.notifyAll() should only wake up the thread running foo(). The wait queue your threads are wait()-ing in is part of the condition variable, not the lock. The lock does have its own wait queue, but it's only used by threads trying to acquire the lock. When your thread sleeps in a CV, it doesn't hold the lock, and won't try to reacquire it until another thread calls notify() or similar. That said, you should write your code to assume that B.wait() could in fact wake up at any time. Practically that means re-checking the condition the thread is waiting on: with lock: while not ready: B.wait() # Do stuff with protected data
Monitor Synchronization: Implementing multiple condition variables
I am implementing monitor synchronization. I was wondering how does implementing multiple condition variables works. So a condition variable has method wait() which puts it on the wait queue for a specific lock tied to this condition variable. So if I have multiple condition variables, do each wait call create its own separate wait queue? For eg, if I have: lock = Lock() A = Condition(lock) B = Condition(lock) C = Condition(lock) def foo: with lock: while true: A.wait() def bar: with lock: while true: B.wait() def notifyA with lock: A.notifyAll() So my question is that when we do A.notifyAll(), does it only wake up stuff in the A.wait queue or this there a combined queue for associated with the lock.
[ "A.notifyAll() should only wake up the thread running foo(). The wait queue your threads are wait()-ing in is part of the condition variable, not the lock. The lock does have its own wait queue, but it's only used by threads trying to acquire the lock. When your thread sleeps in a CV, it doesn't hold the lock, a...
[ 2 ]
[]
[]
[ "monitor", "operating_system", "python", "synchronization" ]
stackoverflow_0003826167_monitor_operating_system_python_synchronization.txt
Q: Read the print values of an imported class This is probably very basic, but it's giving me a headache, and I'm not sure what method to even approach it with, making the googling tough. If I have a class in a module that I'm importing with various prints throughout, how can I read the prints as they come so that I may output them to a PyQT text label? class Worker(QtCore.QThread, object): class statusWrapper(object): def __init__(self, outwidget): self.widget = outwidget def write(self, s): self.widget.setText(s) def __init__(self, widget): QtCore.QThread.__init__(self) sys.stdout = statusWrapper(widget) def run(self): self.runModule() #This is the module with the prints within. Something mysterious gets passed to the statusWrapper.write when runModule gets executed, but it's blank. What am I doing wrong? Thanks. A: Instead of writing your own statusWrapper class, you could use a StringIO object as stdout. Something like: def __init__(self, widget): QtCore.QThread.__init__(self) def run(self): real_stdout = sys.stdout sys.stdout = StringIO.StringIO() self.runModule() label_text = sys.stdout.getvalue() sys.stdout = real_stdout Restoring the original value of stdout is important for your sanity. Also note that this will not do what you expect in a multithreaded environment. Also note that delnan is certainly correct, and replacing stdout is an incredibly hackish way of doing this. If you're wanting something which will update the label each time the module prints output (sort of a poor man's status indicator), there are better ways to do that too - you could replace the prints with calls to a callback function, which you set in the module when you import it, or something like that. A: Something mysterious gets passed to the statusWrapper.write when runModule gets executed, but it's blank. What am I doing wrong? It's nothing mysterious: write just receives each string that was written to sys.stdout (that is, your wrapper, in this case). The bug is probably that the wrapper calls setText only, replacing the widget's text on each write, instead of appending to it. You'll need to at least do something like: def write(self, s): self.widget.setText(self.widget.text() + s) (or whatever the more efficient way is of appending text to a QT widget). Note: A much better way to redirect sys.stdout is to use a context manager. PEP 343 defines the following example: from contextlib import contextmanager @contextmanager def stdout_redirected(new_stdout): save_stdout = sys.stdout sys.stdout = new_stdout try: yield None finally: sys.stdout = save_stdout You would use it like: class Worker(QtCore.QThread, object): def run(self): with stdout_redirected(StatusWrapper(widget)): self.runModule() Besides being more readable, this context manager makes sure to restore sys.stdout if runModule raises an exception (which is important for your sanity :-). A: The easiest (still wrong - the right way is changing the function) way is redirecting stdout to the label (print writes to sys.stdout). See Wxwidgets and Pyqt for a trivial example with a QPlainTextEdit, should be easy to adjust for a QLabel.
Read the print values of an imported class
This is probably very basic, but it's giving me a headache, and I'm not sure what method to even approach it with, making the googling tough. If I have a class in a module that I'm importing with various prints throughout, how can I read the prints as they come so that I may output them to a PyQT text label? class Worker(QtCore.QThread, object): class statusWrapper(object): def __init__(self, outwidget): self.widget = outwidget def write(self, s): self.widget.setText(s) def __init__(self, widget): QtCore.QThread.__init__(self) sys.stdout = statusWrapper(widget) def run(self): self.runModule() #This is the module with the prints within. Something mysterious gets passed to the statusWrapper.write when runModule gets executed, but it's blank. What am I doing wrong? Thanks.
[ "Instead of writing your own statusWrapper class, you could use a StringIO object as stdout. Something like: \ndef __init__(self, widget):\n QtCore.QThread.__init__(self)\n\ndef run(self):\n real_stdout = sys.stdout\n sys.stdout = StringIO.StringIO()\n self.runModule()\n label_text = sys.stdout.getva...
[ 1, 1, 0 ]
[]
[]
[ "class", "printing", "pyqt", "python" ]
stackoverflow_0003840050_class_printing_pyqt_python.txt
Q: Getting %def references in mako python is there a way to use %def references somehow, basic idea being: % if condition_a: % func = %def_a % elif condition_b: % func = %def_b ... etc ... ${func( params )} A: Yes like this: % if condition_a: <% func = def_a %> % elif condition_b: <% func = def_b %> % endif ${func( params )} @timmy: I have no idea what you mean, maybe this? <% func = some_dict[key] %> ${func( params )} You can put any Python code inside <% .. %>, see the mako docs!
Getting %def references in mako python
is there a way to use %def references somehow, basic idea being: % if condition_a: % func = %def_a % elif condition_b: % func = %def_b ... etc ... ${func( params )}
[ "Yes like this:\n% if condition_a:\n<% func = def_a %>\n% elif condition_b:\n<% func = def_b %>\n% endif\n\n${func( params )}\n\n@timmy: I have no idea what you mean, maybe this?\n<% func = some_dict[key] %>\n${func( params )}\n\nYou can put any Python code inside <% .. %>, see the mako docs!\n" ]
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003841512_mako_python.txt
Q: Which XML style is better when handling it with Python's ElementTree? I'd like to store some relatively simple stuff in XML in a cascading manner. The idea is that a build can have a number of parameter sets and the Python scripts creates the necessary build artifacts (*.h etc) by reading these sets and if two sets have the same parameter, the latter one replaces the former. There are (at least) two differing ways of doing the XML: First way: <Variants> <Variant name="foo" Info="foobar">1</Variant </Variants> Second way: <Variants> <Variant> <Name>Foo</Name> <Value>1</Value> <Info>foobar</Info> </Variant> </Variants> Which one is better easier to handle in ElementTree. My limited understanding claims it would be the first one as I could search the variant with find() easily and receive the entire subtree but would it be just as easy to do it with the second style? My colleague says that the latter XML is better as it allows expanding the XML more easily (and he is obviously right) but I don't see the expandability a major factor at the moment (might very well be we will never need it). EDIT: I could of course use lxml as well, does it matter in this case? Speed really isn't an issue, the files are relatively small. A: You're both right, but I would pick #1 where possible, except for the text content: 1 is much more succinct and human-readable, thus less error-prone. Complete extensibility: YAGNI. YAGNI is not always true but if you're confident that you won't need extensibility, don't sacrifice other benefits for the sake of extensibility. 1 is still pretty extensible. You can always add more attributes or child elements. The only way it isn't extensible is if you later discover you need multiple values for name, or info (or the text content value)... since you can't have multiple attributes with the same name on an element (nor multiple text content nodes without something in between). However you can still extend those by various techniques, e.g. space-separated values in an attribute, or adding child elements as an alternative to an attribute. I would make the "value" into an attribute or a child element rather than using the text content. If you ever have to add a child element, and you have that text content there, you will end up with mixed content (text as a sibling of an element), which gets messy to process. Update: further reading A few good articles on the XML elements-vs-attributes debate, including when to use each: Principles of XML design: When to use elements versus attributes - well-integrated article by Uche Ogbuji SGML/XML Elements versus Attributes - with many links to other commentary on this old debate Elements or Attributes? See also this SO question (but I think the above give more profitable reading). A: Remember the critical limitations on XML attributes: Attribute names must be XML names. An element can have only one attribute with a given name. The ordering of attributes is not significant. In other words, attributes represent key/value pairs. If you can represent it in Python as a dictionary whose keys are XML names and whose values are strings, you can represent it in XML as a set of attributes, no matter what "it" is. If you can't - if, for instance, ordering is significant, or you need a value to include child elements - then you shouldn't use attributes.
Which XML style is better when handling it with Python's ElementTree?
I'd like to store some relatively simple stuff in XML in a cascading manner. The idea is that a build can have a number of parameter sets and the Python scripts creates the necessary build artifacts (*.h etc) by reading these sets and if two sets have the same parameter, the latter one replaces the former. There are (at least) two differing ways of doing the XML: First way: <Variants> <Variant name="foo" Info="foobar">1</Variant </Variants> Second way: <Variants> <Variant> <Name>Foo</Name> <Value>1</Value> <Info>foobar</Info> </Variant> </Variants> Which one is better easier to handle in ElementTree. My limited understanding claims it would be the first one as I could search the variant with find() easily and receive the entire subtree but would it be just as easy to do it with the second style? My colleague says that the latter XML is better as it allows expanding the XML more easily (and he is obviously right) but I don't see the expandability a major factor at the moment (might very well be we will never need it). EDIT: I could of course use lxml as well, does it matter in this case? Speed really isn't an issue, the files are relatively small.
[ "You're both right, but I would pick #1 where possible, except for the text content:\n\n1 is much more succinct and human-readable, thus less error-prone.\n\nComplete extensibility: YAGNI. YAGNI is not always true but if you're confident that you won't need extensibility, don't sacrifice other benefits for the sake...
[ 3, 1 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003836866_lxml_python_xml.txt
Q: Django Admin app or roll my own? I'm just starting to use Django for a personal project. What are the pros and cons of using the built-in Admin application versus integrating my administrative functions into the app itself (by checking request.user.is_staff)? This is a community wiki because it could be considered a poll. A: It really depends on the project I guess. While you can do everything in the admin, when your app gets more complex using the admin gets more complex too. And if you want to make your app really easy to manage you want control over every little detail, which is not really possible with the admin app. I guess you should see it like this: Using django admin: save time writing it, lose time using it. Rolling your own admin: lose time writing it, save time using it. A: I would use Django's admin app, for a number of reasons. First, writing an administration app may be quite tricky and take some time if you want to do it right, and django.contrib.admin is for free and works out of the box. Second, it is really well designed and very nice to work with (even for non-technical users). Third, it covers a lot of the common cases and it doesn't seem wise to waste time on rewriting it until you are really sure you cannot do otherwise. Fourth, it isn't really so difficult to customize. For example, adding akismet mark-as-spam and mark-as-ham buttons was really a piece of cake. A: It's so easy to selectively override parts of the admin in varying degrees. You can: Override admin templates on an app by app basis or even model by model basis. Override admin views by inheriting and subclassing Catch admin url's by putting yours before it in urls.py and provide your own interfaces that are based on admin look and feel ...and lots more. So start with the admin and then slot in whatever custom functionality you need where you need it. There are a bunch of apps that do clever things with the admin. For example: django-reversion takes over the admin-log and extends it into full history. Tusk CMS combines the django-mptt app with JQuery nested sortable widget in a neat way. Also search django-snippets for admin related snippets and this page has got a wealth of info. A: I found sadly, that the while the django admin app saves a lot of time at first, it becomes a hinderence later on, as your costumer demands more features that are not easily integrated with the default admin interface. You might endup with two kinds of admin tools: the django admin (for apps that require simple data entry), and your custom rolled admin interface for other applications that require a richer interface. A: Consider using the Django admin, but with your own hand-crafted widgets for particular fields. You can create sophisticated form-parts, and tell the admin to use your code for the inputs and displays of any specific field, or all fields of a type. Jannis has done some cool stuff, and his work shows you how easy it is: http://jannisleidel.com/2008/11/wysiwym-editor-widget-django-admin-interface/ A project that I am working on recently incorporated a time picker that uses drop-downs for the various parts of time, (h, m, s) Another field would indicate which days of the week were recurring... it would use 7 checkboxes for the days of the week, and store that in the database as a pickled dateutil.rruleset. Then, you just give the admin hints on which widgets to use for the various fields. It involves defining your data class, your own widget which subclasses forms.Widget, your own Field which subclasses forms.Field, and a model.Field too. Each of the three classes is nice and simple and clean, and is responsible for a transition from the database to the Model, the Model to the Widget, and back through those two steps. It's really a thing of beauty. The fields you create will be some of the most reusable, sophisticated intellectual property that you can accumulate... and you don't have to write your own admin from scratch. A: I'd recommend enabling the admin site on just about every type of project. The cost of setting it up is pretty low, and it gives you a reasonably convenient mechanism for inspecting and modifying your site. If your site has mostly a one way flow of information, from webmaster to visitors, then the admin site is probably all you need. If, however, your site has a richer interaction among its users, you will need to compose django views that can enable that interaction while also limiting access to what users can really do. A: I'd go with the Django admin functionality, over writing your own. You can customize the Django admin by adding your own templates for the admin, your own widgets, etc. I'm working on a project with a very customized Django admin. If we had decided to write it by hand, it would have taken 4 times as long to get done. I just can't see a scenario where you would want to write your own.
Django Admin app or roll my own?
I'm just starting to use Django for a personal project. What are the pros and cons of using the built-in Admin application versus integrating my administrative functions into the app itself (by checking request.user.is_staff)? This is a community wiki because it could be considered a poll.
[ "It really depends on the project I guess. While you can do everything in the admin, when your app gets more complex using the admin gets more complex too. And if you want to make your app really easy to manage you want control over every little detail, which is not really possible with the admin app.\nI guess you ...
[ 17, 17, 7, 3, 3, 1, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0000495879_django_django_admin_python.txt
Q: Extension Crashing Python on Import? I have a python extension that is built and installed through distutils (using mingw on windows). However on import of this module the interpreter crashes. Is there anyway to debug and figure out why it crashes? I did look around online and couldn't find anything specific, or any examples. EDIT Sorry i am trying to compile for python 2.5.4 (we need 2.5.4, since we use arcgis geoprocessor library): http://effbot.org/media/downloads/ftpparse-1.1-20021124.zip On windows, i define crash as: "Python.exe has encountered a problem and needs to close" I'll try debugging with GDB EDIT 2 For what ever reason, doing a setup.py clean For the package and doing: setup.py install fixed all the problems. :psyduck: A: Simply running the following may give you a clue about what call is causing the issue without having to break out a debugger. But if you just get a silent crash you're going to have to put on your detective hat as per Xavier's answer. strace python -v -c "import faultylib" A: I suppose using gdb see http://oldwiki.mingw.org/index.php/gdb
Extension Crashing Python on Import?
I have a python extension that is built and installed through distutils (using mingw on windows). However on import of this module the interpreter crashes. Is there anyway to debug and figure out why it crashes? I did look around online and couldn't find anything specific, or any examples. EDIT Sorry i am trying to compile for python 2.5.4 (we need 2.5.4, since we use arcgis geoprocessor library): http://effbot.org/media/downloads/ftpparse-1.1-20021124.zip On windows, i define crash as: "Python.exe has encountered a problem and needs to close" I'll try debugging with GDB EDIT 2 For what ever reason, doing a setup.py clean For the package and doing: setup.py install fixed all the problems. :psyduck:
[ "Simply running the following may give you a clue about what call is causing the issue without having to break out a debugger. But if you just get a silent crash you're going to have to put on your detective hat as per Xavier's answer.\nstrace python -v -c \"import faultylib\"\n\n", "I suppose using gdb see http:...
[ 3, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0003840770_debugging_python.txt
Q: Python - Most efficient way to find how often each possible pair of words occurs in the same line in a text file? This particular problem is easy to solve, but I'm not so sure that the solution I'd arrive at would be computationally efficient. So I'm asking the experts! What would be the best way to go through a large file, collecting stats (for the entire file) on how often two words occur in the same line? For instance, if the text contained only the following two lines: "This is the white baseball." "These guys have white baseball bats." You would end up collecting the following stats: (this, is: 1), (this, the: 1), (this, white: 1), (this, baseball: 1), (is, the: 1), (is, white: 1), (is, baseball: 1) ... and so forth. For the entry (baseball, white: 2), the value would be 2, since this pair of words occurs in the same line a total of 2 times. Ideally, the stats should be placed in a dictionary, where the keys are alphabetized at the tuple level (i.e., you wouldn't want separate entries for "this, is" and "is, this." We don't care about order here: we just want to find how often each possible pair of words occurs in the same line throughout the text. A: from collections import defaultdict import itertools as it import re pairs = defaultdict(int) for line in lines: for pair in it.combinations(re.findall('\w+', line), 2): pairs[tuple(pair)] += 1 resultList = [pair + (occurences, ) for pair, occurences in pairs.iterkeys()]
Python - Most efficient way to find how often each possible pair of words occurs in the same line in a text file?
This particular problem is easy to solve, but I'm not so sure that the solution I'd arrive at would be computationally efficient. So I'm asking the experts! What would be the best way to go through a large file, collecting stats (for the entire file) on how often two words occur in the same line? For instance, if the text contained only the following two lines: "This is the white baseball." "These guys have white baseball bats." You would end up collecting the following stats: (this, is: 1), (this, the: 1), (this, white: 1), (this, baseball: 1), (is, the: 1), (is, white: 1), (is, baseball: 1) ... and so forth. For the entry (baseball, white: 2), the value would be 2, since this pair of words occurs in the same line a total of 2 times. Ideally, the stats should be placed in a dictionary, where the keys are alphabetized at the tuple level (i.e., you wouldn't want separate entries for "this, is" and "is, this." We don't care about order here: we just want to find how often each possible pair of words occurs in the same line throughout the text.
[ "from collections import defaultdict\nimport itertools as it\nimport re\n\npairs = defaultdict(int)\n\nfor line in lines:\n for pair in it.combinations(re.findall('\\w+', line), 2):\n pairs[tuple(pair)] += 1\n\nresultList = [pair + (occurences, ) for pair, occurences in pairs.iterkeys()]\n\n" ]
[ 4 ]
[]
[]
[ "compare", "dictionary", "line", "python", "statistics" ]
stackoverflow_0003842206_compare_dictionary_line_python_statistics.txt
Q: How do I get a size of an UTF-8 string in Bytes with Python Having an UTF-8 string like this: mystring = "işğüı" is it possible to get its (in memory) size in Bytes with Python (2.5)? A: Assuming you mean the number of UTF-8 bytes (and not the extra bytes that Python requires to store the object), it’s the same as for the length of any other string. A string literal in Python 2.x is a string of encoded bytes, not Unicode characters. Byte strings: >>> mystring = "işğüı" >>> print "length of {0} is {1}".format(repr(mystring), len(mystring)) length of 'i\xc5\x9f\xc4\x9f\xc3\xbc\xc4\xb1' is 9 Unicode strings: >>> myunicode = u"işğüı" >>> print "length of {0} is {1}".format(repr(myunicode), len(myunicode)) length of u'i\u015f\u011f\xfc\u0131' is 5 It’s good practice to maintain all of your strings in Unicode, and only encode when communicating with the outside world. In this case, you could use len(myunicode.encode('utf-8')) to find the size it would be after encoding.
How do I get a size of an UTF-8 string in Bytes with Python
Having an UTF-8 string like this: mystring = "işğüı" is it possible to get its (in memory) size in Bytes with Python (2.5)?
[ "Assuming you mean the number of UTF-8 bytes (and not the extra bytes that Python requires to store the object), it’s the same as for the length of any other string. A string literal in Python 2.x is a string of encoded bytes, not Unicode characters.\nByte strings:\n>>> mystring = \"işğüı\"\n>>> print \"length of {...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0003842487_python.txt
Q: Why does Tkinter frame resize when text box is added to it? With this code, the window is 500 by 500, which is what I'm going for: from tkinter import * root = Tk() frame = Frame(root, width=500, height=500) frame.pack() root.mainloop() When I add a text box to the frame, though, it shrinks to just the size of the text box: from tkinter import * root = Tk() frame = Frame(root, width=500, height=500) text = Text(frame, width=10, height=2) # THESE TWO text.pack() # LINES HERE frame.pack() root.mainloop() Why does this happen, and how can I prevent it from happening? A: The frame by default has "pack propagation" turned on. That means the packer "computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions" (quoting from the official tcl/tk man pages [1]). For the vast majority of cases this is the exact right behavior. For the times that you don't want this you can call pack_propagate on the master and set the value to false. I think in close to 20 years of tk programing I've only needed to do this a half dozen times or so, if that. Another choice you have is to use wm_geometry to set the size of the toplevel after you've created all the widgets. This does effectively the same thing as if the user had manually resized the window. This only works for toplevel windows though, you can't use wm_geometry on a frame.
Why does Tkinter frame resize when text box is added to it?
With this code, the window is 500 by 500, which is what I'm going for: from tkinter import * root = Tk() frame = Frame(root, width=500, height=500) frame.pack() root.mainloop() When I add a text box to the frame, though, it shrinks to just the size of the text box: from tkinter import * root = Tk() frame = Frame(root, width=500, height=500) text = Text(frame, width=10, height=2) # THESE TWO text.pack() # LINES HERE frame.pack() root.mainloop() Why does this happen, and how can I prevent it from happening?
[ "The frame by default has \"pack propagation\" turned on. That means the packer \"computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions\" (quoting from the official tcl/tk man pages [1]).\nFor the vast majority ...
[ 6 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0003842551_python_tkinter_user_interface.txt
Q: Inline SVG Served By Python Script in Google App Engine Not Appearing I'm writing an app that pulls chunks of svg together and serves them as part of a page mixed with css and javascript. I'm using Python and Google App Engine. What I'm doing works fine on my local development server but fails to render once it's deployed. So here's some test python to build a response: self.response.headers.add_header('Content-Type','application/xhtml+xml') self.response.out.write("<html xmlns='http://www.w3.org/1999/xhtml'>") self.response.out.write("<body>") self.response.out.write("<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>") self.response.out.write("<rect x='10' y='10' height='100' width='100' />") self.response.out.write("</svg>") self.response.out.write("</body></html>") Now if I request this on the local development server (I'm using Safari, but Firefox works too) it works and I see a black square. If I create an xhtml document with this markup, and I upload that page to a server, I will see the square, but when I deploy this app on a server and run it, I don't see the square. All the markup is there when I look at View Source, but it wont render. I've tried using different mime types. I've tried adding: <!DOCTYPE html> or adding <?xml version=1.0"?> and none of it makes a difference. Any ideas? A: I solved the problem. This line: self.response.headers.add_header('Content-Type','application/xhtml+xml') was not working. I determined that by using http://web-sniffer.net to see what content-type accompanied the page, and it was always returning the default text/html. The correct syntax is: self.response.headers["Content-Type"] = "application/xhtml+xml" Now everything works just peachy. Not many questions on svg + google-app-engine on SO, but this might be useful for someone else in the future.
Inline SVG Served By Python Script in Google App Engine Not Appearing
I'm writing an app that pulls chunks of svg together and serves them as part of a page mixed with css and javascript. I'm using Python and Google App Engine. What I'm doing works fine on my local development server but fails to render once it's deployed. So here's some test python to build a response: self.response.headers.add_header('Content-Type','application/xhtml+xml') self.response.out.write("<html xmlns='http://www.w3.org/1999/xhtml'>") self.response.out.write("<body>") self.response.out.write("<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>") self.response.out.write("<rect x='10' y='10' height='100' width='100' />") self.response.out.write("</svg>") self.response.out.write("</body></html>") Now if I request this on the local development server (I'm using Safari, but Firefox works too) it works and I see a black square. If I create an xhtml document with this markup, and I upload that page to a server, I will see the square, but when I deploy this app on a server and run it, I don't see the square. All the markup is there when I look at View Source, but it wont render. I've tried using different mime types. I've tried adding: <!DOCTYPE html> or adding <?xml version=1.0"?> and none of it makes a difference. Any ideas?
[ "I solved the problem.\nThis line:\nself.response.headers.add_header('Content-Type','application/xhtml+xml')\n\nwas not working. I determined that by using http://web-sniffer.net to see what content-type accompanied the page, and it was always returning the default text/html.\nThe correct syntax is:\nself.response....
[ 6 ]
[]
[]
[ "google_app_engine", "python", "svg", "xhtml" ]
stackoverflow_0003840166_google_app_engine_python_svg_xhtml.txt
Q: Concatenate sequence from a predefined datastructure I've been struggling a little to build this piece of code, and I was wondering if there are others more simple/efficient way of doing this: fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}} def __buildPathFromSchema(self, schema, root=''): metaDirs = [] for dir_ in schema.keys(): root = os.path.join(root, dir_) if isinstance(schema[dir_], dict): return self.__buildPathFromSchema(schema[dir_], root) if isinstance(schema[dir_], tuple): for i in schema[dir_]: bottom = os.path.join(root, i) metaDirs.append(bottom) root = os.sep.join(os.path.split(root)[:-1]) return metaDirs Basically what I want to do is generating paths from a predefined structure like fsSchema. Note the latest iteration is always a tuple. The ouput looks like: ['published\renders\REN\fold1', 'published\renders\REN\fold2', 'published\renders\SIM\fold1', 'published\renders\SIM\fold2'] Thanks! A: You can use a recursive function to generate all the paths: def flatten(data): if isinstance(data, tuple): for v in data: yield v else: for k in data: for v in flatten(data[k]): yield k + '\\' + v This should be able to handle any kind of nested dictionaries: >>> fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}} >>> list(flatten(fsSchema)) ['published\\renders\\REN\\fold1', 'published\\renders\\REN\\fold2', 'published\\renders\\SIM\\fold1', 'published\\renders\\SIM\\fold2'] Note that the paths are generated in "random" order since dictionaries don't have any internal ordering. A: Instead of: for dir_ in schema.keys(): ... if isinstance(schema[dir_], dict): you can do: for dir_name, dir_content in schema.iteritems(): ... if isinstance(dir_content, tuple): It's both faster and more readable. A: I would keep doing it recursively like you already are but split the walker off from the path generator: def walk(data): if hasattr(data, 'items'): for outer_piece, subdata in data.items(): for inner_piece in walk(subdata): yield (outer_piece, ) + inner_piece else: for piece in data: yield (piece, ) def paths(data): for path in walk(data): yield os.sep.join(path) The reason being that it is really two separate pieces of functionality and having them implemented as separate functions is hence easier to debug, maintain, implement and just generally think about.
Concatenate sequence from a predefined datastructure
I've been struggling a little to build this piece of code, and I was wondering if there are others more simple/efficient way of doing this: fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}} def __buildPathFromSchema(self, schema, root=''): metaDirs = [] for dir_ in schema.keys(): root = os.path.join(root, dir_) if isinstance(schema[dir_], dict): return self.__buildPathFromSchema(schema[dir_], root) if isinstance(schema[dir_], tuple): for i in schema[dir_]: bottom = os.path.join(root, i) metaDirs.append(bottom) root = os.sep.join(os.path.split(root)[:-1]) return metaDirs Basically what I want to do is generating paths from a predefined structure like fsSchema. Note the latest iteration is always a tuple. The ouput looks like: ['published\renders\REN\fold1', 'published\renders\REN\fold2', 'published\renders\SIM\fold1', 'published\renders\SIM\fold2'] Thanks!
[ "You can use a recursive function to generate all the paths:\ndef flatten(data):\n if isinstance(data, tuple):\n for v in data:\n yield v\n else:\n for k in data:\n for v in flatten(data[k]):\n yield k + '\\\\' + v\n\nThis should be able to handle any kind of nested dictiona...
[ 2, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0003842927_python_recursion.txt
Q: Searching a python list quickly? I have a dictionary and a list. The list is made up of values. The dictionary has all of the values plus some more values. I'm trying to count the number of times the values in the list show up in the dictionary per key/values pair. It looks something like this: for k in dict: count = 0 for value in dict[k]: if value in list: count += 1 list.remove(value) dict[k].append(count) I have something like ~1 million entries in the list so searching through each time is ultra slow. Is there some faster way to do what I'm trying to do? Thanks, Rohan A: If you search in a list, then convert this list to a set, it will be much faster: listSet = set(list) for k, values in dict.iteritems(): count = 0 for value in values: if value in listSet: count += 1 listSet.remove(value) dict[k].append(count) list = [elem for elem in list if elem in listSet] # return the original list without removed elements A: You're going to have all manner of trouble with this code, since you're both removing items from your list and using an index into it. Also, you're using list as a variable name, which gets you into interesting trouble as list is also a type. You should be able to get a huge performance improvement (once you fix the other defects in your code) by using a set instead of a list. What you lose by using a set is the ordering of the items and the ability to have an item appear in the list more than once. (Also your items have to be hashable.) What you gain is O(1) lookup time. A: for val in my_list: if val in my_dict: my_dict[val] = my_dict[val] + 1 else: my_dict[val] = 0 What you still need Handle case when val is not in dict A: I changed the last line to append to the dictionary. It's a defaultdict(list). Hopefully that clears up some of the questions. Thanks again.
Searching a python list quickly?
I have a dictionary and a list. The list is made up of values. The dictionary has all of the values plus some more values. I'm trying to count the number of times the values in the list show up in the dictionary per key/values pair. It looks something like this: for k in dict: count = 0 for value in dict[k]: if value in list: count += 1 list.remove(value) dict[k].append(count) I have something like ~1 million entries in the list so searching through each time is ultra slow. Is there some faster way to do what I'm trying to do? Thanks, Rohan
[ "If you search in a list, then convert this list to a set, it will be much faster:\nlistSet = set(list)\n\nfor k, values in dict.iteritems():\n count = 0\n for value in values:\n if value in listSet:\n count += 1\n listSet.remove(value)\n dict[k].append(count)\n\nlist = [elem f...
[ 2, 2, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0003842856_dictionary_list_python.txt
Q: How to write a "joiner" extension for Jinja2? Hi I've been trying to create an extension for jinja2 that would join multiple items with a separator, while skipping items (template fragments) that evaluate to whitespace. There are several of those fragments and you never know in advance which ones will be non-empty and which ones will. Sounds like a trivial task, but I had real hard time making this to work in jinja2. Maybe part of the reason is that jinja does not allow to define custom template nodes. Would you have any suggestions? Below is a snippet that will do the parsing job, but it's missing the evaluation part. class JoinerExtension(Extension): """Template tag that joins non-whitespace (string) items with a specified separator Usage syntax: {% joinitems separator='|' %} .... {% separator %} .... {% separator %} .... {% endjoinitems %} where value of "separator" within the joinitems tag can be an expression, not necessarily a sting """ tags = set(['joinitems']) def parse(self, parser): """parse function for the joinitems template tag """ lineno = next(parser.stream).lineno #1) read separator separator = None while parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value != 'separator': parser.fail('found %r, "separator" expected' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) separator = parser.parse_expression() else: var = parser.stream.current parser.fail('assignment expected after the separator' % var.value, var.lineno, exc=TemplateAssertionError) #2) read the items items = list() end_tags = ['name:separator', 'name:endjoinitems'] while True: item = parser.parse_statements(end_tags) items.append(item) if parser.stream.current.test('name:separator'): next(parser.stream) else: next(parser.stream) break A: Would the built-in joiner class potentially work? Here is a simple example from the documentation. {% set pipe = joiner("|") %} {% if categories %} {{ pipe() }} Categories: {{ categories|join(", ") }} {% endif %} {% if author %} {{ pipe() }} Author: {{ author() }} {% endif %} {% if can_edit %} {{ pipe() }} <a href="?action=edit">Edit</a> {% endif %} You mentioned that it is not known ahead of time which fragments will be empty; perhaps it is possible to store the value of each fragment in a variable before "displaying" it so that you can determine which fragments are indeed empty. For example: {% set pipe = joiner("|") %} {% set fragment = gen_fragment1() %} {% if fragment|trim is not "" %} {{ pipe() }} {{ fragment }} {% endif %} ... You could even encapsulate the above pattern in a macro to reduce repetition: {% set pipe = joiner("|") %} {{ print_if_notblank(pipe, gen_fragment1()) }} {{ print_if_notblank(pipe, gen_fragment2()) }} ... where print_if_notblank is a macro defined as: {% macro print_if_notblank(separator, content) %} {% if content|trim is not "" %} {{ separator() }} {{ content }} {% endif %} {% endmacro %}
How to write a "joiner" extension for Jinja2?
Hi I've been trying to create an extension for jinja2 that would join multiple items with a separator, while skipping items (template fragments) that evaluate to whitespace. There are several of those fragments and you never know in advance which ones will be non-empty and which ones will. Sounds like a trivial task, but I had real hard time making this to work in jinja2. Maybe part of the reason is that jinja does not allow to define custom template nodes. Would you have any suggestions? Below is a snippet that will do the parsing job, but it's missing the evaluation part. class JoinerExtension(Extension): """Template tag that joins non-whitespace (string) items with a specified separator Usage syntax: {% joinitems separator='|' %} .... {% separator %} .... {% separator %} .... {% endjoinitems %} where value of "separator" within the joinitems tag can be an expression, not necessarily a sting """ tags = set(['joinitems']) def parse(self, parser): """parse function for the joinitems template tag """ lineno = next(parser.stream).lineno #1) read separator separator = None while parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value != 'separator': parser.fail('found %r, "separator" expected' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) separator = parser.parse_expression() else: var = parser.stream.current parser.fail('assignment expected after the separator' % var.value, var.lineno, exc=TemplateAssertionError) #2) read the items items = list() end_tags = ['name:separator', 'name:endjoinitems'] while True: item = parser.parse_statements(end_tags) items.append(item) if parser.stream.current.test('name:separator'): next(parser.stream) else: next(parser.stream) break
[ "Would the built-in joiner class potentially work? Here is a simple example from the documentation.\n{% set pipe = joiner(\"|\") %}\n{% if categories %} {{ pipe() }}\n Categories: {{ categories|join(\", \") }}\n{% endif %}\n{% if author %} {{ pipe() }}\n Author: {{ author() }}\n{% endif %}\n{% if can_edit %}...
[ 4 ]
[]
[]
[ "jinja2", "python", "templates" ]
stackoverflow_0003836770_jinja2_python_templates.txt
Q: Does urllib2 in Python 2.6.1 support proxy via https Does urllib2 in Python 2.6.1 support proxy via https? I've found the following at http://www.voidspace.org.uk/python/articles/urllib2.shtml: NOTE Currently urllib2 does not support fetching of https locations through a proxy. This can be a problem. I'm trying automate login in to web site and downloading document, I have valid username/password. proxy_info = { 'host':"axxx", # commented out the real data 'port':"1234" # commented out the real data } proxy_handler = urllib2.ProxyHandler( {"http" : "http://%(host)s:%(port)s" % proxy_info}) opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler(debuglevel=1),urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) fullurl = 'https://correct.url.to.login.page.com/user=a&pswd=b' # example req1 = urllib2.Request(url=fullurl, headers=headers) response = urllib2.urlopen(req1) I've had it working for similar pages but not using HTTPS and I suspect it does not get through proxy - it just gets stuck in the same way as when I did not specify proxy. I need to go out through proxy. I need to authenticate but not using basic authentication, will urllib2 figure out authentication when going via https site (I supply username/password to site via url)? EDIT: Nope, I tested with proxies = { "http" : "http://%(host)s:%(port)s" % proxy_info, "https" : "https://%(host)s:%(port)s" % proxy_info } proxy_handler = urllib2.ProxyHandler(proxies) And I get error: urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in violation of protocol A: Fixed in Python 2.6.3 and several other branches: _bugs.python.org/issue1424152 (replace _ with http...) http://www.python.org/download/releases/2.6.3/NEWS.txt Issue #1424152: Fix for httplib, urllib2 to support SSL while working through proxy. Original patch by Christopher Li, changes made by Senthil Kumaran. A: I'm not sure Michael Foord's article, that you quote, is updated to Python 2.6.1 -- why not give it a try? Instead of telling ProxyHandler that the proxy is only good for http, as you're doing now, register it for https, too (of course you should format it into a variable just once before you call ProxyHandler and just repeatedly use that variable in the dict): that may or may not work, but, you're not even trying, and that's sure not to work!-) A: Incase anyone else have this issue in the future I'd like to point out that it does support https proxying now, make sure the proxy supports it too or you risk running into a bug that puts the python library into an infinite loop (this happened to me). See the unittest in the python source that is testing https proxying support for further information: http://svn.python.org/view/python/branches/release26-maint/Lib/test/test_urllib2.py?r1=74203&r2=74202&pathrev=74203
Does urllib2 in Python 2.6.1 support proxy via https
Does urllib2 in Python 2.6.1 support proxy via https? I've found the following at http://www.voidspace.org.uk/python/articles/urllib2.shtml: NOTE Currently urllib2 does not support fetching of https locations through a proxy. This can be a problem. I'm trying automate login in to web site and downloading document, I have valid username/password. proxy_info = { 'host':"axxx", # commented out the real data 'port':"1234" # commented out the real data } proxy_handler = urllib2.ProxyHandler( {"http" : "http://%(host)s:%(port)s" % proxy_info}) opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler(debuglevel=1),urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) fullurl = 'https://correct.url.to.login.page.com/user=a&pswd=b' # example req1 = urllib2.Request(url=fullurl, headers=headers) response = urllib2.urlopen(req1) I've had it working for similar pages but not using HTTPS and I suspect it does not get through proxy - it just gets stuck in the same way as when I did not specify proxy. I need to go out through proxy. I need to authenticate but not using basic authentication, will urllib2 figure out authentication when going via https site (I supply username/password to site via url)? EDIT: Nope, I tested with proxies = { "http" : "http://%(host)s:%(port)s" % proxy_info, "https" : "https://%(host)s:%(port)s" % proxy_info } proxy_handler = urllib2.ProxyHandler(proxies) And I get error: urllib2.URLError: urlopen error [Errno 8] _ssl.c:480: EOF occurred in violation of protocol
[ "Fixed in Python 2.6.3 and several other branches:\n\n_bugs.python.org/issue1424152 (replace _ with http...)\nhttp://www.python.org/download/releases/2.6.3/NEWS.txt\nIssue #1424152: Fix for httplib, urllib2 to support SSL while working through\nproxy. Original patch by Christopher Li, changes made by Senthil Kumara...
[ 6, 3, 3 ]
[]
[]
[ "https", "proxy", "python", "urllib2" ]
stackoverflow_0001030113_https_proxy_python_urllib2.txt
Q: Mako calling function from string? Is there an easy way to call a function given a string name in mako? A: You should be able to look it up in the dict returned by globals(). Eg.: <$ func_name = 'my_function_name' %> ${globals()[func_name](...)} Although, this does smell rather nasty to me. If you could expand upon your end game perhaps we can figure out something a bit saner.
Mako calling function from string?
Is there an easy way to call a function given a string name in mako?
[ "You should be able to look it up in the dict returned by globals(). Eg.:\n<$ func_name = 'my_function_name' %>\n${globals()[func_name](...)}\n\nAlthough, this does smell rather nasty to me. If you could expand upon your end game perhaps we can figure out something a bit saner.\n" ]
[ 5 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003843095_mako_python.txt
Q: Is there a way to cleanly exit out of a thread which is processing data from a (never-ending) generator? Here's the issue: I have a thread which runs a for-loop reading from a generator, doing some processing on that data, etc.. The generator always has data coming in, so no StopIteration exception is ever raised by it. I would like to stop this thread (cleanly) from the main thread (i.e., exit out of the for-loop which is processing data from the generator). Below is an example of the above scenario, with the correct result, but in the limited sense I'll describe below: import threading import time import random def add(): r = random.Random() i = 0 while True: sleep_time = r.randint(0, 3) time.sleep(sleep_time) yield i i = i + 1 class Test(object): def __init__(self): self.func = add self.stopped = False def stop(self): self.stopped = True def run(self): self.generator = self.func() for x in self.generator: print x if self.stopped is True: break print 'DONE' tester = Test() thread = threading.Thread(target=tester.run) thread.daemon = True thread.start() time.sleep(10) print 'Stopping thread' tester.stop() print 'Complete, but should stop immediately!' Now, while this works in the above example (obviously the above doesn't prevent race conditions on self.stopped, but that's not the problem at hand so I left that code out), the problem I have is that the generator in my real code does not always have data immediately, so there can be a long pause between when self.stopped is set and the break statement is actually executed. So, the gist of my problem is that I would like to be able to cleanly exit out of the for-loop as soon as possible, rather than waiting for data from the generator before being able to exit, and obviously the above solution does not do that. Is there any hope? It's a pretty out-there problem, which likely has no clean solution, but any help would be greatly appreciated. EDIT: To clarify, in my real application I have a generator (let's denote it as G) which grabs data from a kernel driver. This data is to be sent out to a server, but while the socket is attempting to connect to the server (which may not always be running) I want to process the data from the driver (once connected this processing does not occur). So I launched a thread to grab data from G (and process it) while the main thread attempts to connect to the server. Once connected, ideally the following should occur: I pause the execution of G, exit the thread, and pass the same G instance to another function which sends the data straight to the server. From the answers/comments below, I believe this is impossible without destroying G, because there is no way to cleanly pause a currently executing generator. Sorry for the confusion. A: You need the self:generator to have a timeout capability. Conceptually wait(1 sec); rather than just wait(); I don't know if that's possible (show us your generator code). For example if you were reading from a pipe or a socket don't code giveMeSomeBytes( buffer); // wait indefinately code giveMeSomeBytesOrTimeout( buffer, howLongToWait); // wait for a while and // then go see if we should dies A: Sounds like what you really want is a coroutine, not a generator. See David Beazley's mind-bending A Curious Course on Coroutines and Concurrency, which, while being more information than you require and then some, should give you some clarity on what you're trying to do. A: Couldn't you just 'close' the generator ? Doing something like def stop(self): self.generator.close() def run(self): self.generator = self.func() try: for x in self.generator: print x time.sleep(1) except GeneratorExit: pass print 'DONE' A: First, generators are probably a red herring; don't worry about them. The canonical way to solve this kind producer-consumer problem in Python is using the built-in queue module. It acts as an intermediary, allowing your producer thread to keep grabbing/processing data from the kernel into the queue, and your consumer thread to send queue data to the server, without their respective blocking I/O calls interfering with one another. Here's a sketch of the basic idea, without the details filled in: from queue import Queue class Application(object): def __init__(self): self.q = Queue() self.running = False # From kernel to queue def produce(self): while self.running: data = read_from_kernel() self.q.put(data) # From queue to server def consume(self): while self.running: data = self.q.get() send_to_server(data) # Start producer thread, then consume def run(): try: self.running = True producer = Thread(target=self.produce) producer.start() self.consume() finally: self.running = False If self.running is set to False, the above code's produce method will still block inside the read_from_kernel until its next return before exiting itself, but there's little Python can do about that. Whatever system call you use must support this somehow: if it's an actual read, for example, your options would include: A short timeout, plus retry handling Non-blocking I/O (but in this case you might want to investigate a framework based around this, like Twisted Python)
Is there a way to cleanly exit out of a thread which is processing data from a (never-ending) generator?
Here's the issue: I have a thread which runs a for-loop reading from a generator, doing some processing on that data, etc.. The generator always has data coming in, so no StopIteration exception is ever raised by it. I would like to stop this thread (cleanly) from the main thread (i.e., exit out of the for-loop which is processing data from the generator). Below is an example of the above scenario, with the correct result, but in the limited sense I'll describe below: import threading import time import random def add(): r = random.Random() i = 0 while True: sleep_time = r.randint(0, 3) time.sleep(sleep_time) yield i i = i + 1 class Test(object): def __init__(self): self.func = add self.stopped = False def stop(self): self.stopped = True def run(self): self.generator = self.func() for x in self.generator: print x if self.stopped is True: break print 'DONE' tester = Test() thread = threading.Thread(target=tester.run) thread.daemon = True thread.start() time.sleep(10) print 'Stopping thread' tester.stop() print 'Complete, but should stop immediately!' Now, while this works in the above example (obviously the above doesn't prevent race conditions on self.stopped, but that's not the problem at hand so I left that code out), the problem I have is that the generator in my real code does not always have data immediately, so there can be a long pause between when self.stopped is set and the break statement is actually executed. So, the gist of my problem is that I would like to be able to cleanly exit out of the for-loop as soon as possible, rather than waiting for data from the generator before being able to exit, and obviously the above solution does not do that. Is there any hope? It's a pretty out-there problem, which likely has no clean solution, but any help would be greatly appreciated. EDIT: To clarify, in my real application I have a generator (let's denote it as G) which grabs data from a kernel driver. This data is to be sent out to a server, but while the socket is attempting to connect to the server (which may not always be running) I want to process the data from the driver (once connected this processing does not occur). So I launched a thread to grab data from G (and process it) while the main thread attempts to connect to the server. Once connected, ideally the following should occur: I pause the execution of G, exit the thread, and pass the same G instance to another function which sends the data straight to the server. From the answers/comments below, I believe this is impossible without destroying G, because there is no way to cleanly pause a currently executing generator. Sorry for the confusion.
[ "You need the self:generator to have a timeout capability. Conceptually\nwait(1 sec);\n\nrather than just\nwait();\n\nI don't know if that's possible (show us your generator code). For example if you were reading from a pipe or a socket don't code\ngiveMeSomeBytes( buffer); // wait indefinately\n\ncode\ngiveMeSome...
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003842410_python.txt
Q: Python lookup function I want to set up a lookup function with mako. on top of the template, i have <%! lookup = { 'key': function } %> <%def name="function()"> Output </%def> so i can use it later <%def name="body()"> ${lookup['key']()} </%def> this gives me a function is not a defined error. can i get around this? i know why it doesn't work, as it runs first, before the method gets loaded, but how else would i set this up? A: Maybe you could delay the lookup of function from dict-creation time to invocation time? <%! lookup = { 'key': lambda: function() } %> I haven't used Mako, but it works in the Python shell: >>> x = lambda: foo() >>> x <function <lambda> at 0x10047e050> >>> x() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> NameError: global name 'foo' is not defined >>> def foo(): ... print "Test" ... >>> x() Test A: I can tell you why it isn't working, but I do not have a clean solution at this point. Your template as given compiles into this Python code: # -*- encoding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 5 _modified_time = 1285968547.0498569 _template_filename='<snip>' _template_uri='<snip>' _template_cache=cache.Cache(__name__, _modified_time) _source_encoding='utf-8' _exports = ['function'] # SOURCE LINE 1 lookup = { 'key': function } def render_body(context,**pageargs): context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) __M_writer = context.writer() # SOURCE LINE 3 __M_writer(u'\n\n') # SOURCE LINE 7 __M_writer(u'\n') return '' finally: context.caller_stack._pop_frame() def render_function(context): context.caller_stack._push_frame() try: __M_writer = context.writer() # SOURCE LINE 5 __M_writer(u'\n Output\n') return '' finally: context.caller_stack._pop_frame() As you can see your function has actually been defined as render_function. The Mako docs specify how to call defs from outside a template, but they do not indicate how to do this properly at runtime. The code that I have linked too simply does a lookup for "render_%s" % name (see mako.template, line 217), so you might consider just doing that.
Python lookup function
I want to set up a lookup function with mako. on top of the template, i have <%! lookup = { 'key': function } %> <%def name="function()"> Output </%def> so i can use it later <%def name="body()"> ${lookup['key']()} </%def> this gives me a function is not a defined error. can i get around this? i know why it doesn't work, as it runs first, before the method gets loaded, but how else would i set this up?
[ "Maybe you could delay the lookup of function from dict-creation time to invocation time?\n<%!\n lookup = { 'key': lambda: function() }\n%>\n\nI haven't used Mako, but it works in the Python shell:\n>>> x = lambda: foo()\n>>> x\n<function <lambda> at 0x10047e050>\n>>> x()\nTraceback (most recent call last):\n F...
[ 1, 1 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003842458_mako_python.txt
Q: Where is the source code for a Python egg? I'm attempting to add a video extension to the Python Markdown-2.0.3-py2.7.egg Things aren't working, so I want to use pdb debugger to see what's going on. I can't seem to find the source code to insert pdb. The egg is located here: /usr/local/lib/python2.7/site-packages/Markdown-2.0.3-py2.7.egg Using iPython, I can view the Python source code of the Markdown module and it's path: /usr/local/lib/python2.7/site-packages/Markdown-2.0.3-py2.7.egg/markdown/__init__.py But I can't navigate to that file, nor can open it in a Text Editor. I'm guessing the source code I'm viewing may be generated from the compiled egg. However, it seems there must be some way of accessing the code. A: An .egg file is a simple ZIP archive, you can extract the files using any ZIP-enabled application if you want. That being said, you can install an .egg into a folder for development by passing the develop option to setup.py. This will make setuptools use the sources in the specified folder and just link to them by a file in your package path. A: A .egg file is a zipfile -- so, typing at a command prompt or shell prompt unzip -l /usr/local/lib/python2.7/site-packages/Markdown-2.0.3-py2.7.egg should tell you about its contents, for example (if you have unzip on your shell or command's $PATH, of course). A: You could reinstall the egg as a directory. Look in the comments of this answer
Where is the source code for a Python egg?
I'm attempting to add a video extension to the Python Markdown-2.0.3-py2.7.egg Things aren't working, so I want to use pdb debugger to see what's going on. I can't seem to find the source code to insert pdb. The egg is located here: /usr/local/lib/python2.7/site-packages/Markdown-2.0.3-py2.7.egg Using iPython, I can view the Python source code of the Markdown module and it's path: /usr/local/lib/python2.7/site-packages/Markdown-2.0.3-py2.7.egg/markdown/__init__.py But I can't navigate to that file, nor can open it in a Text Editor. I'm guessing the source code I'm viewing may be generated from the compiled egg. However, it seems there must be some way of accessing the code.
[ "An .egg file is a simple ZIP archive, you can extract the files using any ZIP-enabled application if you want. That being said, you can install an .egg into a folder for development by passing the develop option to setup.py. This will make setuptools use the sources in the specified folder and just link to them by...
[ 9, 5, 1 ]
[]
[]
[ "django", "egg", "markdown", "python", "setuptools" ]
stackoverflow_0003843097_django_egg_markdown_python_setuptools.txt
Q: py-appscript & events Is it possible to subscribe to events using py-appscript ? Example: I'd like to get a callback when a user changes a rating on iTunes. A: Some very few applications are recordable: that is, they'll send Apple Events to themselves which can be intercepted. iTunes is not one of these applications. iTunes does send distributed notifications for music start/stop, but not for rating changes. Assuming you don't want to patch iTunes itself, your only real choice is to parse iTunes Music Library.xml.
py-appscript & events
Is it possible to subscribe to events using py-appscript ? Example: I'd like to get a callback when a user changes a rating on iTunes.
[ "Some very few applications are recordable: that is, they'll send Apple Events to themselves which can be intercepted. iTunes is not one of these applications. iTunes does send distributed notifications for music start/stop, but not for rating changes. Assuming you don't want to patch iTunes itself, your only rea...
[ 1 ]
[]
[]
[ "itunes", "macos", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0003842882_itunes_macos_py_appscript_python_sourceforge_appscript.txt
Q: Does this function have to use reduce() or is there a more pythonic way? If I have a value, and a list of additional terms I want multiplied to the value: n = 10 terms = [1,2,3,4] Is it possible to use a list comprehension to do something like this: n *= (term for term in terms) #not working... Or is the only way: n *= reduce(lambda x,y: x*y, terms) This is on Python 2.6.2. Thanks! A: reduce is the best way to do this IMO, but you don't have to use a lambda; instead, you can use the * operator directly: import operator n *= reduce(operator.mul, terms) n is now 240. See the docs for the operator module for more info. A: Reduce is not the only way. You can also write it as a simple loop: for term in terms: n *= term I think this is much more clear than using reduce, especially when you consider that many Python programmers have never seen reduce and the name does little to convey to people who see it for the first time what it actually does. Pythonic does not mean write everything as comprehensions or always use a functional style if possible. Python is a multi-paradigm language and writing simple imperative code when appropriate is Pythonic. Guido van Rossum also doesn't want reduce in Python: So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly. There aren't a whole lot of associative operators. (Those are operators X for which (a X b) X c equals a X (b X c).) I think it's just about limited to +, *, &, |, ^, and shortcut and/or. We already have sum(); I'd happily trade reduce() for product(), so that takes care of the two most common uses. [...] In Python 3 reduce has been moved to the functools module. A: Yet another way: import operator n = reduce(operator.mul, terms, n)
Does this function have to use reduce() or is there a more pythonic way?
If I have a value, and a list of additional terms I want multiplied to the value: n = 10 terms = [1,2,3,4] Is it possible to use a list comprehension to do something like this: n *= (term for term in terms) #not working... Or is the only way: n *= reduce(lambda x,y: x*y, terms) This is on Python 2.6.2. Thanks!
[ "reduce is the best way to do this IMO, but you don't have to use a lambda; instead, you can use the * operator directly:\nimport operator\nn *= reduce(operator.mul, terms)\n\nn is now 240. See the docs for the operator module for more info.\n", "Reduce is not the only way. You can also write it as a simple loop:...
[ 8, 7, 2 ]
[]
[]
[ "list_comprehension", "python", "reduce" ]
stackoverflow_0003843188_list_comprehension_python_reduce.txt
Q: Python: callback when accessing the value of a variable? Suppose a function f() returns a value of arbitrary type, perhaps an object but possibly even a builtin type like int or list. Is there a way to assign a variable to that return value, and have a function of my choosing be called the first time the variable is used? I suppose this is similar to lazy evaluation except that a reference to x exists and can be used by subsequent code. It might look like this: x = f() # f is a function, assign variable to return value, but return value is unknown # do something arbitrary with x return str(x) # this calls a callback attached to x, which returns the value of x to be used Again, I want to do this on any type, not just an object instance. A: Sounds like you want properties. class DeepThought(object): @property def answer(self): print ("Computing the Ultimate Answer to the Ultimate Question" " of Life, The Universe, and Everything ") return 42 print DeepThought().answer You can do that only in classes. A: If you want to write a C extension for it, you could wrap the value in something that behaves the way that Python's weakref.ProxyType does, only with laziness instead of "weak"ness. You can always take a look at the Python source code to see how that's done but something tells me it's nontrivial. The implementation of the weakref proxy type in Python is here. A: Given your constraints, the only viable solution is to fork Python and modify its internal handling of variable lookups. You may also need to modify the bytecode definition. Be prepared for a performance hit. Or write a PEP and be very, very patient. Your choice. A: There are several implementations of poor-man's lazy evaluation in Python, such as lazypy. True lazy evaluation is not available in CPython, of course, but is available in PyPy, using the thunk object space. A: In that particular case, you can overload the __str__ method on the return type of f(). for example. def f(): class _f: def __str__(self): return "something" return _f()
Python: callback when accessing the value of a variable?
Suppose a function f() returns a value of arbitrary type, perhaps an object but possibly even a builtin type like int or list. Is there a way to assign a variable to that return value, and have a function of my choosing be called the first time the variable is used? I suppose this is similar to lazy evaluation except that a reference to x exists and can be used by subsequent code. It might look like this: x = f() # f is a function, assign variable to return value, but return value is unknown # do something arbitrary with x return str(x) # this calls a callback attached to x, which returns the value of x to be used Again, I want to do this on any type, not just an object instance.
[ "Sounds like you want properties.\nclass DeepThought(object):\n\n @property\n def answer(self):\n print (\"Computing the Ultimate Answer to the Ultimate Question\"\n \" of Life, The Universe, and Everything \")\n return 42\n\nprint DeepThought().answer\n\nYou can do that only i...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003842338_python.txt
Q: SWIG passing argument to python callback function So I'm almost done. Now I have working code which calls python callback function. Only thing I need now is how to pass argument to the python callback function. My callback.c is: #include <stdio.h> typedef void (*CALLBACK)(void); CALLBACK my_callback = 0; void set_callback(CALLBACK c); void test(void); void set_callback(CALLBACK c) { my_callback = c; } void test(void) { printf("Testing the callback function\n"); if (my_callback) (*my_callback)(); else printf("No callback registered\n"); } My callback.i is: // An entirely different mechanism for handling a callback %module callback %{ typedef void (*CALLBACK)(void); extern CALLBACK my_callback; extern void set_callback(CALLBACK c); extern void my_set_callback(PyObject *PyFunc); extern void test(void); %} extern CALLBACK my_callback; extern void set_callback(CALLBACK c); extern void my_set_callback(PyObject *PyFunc); extern void test(void); %{ static PyObject *my_pycallback = NULL; static void PythonCallBack(void) { PyObject *func, *arglist; PyObject *result; func = my_pycallback; /* This is the function .... */ arglist = Py_BuildValue("()"); /* No arguments needed */ result = PyEval_CallObject(func, arglist); Py_DECREF(arglist); Py_XDECREF(result); return /*void*/; } void my_set_callback(PyObject *PyFunc) { Py_XDECREF(my_pycallback); /* Dispose of previous callback */ Py_XINCREF(PyFunc); /* Add a reference to new callback */ my_pycallback = PyFunc; /* Remember new callback */ set_callback(PythonCallBack); } %} %typemap(python, in) PyObject *PyFunc { if (!PyCallable_Check($input)) { PyErr_SetString(PyExc_TypeError, "Need a callable object!"); return NULL; } $1 = $input; } It works well. What should I do so I can pass argument to my_callback? Any help will be greatly appreciated! A: The arguments to the callback are the second argument to PyEval_CallObject(). Right now you're building an empty tuple, which means "no arguments". So, change that. Where you now do: arglist = Py_BuildValue("()"); /* No arguments needed */ you instead pass Py_BuildValue whatever arguments you want the Python function to receive. For example, if you want to pass the callback an integer, a string and a Python object you got from somewhere, you would do: arglist = Py_BuildValue("(isO)", the_int, the_str, the_pyobject);
SWIG passing argument to python callback function
So I'm almost done. Now I have working code which calls python callback function. Only thing I need now is how to pass argument to the python callback function. My callback.c is: #include <stdio.h> typedef void (*CALLBACK)(void); CALLBACK my_callback = 0; void set_callback(CALLBACK c); void test(void); void set_callback(CALLBACK c) { my_callback = c; } void test(void) { printf("Testing the callback function\n"); if (my_callback) (*my_callback)(); else printf("No callback registered\n"); } My callback.i is: // An entirely different mechanism for handling a callback %module callback %{ typedef void (*CALLBACK)(void); extern CALLBACK my_callback; extern void set_callback(CALLBACK c); extern void my_set_callback(PyObject *PyFunc); extern void test(void); %} extern CALLBACK my_callback; extern void set_callback(CALLBACK c); extern void my_set_callback(PyObject *PyFunc); extern void test(void); %{ static PyObject *my_pycallback = NULL; static void PythonCallBack(void) { PyObject *func, *arglist; PyObject *result; func = my_pycallback; /* This is the function .... */ arglist = Py_BuildValue("()"); /* No arguments needed */ result = PyEval_CallObject(func, arglist); Py_DECREF(arglist); Py_XDECREF(result); return /*void*/; } void my_set_callback(PyObject *PyFunc) { Py_XDECREF(my_pycallback); /* Dispose of previous callback */ Py_XINCREF(PyFunc); /* Add a reference to new callback */ my_pycallback = PyFunc; /* Remember new callback */ set_callback(PythonCallBack); } %} %typemap(python, in) PyObject *PyFunc { if (!PyCallable_Check($input)) { PyErr_SetString(PyExc_TypeError, "Need a callable object!"); return NULL; } $1 = $input; } It works well. What should I do so I can pass argument to my_callback? Any help will be greatly appreciated!
[ "The arguments to the callback are the second argument to PyEval_CallObject(). Right now you're building an empty tuple, which means \"no arguments\". So, change that. Where you now do:\narglist = Py_BuildValue(\"()\"); /* No arguments needed */\n\nyou instead pass Py_BuildValue whatever arguments you want the Pyt...
[ 3 ]
[]
[]
[ "callback", "python", "swig" ]
stackoverflow_0003843064_callback_python_swig.txt
Q: Starting a web app now which will use python that later this need to embed nicely into a Drupal site? This week, I want to start a web mapping and data visualization site for my work. Unfortunately, I just found out my work place will be using Drupal in a few months down the road. (Most of my web development experience is with App Engine.) My problem is that I need to make sure my web application embeds nicely into the larger Drupal site that outside consultants plan to make. I am most comfy with Python, and I was expecting to use the Python-Django combo instead. There are important python libraries and modules I must have that cant be found or re-written in PHP. I was thinking I will avoid all django on the web pages so things dont get confusing when the Drupal switch is made. I will have the javascript on the web page make calls to python on the server which then spits out JSON data, and I think this will stay the same even after the Drupal switch. Does this make sense? Any general or specific suggestions that may guide me are greatly appreciated! A: If you write API calls and utilize Drupal Services module, you can hook into just about anything and send/receive JSON/XML data.
Starting a web app now which will use python that later this need to embed nicely into a Drupal site?
This week, I want to start a web mapping and data visualization site for my work. Unfortunately, I just found out my work place will be using Drupal in a few months down the road. (Most of my web development experience is with App Engine.) My problem is that I need to make sure my web application embeds nicely into the larger Drupal site that outside consultants plan to make. I am most comfy with Python, and I was expecting to use the Python-Django combo instead. There are important python libraries and modules I must have that cant be found or re-written in PHP. I was thinking I will avoid all django on the web pages so things dont get confusing when the Drupal switch is made. I will have the javascript on the web page make calls to python on the server which then spits out JSON data, and I think this will stay the same even after the Drupal switch. Does this make sense? Any general or specific suggestions that may guide me are greatly appreciated!
[ "If you write API calls and utilize Drupal Services module, you can hook into just about anything and send/receive JSON/XML data.\n" ]
[ 1 ]
[]
[]
[ "drupal", "python" ]
stackoverflow_0003843218_drupal_python.txt
Q: Why doesn't Python's `except` use `isinstance`? The Python documentation for except says: For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, [...] Why doesn't except use isinstance instead of comparing base classes? This is preventing the use of __instancecheck__ to override the instance check. EDIT: I can understand that one of the reasons this doesn't exist is that no one considered it. But are there any reasons why this should not be implemented? EDIT: Shell session from Python 3.2a showing that trying to use __subclasscheck__ for this doesn't work: >>> class MyType(type): __subclasscheck__ = lambda cls, other_cls: True >>> class O(Exception, metaclass=MyType): pass >>> issubclass(3, O) 0: True >>> issubclass(int, O) 1: True >>> try: ... 1/0 ... except O: ... print('Success') Traceback (most recent call last): File "<pyshell#4>", line 2, in <module> 1/0 ZeroDivisionError: division by zero >>> A: The simple answer is probably that nobody considered it. A more complex answer would be that nobody considered it because it's hard to get this right, because it would mean executing potentially arbitrary Python code while handling an exception, and that it is of dubious value. Exception classes in Python are typically very simple classes, and overloading them with functionality is often a mistake. It's hard to imagine a case for having it consult __instancecheck__. If you have such a case (with or without a patch), file a bug and someone might pick it up. A: But are there any reasons why this should not be implemented? Can you give an example where this would be useful? When you do this: class SomeMeta(type): def __subclasscheck__(cls, sub): print (cls, sub) return True class Something(Exception): pass class SomeType(Exception): __metaclass__ = SomeMeta try: raise Something() except SomeType, e: pass # prints (<class '__main__.SomeType'>, <class '__main__.Something'>) Python calls __subclasscheck__ on SomeType's metaclass to determine if Something a subclass of SomeType. The Metaclass PEP talks about this in more detail.
Why doesn't Python's `except` use `isinstance`?
The Python documentation for except says: For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, [...] Why doesn't except use isinstance instead of comparing base classes? This is preventing the use of __instancecheck__ to override the instance check. EDIT: I can understand that one of the reasons this doesn't exist is that no one considered it. But are there any reasons why this should not be implemented? EDIT: Shell session from Python 3.2a showing that trying to use __subclasscheck__ for this doesn't work: >>> class MyType(type): __subclasscheck__ = lambda cls, other_cls: True >>> class O(Exception, metaclass=MyType): pass >>> issubclass(3, O) 0: True >>> issubclass(int, O) 1: True >>> try: ... 1/0 ... except O: ... print('Success') Traceback (most recent call last): File "<pyshell#4>", line 2, in <module> 1/0 ZeroDivisionError: division by zero >>>
[ "The simple answer is probably that nobody considered it. A more complex answer would be that nobody considered it because it's hard to get this right, because it would mean executing potentially arbitrary Python code while handling an exception, and that it is of dubious value. Exception classes in Python are typi...
[ 4, 1 ]
[]
[]
[ "exception", "exception_handling", "isinstance", "python", "types" ]
stackoverflow_0003843469_exception_exception_handling_isinstance_python_types.txt
Q: Why is the notebook control not showing up in my window? Although I am not new to Python, this is my first attempt at using Glade to design the interface. My Python file looks like this: import gobject import gtk import gtk.glade class prefs_dialog: def __init__ (self): # Initialize the dialog self.window = gtk.glade.XML("file.glade").get_widget("prefs_dialog") self.window.show() pd = prefs_dialog() gtk.main() And the "file.glade" file looks like this: <?xml version="1.0"?> <glade-interface> <!-- interface-requires gtk+ 2.16 --> <!-- interface-naming-policy project-wide --> <widget class="GtkDialog" id="prefs_dialog"> <property name="border_width">5</property> <property name="type_hint">normal</property> <property name="has_separator">False</property> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox"> <property name="visible">True</property> <property name="spacing">2</property> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <placeholder/> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </widget> <packing> <property name="tab_fill">False</property> <property name="type">tab</property> </packing> </child> <child> <placeholder/> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </widget> <packing> <property name="position">1</property> <property name="tab_fill">False</property> <property name="type">tab</property> </packing> </child> <child> <placeholder/> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </widget> <packing> <property name="position">2</property> <property name="tab_fill">False</property> <property name="type">tab</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <placeholder/> </child> <child> <placeholder/> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </widget> </child> </widget> </glade-interface> When I run the application, I get a really tiny window and the message: python prefs_dialog.py prefs_dialog.py:11: GtkWarning: gtk_notebook_set_tab_label: assertion `GTK_IS_WI DGET (child)' failed self.window = gtk.glade.XML("file.glade").get_widget("prefs_dialog") Also, the control does not show. A: Okay, so it seems like the problem is that the notebook control had no widgets in the tabs. Adding something caused the control to finally show up.
Why is the notebook control not showing up in my window?
Although I am not new to Python, this is my first attempt at using Glade to design the interface. My Python file looks like this: import gobject import gtk import gtk.glade class prefs_dialog: def __init__ (self): # Initialize the dialog self.window = gtk.glade.XML("file.glade").get_widget("prefs_dialog") self.window.show() pd = prefs_dialog() gtk.main() And the "file.glade" file looks like this: <?xml version="1.0"?> <glade-interface> <!-- interface-requires gtk+ 2.16 --> <!-- interface-naming-policy project-wide --> <widget class="GtkDialog" id="prefs_dialog"> <property name="border_width">5</property> <property name="type_hint">normal</property> <property name="has_separator">False</property> <child internal-child="vbox"> <widget class="GtkVBox" id="dialog-vbox"> <property name="visible">True</property> <property name="spacing">2</property> <child> <widget class="GtkNotebook" id="notebook1"> <property name="visible">True</property> <property name="can_focus">True</property> <child> <placeholder/> </child> <child> <widget class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="label" translatable="yes">page 1</property> </widget> <packing> <property name="tab_fill">False</property> <property name="type">tab</property> </packing> </child> <child> <placeholder/> </child> <child> <widget class="GtkLabel" id="label2"> <property name="visible">True</property> <property name="label" translatable="yes">page 2</property> </widget> <packing> <property name="position">1</property> <property name="tab_fill">False</property> <property name="type">tab</property> </packing> </child> <child> <placeholder/> </child> <child> <widget class="GtkLabel" id="label3"> <property name="visible">True</property> <property name="label" translatable="yes">page 3</property> </widget> <packing> <property name="position">2</property> <property name="tab_fill">False</property> <property name="type">tab</property> </packing> </child> </widget> <packing> <property name="position">1</property> </packing> </child> <child internal-child="action_area"> <widget class="GtkHButtonBox" id="dialog-action_area"> <property name="visible">True</property> <property name="layout_style">end</property> <child> <placeholder/> </child> <child> <placeholder/> </child> </widget> <packing> <property name="expand">False</property> <property name="pack_type">end</property> <property name="position">0</property> </packing> </child> </widget> </child> </widget> </glade-interface> When I run the application, I get a really tiny window and the message: python prefs_dialog.py prefs_dialog.py:11: GtkWarning: gtk_notebook_set_tab_label: assertion `GTK_IS_WI DGET (child)' failed self.window = gtk.glade.XML("file.glade").get_widget("prefs_dialog") Also, the control does not show.
[ "Okay, so it seems like the problem is that the notebook control had no widgets in the tabs. Adding something caused the control to finally show up.\n" ]
[ 2 ]
[]
[]
[ "glade", "pygtk", "python" ]
stackoverflow_0003843311_glade_pygtk_python.txt
Q: search list for exact match How can I search list(s) where all the elements exactly match what I'm looking for. For instance, I want to verify if the following list consist of 'a', 'b' and 'c', and nothing more or less. lst=['a', 'b', 'c'] I did this: if 'a' in lst and 'b' in lst and 'c' in lst: #do something Many thanks in advance. A: You can sort the lists and then simply compare them: sorted( list_one ) == sorted( list_two ). Also you can convert both lists to sets and compare them. But be careful, sets eat duplicate items! set( list_one ) == set( list_two ). Sets can also tell you which items either set is lacking: set(list_one) ^ set(list_two). Some examples: >>> sorted("asd") == sorted("dsa") True >>> sorted( "asd" ) == sorted( "dsa" ) True >>> sorted( "asd" ) == sorted( "dsaf" ) False >>> set( "asd" ) == set( "dasf" ) False >>> set( "asd" ) == set( "daas" ) True >>> set( "asd" ) ^ set( "daf" ) set(['s', 'f']) A: This does actually work. Why do you think it doesn't? Also, are you aware of Python sets? http://docs.python.org/library/sets.html A: Using sets is fine for what has been asked: In the first case, the lists are identical, having all the elements, nothing less or more While in the second case it is not and it shows up. You can use this for this purpose. >>> lst=['a', 'b', 'c'] >>> listtocheck = ['a', 'b', 'c'] >>> s1 = set(lst) >>> s2 = set(listtocheck) >>> k = s1 ^ s2 >>> k set([]) >>> listtocheck = ['a', 'b', 'c', 'd'] >>> s2 = set(listtocheck) >>> k = s1 ^ s2 >>> k set(['d']) >>>
search list for exact match
How can I search list(s) where all the elements exactly match what I'm looking for. For instance, I want to verify if the following list consist of 'a', 'b' and 'c', and nothing more or less. lst=['a', 'b', 'c'] I did this: if 'a' in lst and 'b' in lst and 'c' in lst: #do something Many thanks in advance.
[ "You can sort the lists and then simply compare them: sorted( list_one ) == sorted( list_two ).\nAlso you can convert both lists to sets and compare them. But be careful, sets eat duplicate items! set( list_one ) == set( list_two ). \nSets can also tell you which items either set is lacking: set(list_one) ^ set(lis...
[ 6, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003843571_python.txt
Q: Broken Pipe when calling subprocess.Popen() within a multiprocessing.Process() I am having an issue when making a shell call from within a multiprocessing.Process(). The error seems to be coming from Git, but I just can't figure out why it only happens from within a multiprocessing.Process(). Note, below is an example to demonstrate what's happening... in real code there is a lot more going on within the Process()... but I'm using Popen to make shell calls as part of it: #!/usr/bin/python import os import shutil from multiprocessing import Process from subprocess import Popen def run(): cmd_args = ['git', 'clone', 'git@github.com:derks/test.git', 'test-repo-checkout'] res = Popen(cmd_args) res.wait() # clean if os.path.exists('./test-repo-checkout'): shutil.rmtree('./test-repo-checkout') print "\n--- this doesnt work" process = Process(target=run) process.start() process.join() print "\n--- this does work" run() The result is: $ python test.py --- this doesnt work Cloning into test-repo-checkout... Warning: untrusted X11 forwarding setup failed: xauth key data not generated Warning: No xauth data; using fake authentication data for X11 forwarding. fatal: write error: Broken pipe --- this does work Cloning into test-repo-checkout... Warning: untrusted X11 forwarding setup failed: xauth key data not generated Warning: No xauth data; using fake authentication data for X11 forwarding. remote: Counting objects: 9, done. remote: Compressing objects: 100% (5/5), done. remote: Total 9 (delta 1), reused 0 (delta 0) Receiving objects: 100% (9/9), done. Resolving deltas: 100% (1/1), done. Any help would really be great... I'm still new to the multiprocessing module and haven't come across any issues with it until now. A: Hrm, I just realized I was running on Python 2.6.1 .... running the same example on 2.6.4 does not have the same issue. Looks like a bug that was fix in Python.
Broken Pipe when calling subprocess.Popen() within a multiprocessing.Process()
I am having an issue when making a shell call from within a multiprocessing.Process(). The error seems to be coming from Git, but I just can't figure out why it only happens from within a multiprocessing.Process(). Note, below is an example to demonstrate what's happening... in real code there is a lot more going on within the Process()... but I'm using Popen to make shell calls as part of it: #!/usr/bin/python import os import shutil from multiprocessing import Process from subprocess import Popen def run(): cmd_args = ['git', 'clone', 'git@github.com:derks/test.git', 'test-repo-checkout'] res = Popen(cmd_args) res.wait() # clean if os.path.exists('./test-repo-checkout'): shutil.rmtree('./test-repo-checkout') print "\n--- this doesnt work" process = Process(target=run) process.start() process.join() print "\n--- this does work" run() The result is: $ python test.py --- this doesnt work Cloning into test-repo-checkout... Warning: untrusted X11 forwarding setup failed: xauth key data not generated Warning: No xauth data; using fake authentication data for X11 forwarding. fatal: write error: Broken pipe --- this does work Cloning into test-repo-checkout... Warning: untrusted X11 forwarding setup failed: xauth key data not generated Warning: No xauth data; using fake authentication data for X11 forwarding. remote: Counting objects: 9, done. remote: Compressing objects: 100% (5/5), done. remote: Total 9 (delta 1), reused 0 (delta 0) Receiving objects: 100% (9/9), done. Resolving deltas: 100% (1/1), done. Any help would really be great... I'm still new to the multiprocessing module and haven't come across any issues with it until now.
[ "Hrm, I just realized I was running on Python 2.6.1 .... running the same example on 2.6.4 does not have the same issue. Looks like a bug that was fix in Python.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python", "subprocess" ]
stackoverflow_0003843789_multiprocessing_python_subprocess.txt
Q: Increasing a datetime field with queryset.update My model looks like this class MyModel(models.Model): end_time = DateTimeField() and this is what I'm trying to achieve: m=MyModel.objects.get(pk=1) m.end_time += timedelta(seconds=34) m.save() but I want to do it with update() to avoid race conditions: MyModel.objects.filter(pk=1).update(end_time=F('end_time')+timedelta(seconds=34)) but it doesn't work. Is this possible with the django ORM or is raw SQL the only option? A: This is completely possible. Not sure if you're looking at a cached value for your end_time, but here is a test I just ran: >>> e = Estimate.objects.get(pk=17) >>> e.departure_date datetime.datetime(2010, 8, 12, 0, 1, 8) >>> Estimate.objects.filter(pk=17).update(departure_date=F('departure_date')+timedelta(seconds=34)) 1 >>> e.departure_date datetime.datetime(2010, 8, 12, 0, 1, 8) >>> e = Estimate.objects.get(pk=17) >>> e.departure_date datetime.datetime(2010, 8, 12, 0, 1, 42)
Increasing a datetime field with queryset.update
My model looks like this class MyModel(models.Model): end_time = DateTimeField() and this is what I'm trying to achieve: m=MyModel.objects.get(pk=1) m.end_time += timedelta(seconds=34) m.save() but I want to do it with update() to avoid race conditions: MyModel.objects.filter(pk=1).update(end_time=F('end_time')+timedelta(seconds=34)) but it doesn't work. Is this possible with the django ORM or is raw SQL the only option?
[ "This is completely possible. Not sure if you're looking at a cached value for your end_time, but here is a test I just ran:\n>>> e = Estimate.objects.get(pk=17)\n>>> e.departure_date\ndatetime.datetime(2010, 8, 12, 0, 1, 8)\n>>> Estimate.objects.filter(pk=17).update(departure_date=F('departure_date')+timedelta(se...
[ 2 ]
[]
[]
[ "datetime", "django", "django_orm", "python" ]
stackoverflow_0003843250_datetime_django_django_orm_python.txt
Q: python app gets stuck on shuffle and loop I am working on this small little piece in python and when I run it, It never gets past the print 'c' line and is stuck on the while loop. What am I doing wrong? link to text file: http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip enter code here import sys import random inp = open('5desk.txt', 'r') lis = inp.readlines() inp.close() print lis def proc(): a = raw_input('What are the scrambled letters? ') copy = list(a) print a print copy if a in lis: print a, ' is a word' elif a not in lis: print 'c' while copy not in lis: random.shuffle(copy) print 'd' print "A word that ", a, " might equal is:\n", copy if __name__ == "__main__": proc() A: Perhaps you meant this instead: while copy in lis: Either way there is no guarantee that rearranging the letters will eventually create a word that either is or is not in the list. In particular if the input contains only one letter then the shuffle will have no effect at all. It might be better to iterate over all the permutations in a random order, and if you reach the end of the list break out of the loop with a error. A: readline() and readlines() keep the trailing newline from each line of the input; raw_input() strips newlines. Thus there's never a match. When reading input from external sources, it's often a good idea to use the strip() function to clean things up - by default, it removes whitespace from each end of its input. Try: lis = [line.strip() for line in inp.readlines()]
python app gets stuck on shuffle and loop
I am working on this small little piece in python and when I run it, It never gets past the print 'c' line and is stuck on the while loop. What am I doing wrong? link to text file: http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip enter code here import sys import random inp = open('5desk.txt', 'r') lis = inp.readlines() inp.close() print lis def proc(): a = raw_input('What are the scrambled letters? ') copy = list(a) print a print copy if a in lis: print a, ' is a word' elif a not in lis: print 'c' while copy not in lis: random.shuffle(copy) print 'd' print "A word that ", a, " might equal is:\n", copy if __name__ == "__main__": proc()
[ "Perhaps you meant this instead:\nwhile copy in lis:\n\nEither way there is no guarantee that rearranging the letters will eventually create a word that either is or is not in the list. In particular if the input contains only one letter then the shuffle will have no effect at all. It might be better to iterate ove...
[ 1, 1 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0003843709_list_loops_python.txt
Q: Python: replacing method in calendar module I'm trying to replace two methods in calendar module: import calendar c = calendar.HTMLCalendar(calendar.MONDAY) def ext_formatday(self, day, weekday, *notes): if day == 0: return '<td class="noday">&nbsp;</td>' if len(notes) == 0: return '<td class="%s">%d<br /></td>' % (self.cssclasses[weekday], day) else: return '<td class="%s">%d<br />%s</td>' % (self.cssclasses[weekday], day, notes) def ext_formatweek(self, theweek, *notes): if len(notes) == 0: s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) else: s = ''.join(self.formatday(d, wd, notes) for (d, wd) in theweek) return '<tr>%s</tr>' % s c.formatday = ext_formatday c.formatweek = ext_formatweek print c.formatmonth(2012,1,"foobar") This won't work - could somebody point me to relevant literature or point out what I'm doing wrong? I'm trying to implement Alan Hynes suggestion from the following thread: thread It way too late for me to think straight and I've been dancing around that problem for over an hour. Thanks in advance, Jakub A: Try replacing the method at the class instead of the instance. Like this: import calendar def ext_formatday(self, day, weekday, *notes): if day == 0: return '<td class="noday">&nbsp;</td>' if len(notes) == 0: return '<td class="%s">%d<br /></td>' % (self.cssclasses[weekday], day) else: return '<td class="%s">%d<br />%s</td>' % (self.cssclasses[weekday], day, notes) def ext_formatweek(self, theweek, *notes): if len(notes) == 0: s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) else: s = ''.join(self.formatday(d, wd, notes) for (d, wd) in theweek) return '<tr>%s</tr>' % s calendar.HTMLCalendar.formatday = ext_formatday calendar.HTMLCalendar.formatweek = ext_formatweek c = calendar.HTMLCalendar(calendar.MONDAY) print c.formatmonth(2012,1,"foobar") A: Updated to use types.MethodType as suggested by Aaron in the comments. Try: import types c.formatday = types.MethodType(ext_formatday, c, calendar.HTMLCalendar) See the types module docs. To see why it was failing: In [53]: class A(object): ....: def foo(self): pass In [54]: def bar(self): pass In [55]: a = A() In [56]: a.foo Out[56]: <bound method A.foo of <__main__.A object at 0x030D4770>> In [57]: a.foo = bar In [58]: a.foo Out[58]: <function bar at 0x030C3EB0> In [59]: aa = A() In [60]: aa.foo.im_class, aa.foo.im_func, aa.foo.im_self Out[60]: (<class '__main__.A'>, <function foo at 0x030EE6F0>, <__main__.A object at 0x030D4910>) In [61]: a.foo.im_class AttributeError: 'function' object has no attribute 'im_class' A: You don't want to replace the methods; what Alan Hynes suggested was to subclass HTMLCalendar: class MyCustomCalendar(calendar.HTMLCalendar): def formatday(self, day, weekday, *notes): ... def formatweek(self, theweek, *notes): ... c = MyCustomCalendar(calendar.MONDAY) This will create a new derived class (MyCustomCalendar), which inherits all HTMLCalendar's methods and attributes, but defines its own versions of formatday and formatweek. You can read more about Inheritance in the Python tutorial, or elsewhere on the web. It's an important tool in Python (and object-oriented programming in general), and many libraries are designed around it.
Python: replacing method in calendar module
I'm trying to replace two methods in calendar module: import calendar c = calendar.HTMLCalendar(calendar.MONDAY) def ext_formatday(self, day, weekday, *notes): if day == 0: return '<td class="noday">&nbsp;</td>' if len(notes) == 0: return '<td class="%s">%d<br /></td>' % (self.cssclasses[weekday], day) else: return '<td class="%s">%d<br />%s</td>' % (self.cssclasses[weekday], day, notes) def ext_formatweek(self, theweek, *notes): if len(notes) == 0: s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) else: s = ''.join(self.formatday(d, wd, notes) for (d, wd) in theweek) return '<tr>%s</tr>' % s c.formatday = ext_formatday c.formatweek = ext_formatweek print c.formatmonth(2012,1,"foobar") This won't work - could somebody point me to relevant literature or point out what I'm doing wrong? I'm trying to implement Alan Hynes suggestion from the following thread: thread It way too late for me to think straight and I've been dancing around that problem for over an hour. Thanks in advance, Jakub
[ "Try replacing the method at the class instead of the instance.\nLike this:\nimport calendar \n\n\ndef ext_formatday(self, day, weekday, *notes): \n if ...
[ 1, 0, 0 ]
[]
[]
[ "calendar", "python" ]
stackoverflow_0003843800_calendar_python.txt
Q: Modifying The Template For New Pylons Controllers I'm at a point in my Pylons projects where I end up creating and deleting controllers often (probably more often than I should). I grow tired of adding my own imports and tweaks to the top of every controller. There was a recent question about modifying the new controller template that got me part-way to not having to do that - but I don't understand how the controller.py_tmpl file is used by paster, and how I can tell Paster to, for an existing project, "hey, use this template instead!" What invocation do I need to tell Paster to use my template instead of the default one? A: Pylons creates new controllers and projects by adding command to paste. The commands are defined in setup.py and you can add new commands. For example (this is taken from the Paste docs) lets assume you have a project called Foo that is in a package also called foo. In setup.py add 'foo' to the 'paster_plugins' list Then add a new command to entry_points. ie entry_points=""" [paste.paster_command] mycommand = foo.commands.test_command:Test """ Create a directory called 'commands' under 'foo', add a __init.py__ file and create a file called test_command.py In the file add from paste.script import command class TestCommand(command.Command): max_args = 1 min_args = 1 usage = "NAME" summary = "Say hello!" group_name = "My Package Name" parser = command.Command.standard_parser(verbose=True) parser.add_option('--goodbye', action='store_true', dest='goodbye', help="Say 'Goodbye' instead") def command(self): name = self.args[0] if self.verbose: print "Got name: %r" % name if self.options.goodbye: print "Goodbye", name else: print "Hello", name After you run 'python setup.py develop' you can now run 'paste mycommand bob' and you should get 'Hello bob' output. To see how Pylons adds to this to create new files etc. look in pylons/commands.py they have commands for creating new Controllers and RestControllers that you can copy.
Modifying The Template For New Pylons Controllers
I'm at a point in my Pylons projects where I end up creating and deleting controllers often (probably more often than I should). I grow tired of adding my own imports and tweaks to the top of every controller. There was a recent question about modifying the new controller template that got me part-way to not having to do that - but I don't understand how the controller.py_tmpl file is used by paster, and how I can tell Paster to, for an existing project, "hey, use this template instead!" What invocation do I need to tell Paster to use my template instead of the default one?
[ "Pylons creates new controllers and projects by adding command to paste. The commands are defined in setup.py and you can add new commands.\nFor example (this is taken from the Paste docs) lets assume you have a project called Foo that is in a package also called foo.\nIn setup.py add 'foo' to the 'paster_plugins' ...
[ 1 ]
[]
[]
[ "paste", "paster", "pylons", "python" ]
stackoverflow_0003791790_paste_paster_pylons_python.txt
Q: Tracd Realm I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the site I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server. The Command Line sent was: tracd --port 8000 --auth=My_Test_Project,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac The Warning message was - 'Warning: found no users in realm: trac' Thanks... A: Replacing the above said command line with the one bellow helps. tracd --port 8000 --auth=Trac,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac The string after --auth= should be the environment name and not the project name. A: Check your password digest file. Looking at mine it appears that the output is stored as a line with three fields in this format: username:realm:passwordhash. If your getting that warning then it could be a mismatch between the realm field in the digest file and the realm that you're passing in when launching tracd. Looking in the python generator script there are three options: -u for user -p for password -r for realm When I generate my digest file using this command line (assuming you named it trac-digest.py): python trac-digest.py -u user -p pass >> digest.txt it generates this line in my digest.txt: user:trac:1d395970d2a9a075d0536a4d6e4d0679 So looks like the default realm is trac and launching tracd with the --auth option specified like the documentation says always gives me that warning 'Warning: found no users in realm: realm' But when I generate my digest file using the -r parameter: python trac-digest.py -u user -p pass -r realm >> digest.txt it generates this line in my digest.txt: user:realm:1d395970d2a9a075d0536a4d6e4d0679 And I no longer get that warning when I specify the realm that I passed to trac-digest.py. A: The text referred to says that you must specify the realm name as "trac", not "Trac", but I have no chance of testing whether that makes any difference, sorry.
Tracd Realm
I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the site I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value and also tried leaving it empty. I am using Windows XP. I am using Tracd Standalone server. The Command Line sent was: tracd --port 8000 --auth=My_Test_Project,D:\My_Test_Project\Documents\Trac\digest.txt,Trac D:\My_Test_Project\Documents\Trac The Warning message was - 'Warning: found no users in realm: trac' Thanks...
[ "Replacing the above said command line with the one bellow helps.\ntracd --port 8000 --auth=Trac,D:\\My_Test_Project\\Documents\\Trac\\digest.txt,Trac D:\\My_Test_Project\\Documents\\Trac\nThe string after --auth= should be the environment name and not the project name.\n", "Check your password digest file. Look...
[ 6, 5, 1 ]
[]
[]
[ "project_management", "python", "trac", "wiki" ]
stackoverflow_0000200447_project_management_python_trac_wiki.txt
Q: How to diagnose reason for slow access to sqlite database? As I have stated in this question some time ago, I am having performance problems when accessing an sqlite database from Python. To make that clear once more, the identical code runs more than 20 times faster using apsw. I recently installed a different version of Python in parallel and installed a new version of apsw for that. This version ran slow too. I tried the same code on a different computer using pythons built-int sqlite3, and it ran fast (but slow with apsw). I also tried to install the most recent version of pysqlite on my computer, but that ran slow. I am absolutely certain that it is not an issue with the schema. My question now is, how can I proceed to diagnose the error? A: Just in case you may have overlooked this, make sure you are working with the latest versions of both the pysqlite2 data base adapter and the sqlite3 library. The linked answer also shows how to determine exactly which version of each you are using, data which you might want to add to your question. A: I can offer my experience on a similar experience, but with a different platform, namely J. There was some slowness, and I pinpointed it to the sqlite3_get_table function. This function returns a pointer for each column, each pointing to an array of pointers, where each of those refers to a null terminated string. Pointers can also be null if the result of a function is null (say a Max on an empty dataset, it will return a null pointer, and not a pointer to a null. I hate that.) J then formed the addresses as readable (form a large matrix of addresses followed with a 0 for offset and -1 for length, meaning up to first null) and cycles through each, to finally re-shape the table in its intended columns and rows. So, there's a memory transfer aspect, as well as the actual reading aspect, to fetching data from SQLite to another platform. I have found that this often large dataset is not easily handled by J, meaning that it's clunky as all strings. Plus there's that nasty null pointer thing. I was able to limit matrix modifications enough to optimise the function. The final optimisation was to use the primitive code for reading a memory address (15!:1), and not decently named function (memr), because using memr meant J had to interpret what memr means at every memory read. In conclusion, if python allows some modification, maybe you can tweak database access to better suit your needs. I hope this helps, but I don't have very high hopes...
How to diagnose reason for slow access to sqlite database?
As I have stated in this question some time ago, I am having performance problems when accessing an sqlite database from Python. To make that clear once more, the identical code runs more than 20 times faster using apsw. I recently installed a different version of Python in parallel and installed a new version of apsw for that. This version ran slow too. I tried the same code on a different computer using pythons built-int sqlite3, and it ran fast (but slow with apsw). I also tried to install the most recent version of pysqlite on my computer, but that ran slow. I am absolutely certain that it is not an issue with the schema. My question now is, how can I proceed to diagnose the error?
[ "Just in case you may have overlooked this, make sure you are working with the latest versions of both the pysqlite2 data base adapter and the sqlite3 library. The linked answer also shows how to determine exactly which version of each you are using, data which you might want to add to your question.\n", "I can ...
[ 1, 0 ]
[]
[]
[ "performance", "python", "sqlite" ]
stackoverflow_0003842250_performance_python_sqlite.txt
Q: Please recommend some Python hashing algorithms I'm doing a password hashing program in python. I need to make my hashing dynamic, i.e. each time I need to get different hashed code. I am using md5 library. A: The information that you want can be found in Python's hashlib module. From the documentation: This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm (defined in Internet RFC 1321). The terms secure hash and message digest are interchangeable. Older algorithms were called message digests. The modern term is secure hash. A: You can use salt for that. import hashlib string = "password" strsalt = "anyrandomvalue" #this can be generated.. etc. hashlib.md5(string + strsalt).hexdigest()
Please recommend some Python hashing algorithms
I'm doing a password hashing program in python. I need to make my hashing dynamic, i.e. each time I need to get different hashed code. I am using md5 library.
[ "The information that you want can be found in Python's hashlib module. From the documentation:\n\nThis module implements a common interface to many different secure hash and message digest \n algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and \n SHA512 (defined in ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003844062_python.txt
Q: Static or constant or what are they? I just want to know how I can call certian classes in design pattern here, like which type are they classified in OO design (1) I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class. (2) I use a class with full of static methods, this class is basically used by other classes as a holder of methods that are used by them. So again i dont instantiate the class. What are these kinda classes classified under OOdesign? Can I do it in a more elegant way? A: What are these kinda classes classified under OOdesign? Can I do it in a more elegant way? You do have better alternatives, IMHO. I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class. For e.g. in this case you don't necessarily need a class. You can have a settings module that defines the various "constants". I put constants in quotes because there are no constants in Python the way there are in say, Java. (2) I use a class with full of static methods, this class is basically used by other classes as a holder of methods that are used by them. So again i dont instantiate the class. Again, no need for a class. You can have one or more modules that contain these methods or rather, functions. They can be logically grouped as you see fit. I'd like to add a note that you don't have to stick to (Java style?) "classes only" approach (for lack of a better phrase). Rather try to write code that doesn't go against the grain of the language. In Python's case I'd argue that such classes as you described above are best avoided. They seem to me like a carry over from Java. A: Many (but not all) languages that focus strongly on OOP (C++, C#, Java) have an enum type for constants rather than putting them in a class. However, in other languages, such as Smalltalk and Python, there is no special construct for constants and it can make sense to put them in a class. To the best of my knowledge, there's no special name for that kind of class. In other languages, a static class is a class that cannot be instantiated and which defines only constants and static methods. Even though Python has no language-level support for enforcing those rules, I would still refer to a class designed that way as a static class. In Python 2.6 or greater, you can use a class decorator to enforce the rules: def staticclass(cls): """Decorator to ensure that there are no unbound methods and no instances are created""" for name in cls.__dict__.keys(): ob = getattr(cls, name) if isinstance(ob, types.MethodType) and ob.im_self is None: raise RuntimeError, "unbound method in class declared no_instances" def illegal(self): raise RuntimeError,"Attempt to instantiate class declared no_instances" cls.__init__ = illegal return cls @staticclass class MyStaticClass(object): pass As Manoj points out, many times you can do away with the class and put the constants or functions at the module level. However, there are cases where it really is useful to have a class. For example, if the class has significant state, putting the functions at the module level requires littering the code with global statements. Although rare, it is also sometimes useful to have a class hierarchy of static classes. Another alternative to a static class is the singleton pattern, where you ensure that only one instance of the class is every created (and typically provide a static method that returns that instance).
Static or constant or what are they?
I just want to know how I can call certian classes in design pattern here, like which type are they classified in OO design (1) I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class. (2) I use a class with full of static methods, this class is basically used by other classes as a holder of methods that are used by them. So again i dont instantiate the class. What are these kinda classes classified under OOdesign? Can I do it in a more elegant way?
[ "\nWhat are these kinda classes classified under OOdesign? Can I do it in a more elegant way?\n\nYou do have better alternatives, IMHO.\n\nI use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class.\n\nFor e.g. in this case y...
[ 8, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003844158_oop_python.txt
Q: simple python connect 4 game. why doesnt this test work? Everything about this code seems to work perfectly, except the tests for diagonal wins. The tests for vertical and horizontal wins seem to be exactly the same concept, and they work perfectly. The comments should mostly explain it, but the test should basically iterate through the board and check for x's in the bottom left hand corner (the only place that a right facing diagonal can start). it then goes up and to the right one space four times to check for a four in a row. Here is the function in question. #for diagonal #not working! WHYYYY def winnertest3(): for i in range(3): for e in range(4): print i,e if board[i][e]=='X' and board[i+1][e+1]=='X' and board[i+2][e+2]=='X' and board[i+3][e+3]=='X': print "X wins!!!!" return 'over' return 'on' http://github.com/keevie/Computer-Science/blob/master//board1.py A: It worked for me. I started in the bottom right hand corner with an X and worked it up diagonally to the left. I also started one to the left of that initial position. However, when I got 4 X's in a row, it didn't immediately stop - I had to put another O in because it only checks to see if the game should stop after an O is placed. Have you been testing the right diagonal?
simple python connect 4 game. why doesnt this test work?
Everything about this code seems to work perfectly, except the tests for diagonal wins. The tests for vertical and horizontal wins seem to be exactly the same concept, and they work perfectly. The comments should mostly explain it, but the test should basically iterate through the board and check for x's in the bottom left hand corner (the only place that a right facing diagonal can start). it then goes up and to the right one space four times to check for a four in a row. Here is the function in question. #for diagonal #not working! WHYYYY def winnertest3(): for i in range(3): for e in range(4): print i,e if board[i][e]=='X' and board[i+1][e+1]=='X' and board[i+2][e+2]=='X' and board[i+3][e+3]=='X': print "X wins!!!!" return 'over' return 'on' http://github.com/keevie/Computer-Science/blob/master//board1.py
[ "It worked for me. I started in the bottom right hand corner with an X and worked it up diagonally to the left. I also started one to the left of that initial position. However, when I got 4 X's in a row, it didn't immediately stop - I had to put another O in because it only checks to see if the game should stop af...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003844306_python.txt
Q: Django Group By I'm writing a simple private messenger using Django and am implementing message threading. Each series of messages and replies will have a unique thread_id that will allow me to string sets of messages together. However, in the inbox view ALL of the messages are showing up, I'd just like to group by the thread_id so that although a thread could have 20 messages, it only shows up once in the inbox. It'd be a pretty simple SELECT msg_id, msg_text, subject, from_user_id, to_user_id, date_time, is_read, thread_id WHERE to_user_id='foo' GROUP BY thread_id FROM inbox_message; however, I can't seem to execute it using django's ORM any thoughts? A: What do you want to achieve with this SQL statement? It will work on some DBMS (ie. MySQL), but it isn't legal. When your are using GROUP BY statement, you can select only columns your are grouping by, and aggregates (SUM, AVG, COUNT etc.). Other columns are forbidden, because DBMS don't know what data return (ie. should it return subject of first message, second one or what?). If you wan't some sumup about thread, other than count of messages, probably best solution for you is to add new columns to thread table (BTW. do you have thread table?).
Django Group By
I'm writing a simple private messenger using Django and am implementing message threading. Each series of messages and replies will have a unique thread_id that will allow me to string sets of messages together. However, in the inbox view ALL of the messages are showing up, I'd just like to group by the thread_id so that although a thread could have 20 messages, it only shows up once in the inbox. It'd be a pretty simple SELECT msg_id, msg_text, subject, from_user_id, to_user_id, date_time, is_read, thread_id WHERE to_user_id='foo' GROUP BY thread_id FROM inbox_message; however, I can't seem to execute it using django's ORM any thoughts?
[ "What do you want to achieve with this SQL statement?\nIt will work on some DBMS (ie. MySQL), but it isn't legal. When your are using GROUP BY statement, you can select only columns your are grouping by, and aggregates (SUM, AVG, COUNT etc.). Other columns are forbidden, because DBMS don't know what data return (ie...
[ 1 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0003844392_django_python_sql.txt
Q: Why is there no "compound method call statement", i.e. ".="? Lots of programming languages already have the compound statements +=, -=, /=, etc. A relatively new style of programming is to "chain" method calls onto each other, e.g. in Linq, JQuery and Django's ORM. I sometimes, more often than I'd like, find the need to do this in Django: # Get all items whose description beginning with A items = Items.objects.filter(desc__startswith='A') if something: # Filter further to items whose description also ends with Z items = items.filter(desc__endswith='Z') I think it would be easier and actually more readable if there was a compound method call statement such as .= which could work like this: items = Items.objects.filter(desc__startswith='A') if something: items .= filter(desc__endswith='Z') Are there any programming languages that support this or something like it? If the answer is no, why not? Is this style of programming really that new? Are there any PEPs (Python Enhancement Proposals) that support this idea? A: This is supported in Perl 6. A: IMHO, i don't like it. just imagine this, items .= click(function(){...}); it's not a syntax error anymore, but it doesn't make sense, does it? I can say it does not make sense simply because if you expand my example, it would be like this, items = items.click(function(){...}); items.click(function(){...}); would just return the object items , and you will assign it to items? in this example, items .= filter(desc__endswith='Z'); it would make sense, but not true to all objects, maybe that's the reason it was not implemented. as to parent .= children();, what happens to parent later on the codes? I'm talking jQuery way. A: I can't answer those questions, and I'm not sure what I think of this because I havn't seen it before, but it does have an interesting applicatioon: all of the inplace operators become obsolete. a = 1 a .= __add__(1) a .= __mul__(2) Of course, it's clearer to write a += 1, but if this syntax had come earlier in the design of the language, and the __add__ methods were less ugly (eg. just add), the language today might have eleven fewer operators today. (Of course, there would be other implications of that--in particular, the automatic fallback from __iadd__ to __add__ would be lost. Still, it's an interesting concept.) A: Scala's collections support in-place operations, provided that the variable is a var. scala> var L = List("b", "c") L: List[java.lang.String] = List(b, c) scala> L ::= "a" scala> L res8: List[java.lang.String] = List(a, b, c) (For those unfamiliar with Scala, :: is a method of List) This is a style of programming that many avoid, and in Scala you can avoid such in-place mutation by using immutable vals: scala> val L = List("b", "c") L: List[java.lang.String] = List(b, c) scala> L ::= "a" <console>:7: error: reassignment to val L ::= "a" A: I have thought about this often when doing Java or C# programming, where you find yourself repeating not just one but often the same two or more object references on both sides of the assignment -- e.g., you have a member of some object that is a string, and you want to call some methods on that string and assign it back to the member variable. Oddly enough, it hasn't bothered me nearly as much in Python. The .= operator you propose is one idea I thought of at the time I was doing C#. Another option would be to allow a leading dot to as a shorthand for the object being assigned to, like this: foo.bar.str = .lower() # same as foo.bar.str = foo.bar.str.lower() Pascal, Modula-2, and Visual Basic have a with statement (different from Python's statement of the same name) that would allow you to write something like this if it existed in Python (I call it "using" here so it is not mistaken for valid Python): using foo.bar: str = str.lower() # same as foo.bar.str = foo.bar.str.lower() This is very convenient when you are going to be doing a lot of manipulation of members of a single object since it allows a block. However, you still have a level of redundancy here, which could be eliminated if you combined the last two ideas like so: using foo.bar: str = .lower() This seems to me like it would be a nice bit of syntactic sugar, and I find it very readable, but it does not seem like it is high on the priority list of most language designers. However, since Python does have Modula-2 influences, perhaps it's not out of the question that it would eventually be added. A: Ruby has this feature in a way, but implements it differently. This is through 'destructive' methods, which alter the variable they are called on. For example, calling str.split just returns the object split, it doesn't alter it. But, if you call str.split! it changes it in place. Most builtin array and string methods have a destructive and non-destructive version.
Why is there no "compound method call statement", i.e. ".="?
Lots of programming languages already have the compound statements +=, -=, /=, etc. A relatively new style of programming is to "chain" method calls onto each other, e.g. in Linq, JQuery and Django's ORM. I sometimes, more often than I'd like, find the need to do this in Django: # Get all items whose description beginning with A items = Items.objects.filter(desc__startswith='A') if something: # Filter further to items whose description also ends with Z items = items.filter(desc__endswith='Z') I think it would be easier and actually more readable if there was a compound method call statement such as .= which could work like this: items = Items.objects.filter(desc__startswith='A') if something: items .= filter(desc__endswith='Z') Are there any programming languages that support this or something like it? If the answer is no, why not? Is this style of programming really that new? Are there any PEPs (Python Enhancement Proposals) that support this idea?
[ "This is supported in Perl 6.\n", "IMHO, i don't like it.\njust imagine this,\nitems .= click(function(){...});\n\nit's not a syntax error anymore, but it doesn't make sense, does it?\nI can say it does not make sense simply because if you expand my example, it would be like this,\nitems = items.click(function(){...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "jquery", "linq", "programming_languages", "python", "syntax" ]
stackoverflow_0003829078_jquery_linq_programming_languages_python_syntax.txt
Q: Can't upload file in Google App Engine I don't know why I can't upload my file? When I hit submit instead of redirecting to the default page (which is http://localhost:8082), it redirects to http://localhost:8082/sign. I didn't build no such path, so it return link broken. Here's my html: <form action="/sign" enctype="multipart/form-data" method="post"> <div><label>Excel file submit:</label></div> <div><input type="file" name="excel"/></div> <div><input type="submit" value="Upload file"></div> </form> my app.yaml: application: engineapp01 version: 1 runtime: python api_version: 1 handlers: - url: /js static_dir: js - url: /css static_dir: css - url: .* script: main.py main.py: import os; from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp import template from google.appengine.ext import db from mmap import mmap,ACCESS_READ from xlrd import open_workbook class Account(db.Model): name = db.StringProperty() type = db.StringProperty() no = db.IntegerProperty() co = db.IntegerProperty() class MyFile(db.Model): filedata = db.BlobProperty() class MainHandler(webapp.RequestHandler): def get(self): #delete all old temporary entries query = Account.all() results = query.fetch(limit=40) db.delete(results) #temporary entry acc = Account(name='temporaryAccountName', type='temporaryType', no=0, co=500) acc.put() temp = os.path.join(os.path.dirname(__file__),'templates/index.htm') tableData = '' query = Account.all() query.order('name') results = query.fetch(limit=20) for account in results: tempStr= """ <tr> <td align='left' valign='top'>%s</td> <td align='left' valign='top'>%s</td> <td align='left' valign='top'>%d</td> <td align='left' valign='top'>%d</td> </tr>""" % (account.name,account.type,account.no,account.co) tableData = tableData + tempStr outstr = template.render( temp, {'tabledata':tableData}) self.response.out.write(outstr) def post(self): myFile = MyFile() excel = self.request.get("excel") myFile.fileData = db.Blob(excel) myFile.put() self.redirect('/') def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() A: Why are you sending the form data to a page that doesn't exist? Try changing the HTML to: <form action="/" enctype="multipart/form-data" method="post"> ... ...since "/" is where your form-handling code resides.
Can't upload file in Google App Engine
I don't know why I can't upload my file? When I hit submit instead of redirecting to the default page (which is http://localhost:8082), it redirects to http://localhost:8082/sign. I didn't build no such path, so it return link broken. Here's my html: <form action="/sign" enctype="multipart/form-data" method="post"> <div><label>Excel file submit:</label></div> <div><input type="file" name="excel"/></div> <div><input type="submit" value="Upload file"></div> </form> my app.yaml: application: engineapp01 version: 1 runtime: python api_version: 1 handlers: - url: /js static_dir: js - url: /css static_dir: css - url: .* script: main.py main.py: import os; from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp import template from google.appengine.ext import db from mmap import mmap,ACCESS_READ from xlrd import open_workbook class Account(db.Model): name = db.StringProperty() type = db.StringProperty() no = db.IntegerProperty() co = db.IntegerProperty() class MyFile(db.Model): filedata = db.BlobProperty() class MainHandler(webapp.RequestHandler): def get(self): #delete all old temporary entries query = Account.all() results = query.fetch(limit=40) db.delete(results) #temporary entry acc = Account(name='temporaryAccountName', type='temporaryType', no=0, co=500) acc.put() temp = os.path.join(os.path.dirname(__file__),'templates/index.htm') tableData = '' query = Account.all() query.order('name') results = query.fetch(limit=20) for account in results: tempStr= """ <tr> <td align='left' valign='top'>%s</td> <td align='left' valign='top'>%s</td> <td align='left' valign='top'>%d</td> <td align='left' valign='top'>%d</td> </tr>""" % (account.name,account.type,account.no,account.co) tableData = tableData + tempStr outstr = template.render( temp, {'tabledata':tableData}) self.response.out.write(outstr) def post(self): myFile = MyFile() excel = self.request.get("excel") myFile.fileData = db.Blob(excel) myFile.put() self.redirect('/') def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
[ "Why are you sending the form data to a page that doesn't exist?\nTry changing the HTML to:\n<form action=\"/\" enctype=\"multipart/form-data\" method=\"post\">\n...\n\n...since \"/\" is where your form-handling code resides.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003844488_google_app_engine_python.txt
Q: My .yaml is not redirecting properly app.yaml application: classscheduler9000 version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /images static_dir: static/images - url: /stylesheets static_dir: static/stylesheets - url: /users\.html script: main.py - url: /.* script: login.py main.py import hashlib from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db class AccountHolder(db.Model): ... class MainPage(webapp.RequestHandler): def get(self): ... class UserWrite(webapp.RequestHandler): def post(self): ... application = webapp.WSGIApplication( [('/', MainPage), ('/sign', UserWrite)], debug=True) def getMD5Hash(textToHash=None): return hashlib.md5(textToHash).hexdigest() def main(): run_wsgi_app(application) if __name__ == "__main__": main() I'm currently testing this offline with Google App Engine. When I go to localhost:8080, It takes me to my login page. However, when I try to access localhost:8080/users.html, it doesn't load my main.py file (It errors out like a broken link). If I swap the urls, main.py works, but login.py won't load. I know this is probably some stupid oversight on my part, and I couldn't find any help on google or this site. Thanks for any help. A: The issue is with your application definition. application = webapp.WSGIApplication([('/user\.html', MainPage), ('/sign', UserWrite)], debug=True) The documentation about this is here, although it does not have "simple" examples. http://code.google.com/appengine/docs/python/tools/webapp/running.html Just a note, you do not need to use the .html. Instead you can map '/user' in both places.
My .yaml is not redirecting properly
app.yaml application: classscheduler9000 version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /images static_dir: static/images - url: /stylesheets static_dir: static/stylesheets - url: /users\.html script: main.py - url: /.* script: login.py main.py import hashlib from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db class AccountHolder(db.Model): ... class MainPage(webapp.RequestHandler): def get(self): ... class UserWrite(webapp.RequestHandler): def post(self): ... application = webapp.WSGIApplication( [('/', MainPage), ('/sign', UserWrite)], debug=True) def getMD5Hash(textToHash=None): return hashlib.md5(textToHash).hexdigest() def main(): run_wsgi_app(application) if __name__ == "__main__": main() I'm currently testing this offline with Google App Engine. When I go to localhost:8080, It takes me to my login page. However, when I try to access localhost:8080/users.html, it doesn't load my main.py file (It errors out like a broken link). If I swap the urls, main.py works, but login.py won't load. I know this is probably some stupid oversight on my part, and I couldn't find any help on google or this site. Thanks for any help.
[ "The issue is with your application definition. \napplication = webapp.WSGIApplication([('/user\\.html', MainPage),\n ('/sign', UserWrite)],\n debug=True)\n\nThe documentation about this is here, although it does not have \"simple\" examples....
[ 2 ]
[]
[]
[ "google_app_engine", "python", "yaml" ]
stackoverflow_0003844293_google_app_engine_python_yaml.txt
Q: What structured text format is the best supported in Python? This question may be seen as subjective, but I'd like to ask SO users which common structured textual data format is best supported in Python. My initial choices are: XML JSON and YAML Which of these three is easiest to work with in Python (ie. has the best library support / performance) ... or is there another format that I haven't mentioned that is better supported in Python. I cannot use a Python only format (e.g. Pickling) since interop is quite important, but the majority of the code that handles these files will be written in Python, so I'm keen to use a format that has the strongest support in Python. CSV or fixed column text may also be viable for most use cases, however I'd prefer the flexibility of a more scalable format. Thank you Note Regarding interop I will be generating these files initially from Ruby, using Builder, however Ruby will not be consuming these files again. A: I would go with JSON, I mean YAML is awesome but interop with it is not that great. XML is just an ugly mess to look at and has too much fat. Python has a built-in JSON module since version 2.6. A: JSON has great python support and it is much more compact than XML (and the API is generally more convenient if you're just trying to dump and load objects). There's no out of the box support for YAML that I know of, although I haven't really checked. In the abstract I would suggest using JSON due to the low overhead of the format and the wide range of language support, but it does depend a bit on your application - if you're working in a space that already has established applications, the formats they use might be preferable, even if they're technically deficient. A: I think it depends a lot on what you need to do with the data. If you're going to be building a complex database and doing processing and transformations on it, I suspect you'd be better off with XML. I've found the lxml module pretty useful in this regard. It has full support for standards like xpath and xslt, and this support is implemented in native code so you'll get good performance. But if you're doing something more simple, then likely you'd be better off to use a simpler format like yaml or json. I've heard tell of "json transforms" but don't know how mature the technology is or how developed Python's access to it is. A: It's pretty much all the same, out of those three. Use whichever is easier to inter-operate with.
What structured text format is the best supported in Python?
This question may be seen as subjective, but I'd like to ask SO users which common structured textual data format is best supported in Python. My initial choices are: XML JSON and YAML Which of these three is easiest to work with in Python (ie. has the best library support / performance) ... or is there another format that I haven't mentioned that is better supported in Python. I cannot use a Python only format (e.g. Pickling) since interop is quite important, but the majority of the code that handles these files will be written in Python, so I'm keen to use a format that has the strongest support in Python. CSV or fixed column text may also be viable for most use cases, however I'd prefer the flexibility of a more scalable format. Thank you Note Regarding interop I will be generating these files initially from Ruby, using Builder, however Ruby will not be consuming these files again.
[ "I would go with JSON, I mean YAML is awesome but interop with it is not that great.\nXML is just an ugly mess to look at and has too much fat. \nPython has a built-in JSON module since version 2.6.\n", "JSON has great python support and it is much more compact than XML (and the API is generally more convenient i...
[ 4, 3, 1, 0 ]
[]
[]
[ "python", "structured_data", "text" ]
stackoverflow_0003844556_python_structured_data_text.txt
Q: Receiving 0.0 when expecting a non-zero value after division Hai... i am facing a problem while inserting values to an array. the programming language using is python. the problem is, i need to insert a value to array after performing a division. but every the value in array is always 0.0 . i am attaching the code here.... print len(extract_list1) ratio1=range(len(extract_list1)) i=0 for word in extract_list1: ratio1[i]=float(i/len(extract_list1)) print extract_list1[i],ratio1[i] i+=1 ratio2=range(len(extract_list2)) i=0 for word in extract_list2: ratio2[i]=float(i/len(extract_list2)) print extract_list2[i],ratio2[i] i+=1 A: My best guess is that you are performing integer division and then converting to a float yielding the value of 0.0 which is what gets stuck in the list. you want to convert to float before the division. Sift through that wall of code and find out where you are inserting the value into the list. Where that value is generated. then post the code that generates the value. If the value is making it into the list (and you seem to indicate that it is), then this has nothing to do with lists and everything to do with how you are generating the value. As Roger Pate points out in the comments, you can place the line from __future__ import division as the very first line of your source code (or the first line after the encoding if you are using one) and it will automatically convert all division to floating point division. you can then use // as an operator for when you explicitly want truncating integer division. looking at your code, the problem is float(i/len(extract_list2)) this should be float(i)/len(extract_list2)) also, because you are taking the lengths of extract_list2 and extract_list1 multiple times, it would be better to create variables to store them. L1 = len(extract_list1) L2 = len(extract_list2) you can then reference the variables as long as you are not changing the lengths of the lists. This will save you some function calls and make your code more concise and readable.
Receiving 0.0 when expecting a non-zero value after division
Hai... i am facing a problem while inserting values to an array. the programming language using is python. the problem is, i need to insert a value to array after performing a division. but every the value in array is always 0.0 . i am attaching the code here.... print len(extract_list1) ratio1=range(len(extract_list1)) i=0 for word in extract_list1: ratio1[i]=float(i/len(extract_list1)) print extract_list1[i],ratio1[i] i+=1 ratio2=range(len(extract_list2)) i=0 for word in extract_list2: ratio2[i]=float(i/len(extract_list2)) print extract_list2[i],ratio2[i] i+=1
[ "My best guess is that you are performing integer division and then converting to a float yielding the value of 0.0 which is what gets stuck in the list. you want to convert to float before the division. Sift through that wall of code and find out \n\nwhere you are inserting the value into the list.\nWhere that va...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003844637_python.txt
Q: Mercurial for Windows - Python version? What version of Python is needed to run Mercurial? I see that the website says it requires 2.4. Does that mean 2.4, or 2.x? or something higher than 2.4, i.e., could I install 3.x? I've installed Mercurial without reading the requirements and I installed it anyway and hg.exe executes fine. Looking in the directory that hg.exe lives (C:\Program Files\Mercurial\), it has a python26.dll in there. Does that mean i won't have to install Python - i.e. it's bundled with Mercurial? Thanks A: Yes, it comes bundled. If you install Mercurial using the Windows installer, then you don't need to worry about which version of Python you are using. Mercurial uses py2exe to create an executable that runs without a Python installation. A: Python 3.x is not compatible with 2.x. If Mercurial supports 2.4 and above, then you are better off installing python 2.6.x. Yes there are installers available that come bundled with python. You run the following on command line and if you do not get any errors then you are on your way to use mercurial > hg version > hg debuginstall > hg test_mercurial > cd test_mercurial
Mercurial for Windows - Python version?
What version of Python is needed to run Mercurial? I see that the website says it requires 2.4. Does that mean 2.4, or 2.x? or something higher than 2.4, i.e., could I install 3.x? I've installed Mercurial without reading the requirements and I installed it anyway and hg.exe executes fine. Looking in the directory that hg.exe lives (C:\Program Files\Mercurial\), it has a python26.dll in there. Does that mean i won't have to install Python - i.e. it's bundled with Mercurial? Thanks
[ "Yes, it comes bundled. If you install Mercurial using the Windows installer, then you don't need to worry about which version of Python you are using. Mercurial uses py2exe to create an executable that runs without a Python installation.\n", "Python 3.x is not compatible with 2.x. \nIf Mercurial supports 2.4 and...
[ 10, 1 ]
[]
[]
[ "mercurial", "python", "version", "windows" ]
stackoverflow_0003844859_mercurial_python_version_windows.txt
Q: python and matplotlib server side to generate .pdf documents i would like to write a server side python script that generate .pdf documents. for the moment i have Python 2.7 installed server side and matplolib installed server side too. A simple script that create a simple plot and generate a .png picture works. this is the script i use : # to access standard output : import sys # select a non-GUI backend : import matplotlib matplotlib.use('Agg') #matplotlib.use("cairo.pdf") #matplotlib.use('PDF') # import plotting module : import matplotlib.pyplot as plt # generate the plot : plt.plot([1,2,3,2,3,4]) # print the content type (what's the data type) # the new line is embedded, using '\n' notation : print "Content-Type: image/png\n" # print "Content-Type: image/PDF\n" # print "Content-type: application/pdf" # output directly to webserver, as a png file: plt.savefig(sys.stdout, format='png') # plt.savefig(sys.stdout, format='PDF') # plt.savefig( "test.pdf", format='pdf' ) I am wondering how to do the same thing but with sending a pdf file instead of a png picture. (the # or bold character are for all the things i tried and put in comment) Does someone know ? thanks. jean-claude A: First of all, in your code you send to stdout both the words from the print statement and the figure itself. I've just tried your script, changing the comments like this # plt.savefig(sys.stdout, format='png') # plt.savefig(sys.stdout, format='PDF') plt.savefig( "test.pdf", format='pdf' ) and it works just fine for me. I'm using python 2.6.smth and matplolib 0.99 A: I'm just guessing here, but the correct MIME type is application/pdf, and on that comment line you don't include the necessary extra newline in the print statement.
python and matplotlib server side to generate .pdf documents
i would like to write a server side python script that generate .pdf documents. for the moment i have Python 2.7 installed server side and matplolib installed server side too. A simple script that create a simple plot and generate a .png picture works. this is the script i use : # to access standard output : import sys # select a non-GUI backend : import matplotlib matplotlib.use('Agg') #matplotlib.use("cairo.pdf") #matplotlib.use('PDF') # import plotting module : import matplotlib.pyplot as plt # generate the plot : plt.plot([1,2,3,2,3,4]) # print the content type (what's the data type) # the new line is embedded, using '\n' notation : print "Content-Type: image/png\n" # print "Content-Type: image/PDF\n" # print "Content-type: application/pdf" # output directly to webserver, as a png file: plt.savefig(sys.stdout, format='png') # plt.savefig(sys.stdout, format='PDF') # plt.savefig( "test.pdf", format='pdf' ) I am wondering how to do the same thing but with sending a pdf file instead of a png picture. (the # or bold character are for all the things i tried and put in comment) Does someone know ? thanks. jean-claude
[ "First of all, in your code you send to stdout both the words from the print statement and the figure itself. \nI've just tried your script, changing the comments like this\n# plt.savefig(sys.stdout, format='png')\n# plt.savefig(sys.stdout, format='PDF')\nplt.savefig( \"test.pdf\", format='pdf' ) \n\nand it works ...
[ 4, 2 ]
[]
[]
[ "cgi", "matplotlib", "python" ]
stackoverflow_0003842633_cgi_matplotlib_python.txt
Q: Is it possible to solve this problem with Regular Expression? I'm trying to divide long text in small parts, so that every part is at least N characters and ended with some of the stop punctuation marks (? . !). If the part is bigger than N characters we sttoped when the next punctuation mark appear. For example : Lets say N = 10 Do you want lime? Yes. I love when I drink tequila. This sentence should be divided in two parts. [1] Do you want lime? [2] Yes. I love when I drink tequila. A: Maybe like this? (Thanks to KennyTM for final optimizations.) .{10}[^.?!]*[.?!]+ A: .{10,}?[.!?]+\s* should work. It will also keep repeated punctuation characters together, so it splits Do you want lime??? Yes. I love when I drink tequila. into Do you want lime??? and Yes. I love when I drink tequila. However, it doesn't take quoted speech into account and will break Peter said "Hi! How about dinner tonight?" and left. into Peter said "Hi!, How about dinner tonight? and " and left. Could that be a problem that needs to be taken into account?
Is it possible to solve this problem with Regular Expression?
I'm trying to divide long text in small parts, so that every part is at least N characters and ended with some of the stop punctuation marks (? . !). If the part is bigger than N characters we sttoped when the next punctuation mark appear. For example : Lets say N = 10 Do you want lime? Yes. I love when I drink tequila. This sentence should be divided in two parts. [1] Do you want lime? [2] Yes. I love when I drink tequila.
[ "Maybe like this? (Thanks to KennyTM for final optimizations.)\n.{10}[^.?!]*[.?!]+\n\n", ".{10,}?[.!?]+\\s*\n\nshould work. It will also keep repeated punctuation characters together, so it splits Do you want lime??? Yes. I love when I drink tequila. into Do you want lime??? and Yes. I love when I drink tequila.\...
[ 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003845284_python_regex.txt
Q: Django: request.GET and KeyError Code: # it's an ajax request, so parameters are passed via GET method def my_view(request): my_param = request.GET['param'] // should I check for KeyError exception? In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not. But in Django unexisted parameter results in 500 error page and it seems desired behaviour. So is it ok to leave code as is or there is a better practic? Should I always use standard params passing like /myaction/paramvalue/ instead of /myaction?param_name=param_value (it's kinda hard to build such URLs for ajax requests)? A: Your server should never produce a 500 error page. You can avoid the error by using: my_param = request.GET.get('param', default_value) or: my_param = request.GET.get('param') if my_param is None: return HttpResponseBadRequest() A: Yes, you should check for KeyError in that case. Or you could do this: if 'param' in request.GET: my_param = request.GET['param'] else: my_param = default_value A: How about passing default value if param doesn't exist ? my_param = request.GET.get('param', 'defaultvalue')
Django: request.GET and KeyError
Code: # it's an ajax request, so parameters are passed via GET method def my_view(request): my_param = request.GET['param'] // should I check for KeyError exception? In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not. But in Django unexisted parameter results in 500 error page and it seems desired behaviour. So is it ok to leave code as is or there is a better practic? Should I always use standard params passing like /myaction/paramvalue/ instead of /myaction?param_name=param_value (it's kinda hard to build such URLs for ajax requests)?
[ "Your server should never produce a 500 error page.\nYou can avoid the error by using:\nmy_param = request.GET.get('param', default_value)\n\nor:\nmy_param = request.GET.get('param')\nif my_param is None:\n return HttpResponseBadRequest()\n\n", "Yes, you should check for KeyError in that case. Or you could do...
[ 59, 9, 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003845582_django_django_urls_python.txt
Q: How can I check if a key exists in a dictionary? Let's say I have an associative array like so: {'key1': 22, 'key2': 42}. How can I check if key1 exists in the dictionary? A: if key in array: # do something Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation. A: If you want to retrieve the key's value if it exists, you can also use try: value = a[key] except KeyError: # Key is not present pass If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value). A: Another method is has_key() (if still using Python 2.X): >>> a={"1":"one","2":"two"} >>> a.has_key("1") True
How can I check if a key exists in a dictionary?
Let's say I have an associative array like so: {'key1': 22, 'key2': 42}. How can I check if key1 exists in the dictionary?
[ "if key in array:\n # do something\n\nAssociative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.\n", "If you want to retrieve the key's value if it exists, you can also use\ntry:\n value = a[key]\nexcept KeyError:\n # Key is not present\n pass\n...
[ 699, 64, 62 ]
[]
[]
[ "python" ]
stackoverflow_0003845362_python.txt
Q: Precompose Unicode Character Sequences in Python How can I convert decomposed unicode character sequences like "LATIN SMALL LETTER E" + "COMBINING ACUTE ACCENT" (or U+0075 + U+0301) so they become the precomposed form: "LATIN SMALL LETTER E WITH ACUTE" (or U+00E9) using native Python 2.5+ functions? If it matters, I am on Mac OS X (10.6.4) and I have seen the question Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC but unfortunately while the described OS X native CoreFoundation function CFStringNormalize does not fail or halt the script execution it just doesn't do anything. And by that I don't mean that it doesn't return anything (its return type is void - it mutates in place). I have also tried all possible values for the constant parameter that specifies precomposing or decomposing in either canonical or non-canonical forms. That is why I am searching for a Python native method of handling this case. Thank you very much for reading! André A: import unicodedata as ud astr=u"\N{LATIN SMALL LETTER E}" + u"\N{COMBINING ACUTE ACCENT}" combined_astr=ud.normalize('NFC',astr) 'NFC' tells ud.normalize to apply the canonical decomposition ('NFD'), then compose pre-combined characters: print(ud.name(combined_astr)) # LATIN SMALL LETTER E WITH ACUTE They both print the same: print(astr) # é print(combined_astr) # é But their reprs are different: print(repr(astr)) # u'e\u0301' print(repr(combined_astr)) # u'\xe9' And their encodings, in say utf_8, are (not surprisingly) different too: print(repr(astr.encode('utf_8'))) # 'e\xcc\x81' print(repr(combined_astr.encode('utf_8'))) # '\xc3\xa9'
Precompose Unicode Character Sequences in Python
How can I convert decomposed unicode character sequences like "LATIN SMALL LETTER E" + "COMBINING ACUTE ACCENT" (or U+0075 + U+0301) so they become the precomposed form: "LATIN SMALL LETTER E WITH ACUTE" (or U+00E9) using native Python 2.5+ functions? If it matters, I am on Mac OS X (10.6.4) and I have seen the question Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC but unfortunately while the described OS X native CoreFoundation function CFStringNormalize does not fail or halt the script execution it just doesn't do anything. And by that I don't mean that it doesn't return anything (its return type is void - it mutates in place). I have also tried all possible values for the constant parameter that specifies precomposing or decomposing in either canonical or non-canonical forms. That is why I am searching for a Python native method of handling this case. Thank you very much for reading! André
[ "import unicodedata as ud\n\nastr=u\"\\N{LATIN SMALL LETTER E}\" + u\"\\N{COMBINING ACUTE ACCENT}\"\ncombined_astr=ud.normalize('NFC',astr)\n\n'NFC' tells ud.normalize to apply the canonical decomposition ('NFD'), then\ncompose pre-combined characters:\nprint(ud.name(combined_astr))\n# LATIN SMALL LETTER E WITH ACU...
[ 10 ]
[]
[]
[ "macos", "python", "unicode" ]
stackoverflow_0003845793_macos_python_unicode.txt
Q: AttributeError - Django, GAE This is my code for views.py def addCategory(request): user = users.get_current_user() if users.is_current_user_admin(): if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): cd = form.cleaned_data Category.objects.create_category(cd['name']) return HttpResponseRedirect('/admin/dashboard/') else: form = CategoryForm() temdict = {'form': form, 'title': 'New Category'} return render_to_response('new_category.html', temdict) else: return render_to_response('not_admin.html', {'admin': 'no'}) and this is my model models.py class Category(db.Model): catid = db.IntegerProperty(required=True) name = db.StringProperty(required=True) def get_absolute_url(self): return "/tag/%s/" % str(self.catid) class Meta: verbose_name = 'Category' When I'm running the code it shows: Exception Type: AttributeError Exception Value: type object 'Category' has no attribute '_meta' Exception Location: D:\shwetanka\projects\shwetanka\django\forms\models.py in fields_for_model, line 166 Python Executable: C:\Python26\pythonw.exe Please help me out.I'm using django with gae. This is forms.py class CategoryForm(forms.ModelForm): name = forms.CharField(label='Category', widget=forms.TextInput(attrs={'size':50})) class Meta: model = Category fields = ['name'] Here is the complete stack trace. http://dpaste.com/251985/ A: Django does not support GAE currently. You have to use patched Django, for example, http://www.allbuttonspressed.com/projects/djangoappengine and then rewrite your model using standard django db model (currently you are using GAE one). However djangoappengine does not provide 100% compatibility.
AttributeError - Django, GAE
This is my code for views.py def addCategory(request): user = users.get_current_user() if users.is_current_user_admin(): if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): cd = form.cleaned_data Category.objects.create_category(cd['name']) return HttpResponseRedirect('/admin/dashboard/') else: form = CategoryForm() temdict = {'form': form, 'title': 'New Category'} return render_to_response('new_category.html', temdict) else: return render_to_response('not_admin.html', {'admin': 'no'}) and this is my model models.py class Category(db.Model): catid = db.IntegerProperty(required=True) name = db.StringProperty(required=True) def get_absolute_url(self): return "/tag/%s/" % str(self.catid) class Meta: verbose_name = 'Category' When I'm running the code it shows: Exception Type: AttributeError Exception Value: type object 'Category' has no attribute '_meta' Exception Location: D:\shwetanka\projects\shwetanka\django\forms\models.py in fields_for_model, line 166 Python Executable: C:\Python26\pythonw.exe Please help me out.I'm using django with gae. This is forms.py class CategoryForm(forms.ModelForm): name = forms.CharField(label='Category', widget=forms.TextInput(attrs={'size':50})) class Meta: model = Category fields = ['name'] Here is the complete stack trace. http://dpaste.com/251985/
[ "Django does not support GAE currently. You have to use patched Django, for example, http://www.allbuttonspressed.com/projects/djangoappengine and then rewrite your model using standard django db model (currently you are using GAE one). However djangoappengine does not provide 100% compatibility.\n" ]
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003845272_django_google_app_engine_python.txt
Q: C++ vs Python precision Trying out a problem of finding the first k digits of a num^num I wrote the same program in C++ and Python C++ long double intpart,num,f_digit,k; cin>>num>>k; f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1); cout<<f_digit; Python (a,b) = modf(num*log10(num)) f_digits = pow(10,b+k-1) print f_digits Input 19423474 9 Output C++ > 163074912 Python > 163074908 I checked the results the C++ solution is the accurate one. Checked it at http://www.wolframalpha.com/input/?i=19423474^19423474 Any idea how can I get the same precision in Python ??? EDIT : I know about the external library packages to obtain this precision but any NATIVE solution ??? A: Decimal is a built in python class that handles floating points correctly (as base 10, not as IEEE 7somethingsomething standard). I don't know if it supports logarithms and all that though. Edit: It does indeed support logarithms "and all that". You can set the precision of it as well. Default is 28 places, but it can be as large as you want. Think of it as a BigInt for decimals. A: Python floats are doubles under the hood, as you discovered. You will have to resort to C code, or an external library, to get better floating-point precision. The GMP library is a good one, and it has a python wrapper called 'GMPY', available on PyPI A: In general, I would do it this way. However, it doesn't seem to perform anywhere near fast enough for your example numbers. num = 453 k = 9 result = num ** num print str(result)[:k] # Prints: '163111849'
C++ vs Python precision
Trying out a problem of finding the first k digits of a num^num I wrote the same program in C++ and Python C++ long double intpart,num,f_digit,k; cin>>num>>k; f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1); cout<<f_digit; Python (a,b) = modf(num*log10(num)) f_digits = pow(10,b+k-1) print f_digits Input 19423474 9 Output C++ > 163074912 Python > 163074908 I checked the results the C++ solution is the accurate one. Checked it at http://www.wolframalpha.com/input/?i=19423474^19423474 Any idea how can I get the same precision in Python ??? EDIT : I know about the external library packages to obtain this precision but any NATIVE solution ???
[ "Decimal is a built in python class that handles floating points correctly (as base 10, not as IEEE 7somethingsomething standard). I don't know if it supports logarithms and all that though.\nEdit: It does indeed support logarithms \"and all that\".\nYou can set the precision of it as well. Default is 28 places, bu...
[ 11, 2, 0 ]
[]
[]
[ "c++", "floating_accuracy", "floating_point", "precision", "python" ]
stackoverflow_0003846631_c++_floating_accuracy_floating_point_precision_python.txt
Q: Print variable in python without space or newline print a variable without newline or space python3 does it by print (x,end='') how to do it in python 2.5 A: sys.stdout.write writes (only) strings without newlines unless specified. >>> x = 4 >>> print x 4 >>> import sys >>> sys.stdout.write(str(x)) # you have to str() your variables 4>>> # <- no newline A: Easy: print x, Note comma at the end.
Print variable in python without space or newline
print a variable without newline or space python3 does it by print (x,end='') how to do it in python 2.5
[ "sys.stdout.write writes (only) strings without newlines unless specified.\n>>> x = 4\n>>> print x\n4\n>>> import sys\n>>> sys.stdout.write(str(x)) # you have to str() your variables\n4>>> # <- no newline\n\n", "Easy:\nprint x,\n\nNote comma at the end.\n" ]
[ 11, 0 ]
[]
[]
[ "formatting", "printing", "python", "python_2.5", "python_2.x" ]
stackoverflow_0003846801_formatting_printing_python_python_2.5_python_2.x.txt
Q: Why does importing a dotted module name fail when upper level is matched by a module in current directory? I was trying out one of the Python standard library modules, let's call it foo.bar.baz. So I wrote a little script starting with import foo.bar.baz and saved it as foo.py. When I executed the script I got an ImportError. It took me a while (I'm still learning Python), but I finally realized the problem was how I named the script. Once I renamed foo.py to something else, the problem went away. So I understand that the import foo statement will look for the script foo.py before looking for the standard library foo, but it's not clear to me what it was looking for when I said import foo.bar.baz. Is there some way that foo.py could have the content for that statement to make sense? And if not, why didn't the Python interpreter move on to look for a directory hierarchy like foo/bar with the appropriate __init__.py's?. A: An import statement like import foo.bar.baz first imports foo, then asks it for bar, and then asks foo.bar for baz. Whether foo will, once imported, be able to satisfy the request for bar or bar.baz is unimportant to the import of foo. It's just a module. There is only one foo module. Both import foo and import foo.bar.baz will find the same module -- just like any other way of importing the foo module. There is actually a way for foo to be a single module, rather than a package, and still be able to satisfy a statement like import foo.bar.baz: it can add "foo.bar" and "foo.bar.baz" to the sys.modules dict. This is exactly what the os module does with os.path: it imports the right "path" module for the platform (posixpath, ntpath, os2path, etc), and assigns it to the path attribute. Then it does sys.modules["os.path"] = path to make that module importable as os.path, so a statement like import os.path works. There isn't really a reason to do this -- os.path is available without importing it as well -- but it's possible.
Why does importing a dotted module name fail when upper level is matched by a module in current directory?
I was trying out one of the Python standard library modules, let's call it foo.bar.baz. So I wrote a little script starting with import foo.bar.baz and saved it as foo.py. When I executed the script I got an ImportError. It took me a while (I'm still learning Python), but I finally realized the problem was how I named the script. Once I renamed foo.py to something else, the problem went away. So I understand that the import foo statement will look for the script foo.py before looking for the standard library foo, but it's not clear to me what it was looking for when I said import foo.bar.baz. Is there some way that foo.py could have the content for that statement to make sense? And if not, why didn't the Python interpreter move on to look for a directory hierarchy like foo/bar with the appropriate __init__.py's?.
[ "An import statement like import foo.bar.baz first imports foo, then asks it for bar, and then asks foo.bar for baz. Whether foo will, once imported, be able to satisfy the request for bar or bar.baz is unimportant to the import of foo. It's just a module. There is only one foo module. Both import foo and import fo...
[ 6 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003846821_import_python.txt
Q: parse html beautiful soup I have a html page <a email="corporate@max.ru" href="http://www.max.ru/agent?message&to=corporate@max.ru" title="Click herе" class="mf_spIco spr-mrim-9"></a><a class="mf_t11" type="booster" href="http://max.ru/mail/corporate/"> I neeed a parse email string soup = BeautifulSoup(data string = soup.find("a",{"email": ""}) print string But it not working. Where mistake? A: Your mistake was in using the attrs dict to look for elements with an email attribute that is empty. Try this instead. #!/usr/bin/env python from BeautifulSoup import BeautifulSoup import urllib2 req = urllib2.urlopen('http://worldnuclearwar.ru') soup = BeautifulSoup(req) print soup.find("a", email=True)["email"] To print the email attribute of the first a element which has an email attribute. If you want all emails, try for link in soup.findAll("a", email=True): print link["email"]
parse html beautiful soup
I have a html page <a email="corporate@max.ru" href="http://www.max.ru/agent?message&to=corporate@max.ru" title="Click herе" class="mf_spIco spr-mrim-9"></a><a class="mf_t11" type="booster" href="http://max.ru/mail/corporate/"> I neeed a parse email string soup = BeautifulSoup(data string = soup.find("a",{"email": ""}) print string But it not working. Where mistake?
[ "Your mistake was in using the attrs dict to look for elements with an email attribute that is empty. Try this instead.\n#!/usr/bin/env python\n\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2\n\nreq = urllib2.urlopen('http://worldnuclearwar.ru')\n\nsoup = BeautifulSoup(req)\nprint soup.find(\"a\", email=T...
[ 4 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0003847020_beautifulsoup_python_regex.txt
Q: handling manual user creation with get_current_user() (GAE) I am using GAE's Python environment and Janrain in order to provide multiple ways to login in my service. Based on login information I receive from Janrain, I create a google.appengine.api.User object and store it to the datastore. Is there a way to handle this new object with the built-in get_current_user()? I need to be able to determine whether the requester is logged in or not and who the user is. A: No, you cannot use your custom user objects with the native GAE Users API. You could use a sessions library to track whether or not the request is coming from a logged in user (and who that user is). I recommend gae-sessions. The source includes a demo which shows how to integrate the sessions library with Janrain/RPX. Disclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read this article.
handling manual user creation with get_current_user() (GAE)
I am using GAE's Python environment and Janrain in order to provide multiple ways to login in my service. Based on login information I receive from Janrain, I create a google.appengine.api.User object and store it to the datastore. Is there a way to handle this new object with the built-in get_current_user()? I need to be able to determine whether the requester is logged in or not and who the user is.
[ "No, you cannot use your custom user objects with the native GAE Users API.\nYou could use a sessions library to track whether or not the request is coming from a logged in user (and who that user is). I recommend gae-sessions. The source includes a demo which shows how to integrate the sessions library with Janr...
[ 2 ]
[]
[]
[ "authentication", "google_app_engine", "python" ]
stackoverflow_0003846900_authentication_google_app_engine_python.txt
Q: Multithread DNS Query against specific DNS, domain and recordtype supporting Library Resolved, used adns with python bindings... I have a scenario in which i have to do the following: Load a domain Load what record type is to be queried Load list of DNS Perform query, fetch results and display them. I have tried this but its not multi threaded and even a single query takes about 3 seconds. I looked at ADNS, its python binding and http://www.catonmat.net/blog/asynchronous-dns-resolution , its much much faster than any other way but i still haven't found a way with ADNS Python bindings to query a specific DNS server instead of the ones used in resolv.conf. What do you think? Is there a solution? Or should i launched each ADNS query in a chrooted environment with resolv.conf created the fly? Oh and i would prefer it to be PHP/Python to easily include it in an appiication. A: If you do go with PHP for the client side and feed it with domains to query, you should consider stream_select for working with many streams (each one a dns query) in a non-blocking way. Wez Furlong explains it well.
Multithread DNS Query against specific DNS, domain and recordtype supporting Library
Resolved, used adns with python bindings... I have a scenario in which i have to do the following: Load a domain Load what record type is to be queried Load list of DNS Perform query, fetch results and display them. I have tried this but its not multi threaded and even a single query takes about 3 seconds. I looked at ADNS, its python binding and http://www.catonmat.net/blog/asynchronous-dns-resolution , its much much faster than any other way but i still haven't found a way with ADNS Python bindings to query a specific DNS server instead of the ones used in resolv.conf. What do you think? Is there a solution? Or should i launched each ADNS query in a chrooted environment with resolv.conf created the fly? Oh and i would prefer it to be PHP/Python to easily include it in an appiication.
[ "If you do go with PHP for the client side and feed it with domains to query, you should consider stream_select for working with many streams (each one a dns query) in a non-blocking way. Wez Furlong explains it well.\n" ]
[ 1 ]
[]
[]
[ "dns", "multithreading", "php", "python" ]
stackoverflow_0003846266_dns_multithreading_php_python.txt
Q: Routes/Pylons Fails Before Touching My Code I am very puzzled over this error. In a previously functional Pylons app (running on apache/mod_wsgi), Routes has exploded. When I attempt to access my application, no matter what URL I use, I get the Apache "Internal server error" page and the following traceback in /var/log/apache2/error.log. [Sat Oct 02 2010] WSGI Variables [Sat Oct 02 2010] -------------- [Sat Oct 02 2010] application: <beaker.middleware.SessionMiddleware object at 0xb885be6c> [Sat Oct 02 2010] beaker.get_session: <bound method SessionMiddleware._get_session of <beaker.middleware.SessionMiddleware object at 0xb885be6c>> [Sat Oct 02 2010] beaker.session: {'_accessed_time': 1286040208.138742, '_creation_time': 1286040208.138742} [Sat Oct 02 2010] mod_wsgi.application_group: '192.168.1.51|' [Sat Oct 02 2010] mod_wsgi.callable_object: 'application' [Sat Oct 02 2010] mod_wsgi.handler_script: '' [Sat Oct 02 2010] mod_wsgi.input_chunked: '0' [Sat Oct 02 2010] mod_wsgi.listener_host: '' [Sat Oct 02 2010] mod_wsgi.listener_port: '80' [Sat Oct 02 2010] mod_wsgi.process_group: '' [Sat Oct 02 2010] mod_wsgi.request_handler: 'wsgi-script' [Sat Oct 02 2010] mod_wsgi.script_reloading: '1' [Sat Oct 02 2010] mod_wsgi.version: (3, 3) [Sat Oct 02 2010] paste.registry: <paste.registry.Registry object at 0xb7e373ac> [Sat Oct 02 2010] paste.throw_errors: True [Sat Oct 02 2010] wsgi process: 'Multi process AND threads (?)' [Sat Oct 02 2010] wsgi.file_wrapper: <built-in method file_wrapper of mod_wsgi.Adapter object at 0xb70c77b8> [Sat Oct 02 2010] wsgi.version: (1, 1) [Sat Oct 02 2010] [client 192.168.1.50] ------------------------------------------------------------ [Sat Oct 02 2010] mod_wsgi (pid=13389): Exception occurred processing WSGI script '/var/pylons/myapp/myapp.wsgi'. [Sat Oct 02 2010] Traceback (most recent call last): [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Paste-1.7.4-py2.7.egg/paste/cascade.py", line 130, in __call__ [Sat Oct 02 2010] return self.apps[-1](environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Paste-1.7.4-py2.7.egg/paste/registry.py", line 375, in __call__ [Sat Oct 02 2010] app_iter = self.application(environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Pylons-1.0-py2.7.egg/pylons/middleware.py", line 163, in __call__ [Sat Oct 02 2010] self.app, new_environ, catch_exc_info=True) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Pylons-1.0-py2.7.egg/pylons/util.py", line 48, in call_wsgi_application [Sat Oct 02 2010] app_iter = application(environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/WebError-0.10.2-py2.7.egg/weberror/errormiddleware.py", line 156, in __call__ [Sat Oct 02 2010] return self.application(environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Beaker-1.5.4-py2.7.egg/beaker/middleware.py", line 152, in __call__ [Sat Oct 02 2010] return self.wrap_app(environ, session_start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/middleware.py", line 84, in __call__ [Sat Oct 02 2010] results = self.mapper.routematch(environ=environ) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 690, in routematch [Sat Oct 02 2010] result = self._match(url, environ) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 609, in _match [Sat Oct 02 2010] self.create_regs() [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 560, in create_regs [Sat Oct 02 2010] self._create_regs(*args, **kwargs) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 578, in _create_regs [Sat Oct 02 2010] route.makeregexp(clist) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/route.py", line 306, in makeregexp [Sat Oct 02 2010] self.regmatch = re.compile(reg) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/re.py", line 190, in compile [Sat Oct 02 2010] return _compile(pattern, flags) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/re.py", line 243, in _compile [Sat Oct 02 2010] p = sre_compile.compile(pattern, flags) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_compile.py", line 500, in compile [Sat Oct 02 2010] p = sre_parse.parse(p, flags) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 673, in parse [Sat Oct 02 2010] p = _parse_sub(source, pattern, 0) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 308, in _parse_sub [Sat Oct 02 2010] itemsappend(_parse(source, state)) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 544, in _parse [Sat Oct 02 2010] if not isname(name): [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 218, in isname [Sat Oct 02 2010] if not isident(name[0]): [Sat Oct 02 2010] IndexError: string index out of range This has me very confused because it appears that Routes falls over and dies before it ever touches my code! The only thing it touches is my myapp.wsgi file; neither myapp.wsgi nor my development.ini files have changed between the last working state of the app and now, only model/controller/template files. I have not updated any packages between the last working state of the app and now. The files that I have changed in my app are controller, model, and template files - none of which appear in the traceback. I thought that I might have changed routing.py without remembering it, and the traceback leads to the regular expression processing modules, so I went into routing.py and commented out all lines that use Routes' requirements feature - no change, same error. Retried with lots of apache2ctl restart - no change, same error. What in blue blazes is going on here, and what in my app might have caused it? Solution: The culprit was an innocent-looking route - map.redirect('/foo/*', '/', _redirect_code='301 Moved Permanently'). It looks like that bare asterisk made Routes throw a wobbly. I corrected it by making the match route into '/foo/{bar}' and then dropping the value of bar on the floor. I'm still puzzled about why Routes suffered a meltdown over that instead of being able to throw something like a SyntaxError, but hey, it works now. A: I'd look in your app's config/routing.py file, and add some debugging steps there, or try editing or removing some of the map.connect(...) calls. If you comment out each controller's mapping one at a time, you might be able to narrow down one controller's mapping that is causing this.
Routes/Pylons Fails Before Touching My Code
I am very puzzled over this error. In a previously functional Pylons app (running on apache/mod_wsgi), Routes has exploded. When I attempt to access my application, no matter what URL I use, I get the Apache "Internal server error" page and the following traceback in /var/log/apache2/error.log. [Sat Oct 02 2010] WSGI Variables [Sat Oct 02 2010] -------------- [Sat Oct 02 2010] application: <beaker.middleware.SessionMiddleware object at 0xb885be6c> [Sat Oct 02 2010] beaker.get_session: <bound method SessionMiddleware._get_session of <beaker.middleware.SessionMiddleware object at 0xb885be6c>> [Sat Oct 02 2010] beaker.session: {'_accessed_time': 1286040208.138742, '_creation_time': 1286040208.138742} [Sat Oct 02 2010] mod_wsgi.application_group: '192.168.1.51|' [Sat Oct 02 2010] mod_wsgi.callable_object: 'application' [Sat Oct 02 2010] mod_wsgi.handler_script: '' [Sat Oct 02 2010] mod_wsgi.input_chunked: '0' [Sat Oct 02 2010] mod_wsgi.listener_host: '' [Sat Oct 02 2010] mod_wsgi.listener_port: '80' [Sat Oct 02 2010] mod_wsgi.process_group: '' [Sat Oct 02 2010] mod_wsgi.request_handler: 'wsgi-script' [Sat Oct 02 2010] mod_wsgi.script_reloading: '1' [Sat Oct 02 2010] mod_wsgi.version: (3, 3) [Sat Oct 02 2010] paste.registry: <paste.registry.Registry object at 0xb7e373ac> [Sat Oct 02 2010] paste.throw_errors: True [Sat Oct 02 2010] wsgi process: 'Multi process AND threads (?)' [Sat Oct 02 2010] wsgi.file_wrapper: <built-in method file_wrapper of mod_wsgi.Adapter object at 0xb70c77b8> [Sat Oct 02 2010] wsgi.version: (1, 1) [Sat Oct 02 2010] [client 192.168.1.50] ------------------------------------------------------------ [Sat Oct 02 2010] mod_wsgi (pid=13389): Exception occurred processing WSGI script '/var/pylons/myapp/myapp.wsgi'. [Sat Oct 02 2010] Traceback (most recent call last): [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Paste-1.7.4-py2.7.egg/paste/cascade.py", line 130, in __call__ [Sat Oct 02 2010] return self.apps[-1](environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Paste-1.7.4-py2.7.egg/paste/registry.py", line 375, in __call__ [Sat Oct 02 2010] app_iter = self.application(environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Pylons-1.0-py2.7.egg/pylons/middleware.py", line 163, in __call__ [Sat Oct 02 2010] self.app, new_environ, catch_exc_info=True) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Pylons-1.0-py2.7.egg/pylons/util.py", line 48, in call_wsgi_application [Sat Oct 02 2010] app_iter = application(environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/WebError-0.10.2-py2.7.egg/weberror/errormiddleware.py", line 156, in __call__ [Sat Oct 02 2010] return self.application(environ, start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Beaker-1.5.4-py2.7.egg/beaker/middleware.py", line 152, in __call__ [Sat Oct 02 2010] return self.wrap_app(environ, session_start_response) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/middleware.py", line 84, in __call__ [Sat Oct 02 2010] results = self.mapper.routematch(environ=environ) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 690, in routematch [Sat Oct 02 2010] result = self._match(url, environ) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 609, in _match [Sat Oct 02 2010] self.create_regs() [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 560, in create_regs [Sat Oct 02 2010] self._create_regs(*args, **kwargs) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/mapper.py", line 578, in _create_regs [Sat Oct 02 2010] route.makeregexp(clist) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/site-packages/Routes-1.12.3-py2.7.egg/routes/route.py", line 306, in makeregexp [Sat Oct 02 2010] self.regmatch = re.compile(reg) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/re.py", line 190, in compile [Sat Oct 02 2010] return _compile(pattern, flags) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/re.py", line 243, in _compile [Sat Oct 02 2010] p = sre_compile.compile(pattern, flags) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_compile.py", line 500, in compile [Sat Oct 02 2010] p = sre_parse.parse(p, flags) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 673, in parse [Sat Oct 02 2010] p = _parse_sub(source, pattern, 0) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 308, in _parse_sub [Sat Oct 02 2010] itemsappend(_parse(source, state)) [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 544, in _parse [Sat Oct 02 2010] if not isname(name): [Sat Oct 02 2010] File "/usr/local/lib/python2.7/sre_parse.py", line 218, in isname [Sat Oct 02 2010] if not isident(name[0]): [Sat Oct 02 2010] IndexError: string index out of range This has me very confused because it appears that Routes falls over and dies before it ever touches my code! The only thing it touches is my myapp.wsgi file; neither myapp.wsgi nor my development.ini files have changed between the last working state of the app and now, only model/controller/template files. I have not updated any packages between the last working state of the app and now. The files that I have changed in my app are controller, model, and template files - none of which appear in the traceback. I thought that I might have changed routing.py without remembering it, and the traceback leads to the regular expression processing modules, so I went into routing.py and commented out all lines that use Routes' requirements feature - no change, same error. Retried with lots of apache2ctl restart - no change, same error. What in blue blazes is going on here, and what in my app might have caused it? Solution: The culprit was an innocent-looking route - map.redirect('/foo/*', '/', _redirect_code='301 Moved Permanently'). It looks like that bare asterisk made Routes throw a wobbly. I corrected it by making the match route into '/foo/{bar}' and then dropping the value of bar on the floor. I'm still puzzled about why Routes suffered a meltdown over that instead of being able to throw something like a SyntaxError, but hey, it works now.
[ "I'd look in your app's config/routing.py file, and add some debugging steps there, or try editing or removing some of the map.connect(...) calls. If you comment out each controller's mapping one at a time, you might be able to narrow down one controller's mapping that is causing this.\n" ]
[ 1 ]
[]
[]
[ "mod_wsgi", "pylons", "python", "regex", "routes" ]
stackoverflow_0003846849_mod_wsgi_pylons_python_regex_routes.txt
Q: Image Sent via XML from iPhone to App Engine I am trying to send a small image along with some XML information to App Engine from my iPhone app. I am having trouble with the image somewhere along the path. There is no error given and data is being transfered into a Blob entry in Datastore Viewer but the blob files on App Engine do not appear in Blob Viewer. I have a suspicion that the image is being messed up in one of my transforms in App Engine, or is not being stored as the correct type in App Engine. What do you think? On the iPhone, here is the relevant section that encodes the image (using a standard base64Encoding function) and adds it to a GDataXMLElement, which then gets added to a GDataXMLDoc and sent with ASIHTTPRequest: NSString *dataString = [self.data base64Encoding]; GDataXMLElement *tempXMLElement = [GDataXMLElement elementWithName:@"data" stringValue: dataString]; [imageElement addChild: tempXMLElement]; the ASIHTTPRequest part: ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: url]; [request setDelegate: self]; [request addRequestHeader:@"User-Agent" value: [NSString stringWithFormat:@"MyApp:%@", version]]; [request addRequestHeader:@"Content-Type" value:@"text/xml"]; [request setShouldStreamPostDataFromDisk:YES]; [request appendPostDataFromFile: path]; [request start]; On App Engine in Python (most likely where a problem lies): image_data_xml_element = image_xml_node.getElementsByTagName("data")[0] image_data_base64_unicode = image_data_xml_element.firstChild.data image_data_base64_ascii = image_data_unicode.encode("utf8") image_data_string = binascii.a2b_base64(image_data_base64_ascii) new_image.data = db.Blob(image_data_string) Additionally I have tried: image_data_xml_element = image_xml_node.getElementsByTagName("data")[0] image_data_base64_unicode = image_data_xml_element.firstChild.data image_data_string = base64.b64decode(image_data_base64_unicode) new_image.data = db.Blob(image_data_string) Edit: For completeness, here is the objective-c base64 library I am using - it doesn't look like what I expected: static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - (NSString *)base64Encoding;{ if ([self length] == 0) return @""; char *characters = malloc((([self length] + 2) / 3) * 4); if (characters == NULL) return nil; NSUInteger length = 0; NSUInteger i = 0; while (i < [self length]){ char buffer[3] = {0,0,0}; short bufferLength = 0; while (bufferLength < 3 && i < [self length]) buffer[bufferLength++] = ((char *)[self bytes])[i++]; // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary. characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2]; characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)]; if (bufferLength > 1) characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)]; else characters[length++] = '='; if (bufferLength > 2) characters[length++] = encodingTable[buffer[2] & 0x3F]; else characters[length++] = '='; } return [[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES] autorelease]; } A: The Blob Viewer displays files uploaded with the Blobstore API, not those added to regular datastore entities in Blob Properties. A: What I ended up doing was sending the image to the Blobstore prior to sending the XML then, if successful, send the XML including a key to the blobstore image data. I did not realize initially that Blobstore was a different entity than Blobs stored in the Datastore. Thanks
Image Sent via XML from iPhone to App Engine
I am trying to send a small image along with some XML information to App Engine from my iPhone app. I am having trouble with the image somewhere along the path. There is no error given and data is being transfered into a Blob entry in Datastore Viewer but the blob files on App Engine do not appear in Blob Viewer. I have a suspicion that the image is being messed up in one of my transforms in App Engine, or is not being stored as the correct type in App Engine. What do you think? On the iPhone, here is the relevant section that encodes the image (using a standard base64Encoding function) and adds it to a GDataXMLElement, which then gets added to a GDataXMLDoc and sent with ASIHTTPRequest: NSString *dataString = [self.data base64Encoding]; GDataXMLElement *tempXMLElement = [GDataXMLElement elementWithName:@"data" stringValue: dataString]; [imageElement addChild: tempXMLElement]; the ASIHTTPRequest part: ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: url]; [request setDelegate: self]; [request addRequestHeader:@"User-Agent" value: [NSString stringWithFormat:@"MyApp:%@", version]]; [request addRequestHeader:@"Content-Type" value:@"text/xml"]; [request setShouldStreamPostDataFromDisk:YES]; [request appendPostDataFromFile: path]; [request start]; On App Engine in Python (most likely where a problem lies): image_data_xml_element = image_xml_node.getElementsByTagName("data")[0] image_data_base64_unicode = image_data_xml_element.firstChild.data image_data_base64_ascii = image_data_unicode.encode("utf8") image_data_string = binascii.a2b_base64(image_data_base64_ascii) new_image.data = db.Blob(image_data_string) Additionally I have tried: image_data_xml_element = image_xml_node.getElementsByTagName("data")[0] image_data_base64_unicode = image_data_xml_element.firstChild.data image_data_string = base64.b64decode(image_data_base64_unicode) new_image.data = db.Blob(image_data_string) Edit: For completeness, here is the objective-c base64 library I am using - it doesn't look like what I expected: static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - (NSString *)base64Encoding;{ if ([self length] == 0) return @""; char *characters = malloc((([self length] + 2) / 3) * 4); if (characters == NULL) return nil; NSUInteger length = 0; NSUInteger i = 0; while (i < [self length]){ char buffer[3] = {0,0,0}; short bufferLength = 0; while (bufferLength < 3 && i < [self length]) buffer[bufferLength++] = ((char *)[self bytes])[i++]; // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary. characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2]; characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)]; if (bufferLength > 1) characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)]; else characters[length++] = '='; if (bufferLength > 2) characters[length++] = encodingTable[buffer[2] & 0x3F]; else characters[length++] = '='; } return [[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES] autorelease]; }
[ "The Blob Viewer displays files uploaded with the Blobstore API, not those added to regular datastore entities in Blob Properties.\n", "What I ended up doing was sending the image to the Blobstore prior to sending the XML then, if successful, send the XML including a key to the blobstore image data. I did not re...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "iphone", "objective_c", "python", "xml" ]
stackoverflow_0003692697_google_app_engine_iphone_objective_c_python_xml.txt
Q: Customize HTML Output of Django ModelForm I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML. class LeagueForm(ModelForm): league = forms.ModelChoiceField(queryset=League.objects.all(), empty_label='Manual Team Entry:', required=False) class Meta: model = League exclude = ['league_name'] Template: {% if selected_sport == 1 %} <td>{{ nhl_form.as_p }}</td> {% else %} The problem is I dont want the paragraph tags, nor tables tags or anything at all. I need to have the form nicely sit where I place it without garbling up the surrounding html. Can anyone please point me in the right direction? Thanks A: Just refer to each field separately. {{ nhl_form.league }} will only show the league field, with no surrounding cruft. A: see also http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets
Customize HTML Output of Django ModelForm
I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML. class LeagueForm(ModelForm): league = forms.ModelChoiceField(queryset=League.objects.all(), empty_label='Manual Team Entry:', required=False) class Meta: model = League exclude = ['league_name'] Template: {% if selected_sport == 1 %} <td>{{ nhl_form.as_p }}</td> {% else %} The problem is I dont want the paragraph tags, nor tables tags or anything at all. I need to have the form nicely sit where I place it without garbling up the surrounding html. Can anyone please point me in the right direction? Thanks
[ "Just refer to each field separately.\n{{ nhl_form.league }}\n\nwill only show the league field, with no surrounding cruft.\n", "see also http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets \n" ]
[ 16, 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0001717715_django_django_forms_django_templates_python.txt
Q: alphabetically sorted if statement not working The if statement below has a problem in it somewhere and I can not figure it out. Any conventions or method misuses that might be causing it to not function right? checkList is a user inputed sentence and lis is a large list of words. def realCheck(checkList): string = "".join(checkList) print string wordList = string.split() if match(wordList, lis).sort(key=str.lower) == wordList.sort(key=str.lower): return True else: return False A: If checkList is a string, then there is no need for "".join(checkList). It just gives you back the same string: In [94]: checkList="This is a sentence" In [95]: "".join(checkList) Out[95]: 'This is a sentence' The first line, string = "".join(checkList) has the wrong indentation. Move it back to be flush with the other lines in the definition. Don't name a variable string. It overrides the standard Python module of the same name. Presumably match(wordList, lis) returns a list. The sort method sorts the list, and returns None. Since None == None is True, if match(wordList, lis).sort(key=str.lower) == wordList.sort(key=str.lower): is always true. More likely, what you want is sorted(astr.lower() for astr in match(wordList, lis))==sorted(astr.lower() for astr in wordList) Unlike the sort method, the sorted function returns the sorted list. As Alex Martelli points out, sorted(match(wordList, lis),key=str.lower)==sorted(wordList,key=str.lower) always has the same truth value as sorted(match(wordList, lis))==sorted(wordList) So using str.lower as the key for sorting (rather than as a transformation before comparing with ==) is probably not what you want. The statement if condition: return True else: return False can be simplified to return condition A: .sort, like just about every other mutator method of containers, returns None. So comparing a.sort() to b.sort() is absurd because they'll both be None! I think you want to compare sorted(match(wordList, lis), key=str.lower) with sorted(worldList, key=str.lower). Note that the key is actually irrelevant the way you're using it: if the two lists have items that differ in case, they will not compare equal even if they're sorted "comparably"! So a better idea might be to compare sorted(s.lower() for s in match(wordList, lis)) with sorted(s.lower() for s in worList). Note that the key= is unneeded here since you're comparing the lowercased items so they'll sort that way "by nature".
alphabetically sorted if statement not working
The if statement below has a problem in it somewhere and I can not figure it out. Any conventions or method misuses that might be causing it to not function right? checkList is a user inputed sentence and lis is a large list of words. def realCheck(checkList): string = "".join(checkList) print string wordList = string.split() if match(wordList, lis).sort(key=str.lower) == wordList.sort(key=str.lower): return True else: return False
[ "\nIf checkList is a string, then there\nis no need for \"\".join(checkList).\nIt just gives you back the same\nstring:\nIn [94]: checkList=\"This is a sentence\" \nIn [95]: \"\".join(checkList)\nOut[95]: 'This is a sentence'\n\nThe first line, string =\n\"\".join(checkList) has the wrong\nindentation. Move it b...
[ 5, 4 ]
[]
[]
[ "mutators", "python" ]
stackoverflow_0003847934_mutators_python.txt
Q: Import statement with Django I'm having an issue with a failing import statement, it is called by a manage.py command. It works in the manage.py shell. It also recently worked, i've tried to retrace my steps to no avail. Any advice? A: Your question does not have enough information to answer definitively, but I can at least offer some hints to debug the problem. Understand the import statement Read and understand the documentation for the import statement for your version of Python.. Check the Python path One key step towards debugging any import problem is to ensure that your module is available on the python path. Add the following code to the code that's having the problem: import sys print "\n".join( sys.path ) Somewhere in that list must be the directory tree that contains your module. If it's not there, you'll either have to reference your module differently, or add the right directory to the python path. Keep in mind that Python is a dynamic language -- the python path can be changed as a program runs, and what matters is the state of the python path at the time of them first import of a module. Remember to add an __init__.py file to your packages It must be present, even if empty. Search StackOverflow before asking a question A simple search for [python] import or [django] import may turn up a similar question, with answers that fit your situation.
Import statement with Django
I'm having an issue with a failing import statement, it is called by a manage.py command. It works in the manage.py shell. It also recently worked, i've tried to retrace my steps to no avail. Any advice?
[ "Your question does not have enough information to answer definitively, but I can at least offer some hints to debug the problem.\nUnderstand the import statement\nRead and understand the documentation for the import statement for your version of Python..\nCheck the Python path\nOne key step towards debugging any i...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003843285_django_python.txt
Q: Getting current class in method call class A: def x ( self ): print( self.__class__ ) class B ( A ): pass b = B() b.x() In the above situation, is there any way for the method x to get a reference to class A instead of B? Of course simply writing print( A ) is not allowed, as I want to add some functionality with a decorator that needs the class A (and as I can't pass A itself to the decorator directly, as the class doesn't exist yet at that point). A: Unless you have super-calls involved (or more generally subclasses that override x and call directly to A.x(self) as part of their override's implementation), looking for the first item in type(self).mro() that has an x attribute would work -- next(c for c in type(self).mro() if hasattr(c, 'x')) If you do need to cover for super-calls, it's harder -- unless you happen to know that no super-class of A defines an x attribute (and of course it's easier to know about your superclasses than your subclasses, though multiple inheritance does complicate it;-) in which case you only need the last appropriate item of the mro instead of the first one. A: You can use name mangling to associate the class a method is defined in with a method: def set_defining_class(cls): setattr(cls, '_%s__defining_class' % (cls.__name__,), cls) return cls @set_defining_class class A(object): def x (self): print(self.__defining_class) @set_defining_class class B ( A ): pass b = B() b.x() Done here with a class decorator, but you could do it by hand, or in a metaclass too.
Getting current class in method call
class A: def x ( self ): print( self.__class__ ) class B ( A ): pass b = B() b.x() In the above situation, is there any way for the method x to get a reference to class A instead of B? Of course simply writing print( A ) is not allowed, as I want to add some functionality with a decorator that needs the class A (and as I can't pass A itself to the decorator directly, as the class doesn't exist yet at that point).
[ "Unless you have super-calls involved (or more generally subclasses that override x and call directly to A.x(self) as part of their override's implementation), looking for the first item in type(self).mro() that has an x attribute would work --\nnext(c for c in type(self).mro() if hasattr(c, 'x'))\n\nIf you do need...
[ 4, 2 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003848033_inheritance_python.txt
Q: Calling variable superclass method I'm trying to call a method of the superclass by using a variable method name. Normally, I would see the following two lines of code as equivalent: someObj.method() someObj.__getattribute__( 'method' )() And in fact I believe, this is also what actually happens when I use the first line. However, in the following example, the second line produces a weird problem. I use super to construct a super object and call the method of the super class. Doing it directly works as expected, but using __getattribute__ to get the method first, results in a indefinite loop which calls the method of the subclass again and again. See the following code: class A: def example ( self ): print( 'example in A' ) class B ( A ): def example ( self ): print( super( B, self ).example ) print( super( B, self ).__getattribute__( 'example' ) ) super( B, self ).example() #super( B, self ).__getattribute__( 'example' )() print( 'example in B' ) x = B() x.example() If you run that code, everything works as expected, and you should get an output similar to this: <bound method B.example of <__main__.B object at 0x01CF6C90>> <bound method B.example of <__main__.B object at 0x01CF6C90>> example in A example in B So both methods, the one with the direct access and the one via __getattribute__, look identical. If you however replace the method call by the commented-out line, you'll end up with a recursion runtime error. Why does this happen, and more importantly, how can I actually access the method in the same way as python internally does, when I use the working line? edit When I thought I already tried everything, I found this to be working: super.__getattribute__( super( B, self ), 'example' )() It actually equals to super( B, self ).example. A: Don't use __getattribute__ for this: it does not do what you think it does. (It is a specialized part of Python's machinery, mainly for use if you're implementing new attribute access magic.) For normal attribute access, use the getattr / setattr / delattr builtins: self.example == getattr(self, 'example') super(B, self).example == getattr(super(B, self), 'example') (If you want to understand what __getattribute__ does, read the Descriptor HowTo Guide and Python Data model reference.) A: Getting the example attribute of a B object results in a bound copy of B.example. Calling this will result in a recursion error. That you call A.__getattribute__() is irrelevant; you still have a B object.
Calling variable superclass method
I'm trying to call a method of the superclass by using a variable method name. Normally, I would see the following two lines of code as equivalent: someObj.method() someObj.__getattribute__( 'method' )() And in fact I believe, this is also what actually happens when I use the first line. However, in the following example, the second line produces a weird problem. I use super to construct a super object and call the method of the super class. Doing it directly works as expected, but using __getattribute__ to get the method first, results in a indefinite loop which calls the method of the subclass again and again. See the following code: class A: def example ( self ): print( 'example in A' ) class B ( A ): def example ( self ): print( super( B, self ).example ) print( super( B, self ).__getattribute__( 'example' ) ) super( B, self ).example() #super( B, self ).__getattribute__( 'example' )() print( 'example in B' ) x = B() x.example() If you run that code, everything works as expected, and you should get an output similar to this: <bound method B.example of <__main__.B object at 0x01CF6C90>> <bound method B.example of <__main__.B object at 0x01CF6C90>> example in A example in B So both methods, the one with the direct access and the one via __getattribute__, look identical. If you however replace the method call by the commented-out line, you'll end up with a recursion runtime error. Why does this happen, and more importantly, how can I actually access the method in the same way as python internally does, when I use the working line? edit When I thought I already tried everything, I found this to be working: super.__getattribute__( super( B, self ), 'example' )() It actually equals to super( B, self ).example.
[ "Don't use __getattribute__ for this: it does not do what you think it does. (It is a specialized part of Python's machinery, mainly for use if you're implementing new attribute access magic.)\nFor normal attribute access, use the getattr / setattr / delattr builtins:\nself.example == getattr(self, 'examp...
[ 5, 0 ]
[]
[]
[ "python", "super", "superclass" ]
stackoverflow_0003847919_python_super_superclass.txt
Q: Stdout captured from pipe in Python is truncated I want to capture the ouput of dpkg --list | grep linux-image in Python 2.6.5 on Ubuntu 10.04. from subprocess import Popen from subprocess import PIPE p1 = Popen(["dpkg", "--list"], stdout=PIPE) p2 = Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=PIPE) stdout = p2.communicate()[0] The content of stdout is: >>> print stdout rc linux-image-2. 2.6.31-14.48 Linux kernel image for version 2.6.31 on x86 ii linux-image-2. 2.6.32-22.36 Linux kernel image for version 2.6.32 on x86 ii linux-image-2. 2.6.32-23.37 Linux kernel image for version 2.6.32 on x86 ii linux-image-2. 2.6.32-24.43 Linux kernel image for version 2.6.32 on x86 ii linux-image-2. 2.6.32-25.44 Linux kernel image for version 2.6.32 on x86 ii linux-image-ge 2.6.32.25.27 Generic Linux kernel image However, this is not the same as running dpkg --list | grep linux-image in a shell: cschol@blabla:~$ dpkg --list | grep linux-image rc linux-image-2.6.31-14-generic 2.6.31-14.48 Linux kernel image for version 2.6.31 on x86 ii linux-image-2.6.32-22-generic 2.6.32-22.36 Linux kernel image for version 2.6.32 on x86 ii linux-image-2.6.32-23-generic 2.6.32-23.37 Linux kernel image for version 2.6.32 on x86 ii linux-image-2.6.32-24-generic 2.6.32-24.43 Linux kernel image for version 2.6.32 on x86 ii linux-image-2.6.32-25-generic 2.6.32-25.44 Linux kernel image for version 2.6.32 on x86 ii linux-image-generic 2.6.32.25.27 Generic Linux kernel image Looking at the first line, one can see that the output in Python is truncated: rc linux-image-2. 2.6.31-14.48 instead of rc linux-image-2.6.31-14-generic 2.6.31-14.48 Why does it do that and is there a way to get exactly the same output in Python? A: import subprocess p1 = subprocess.Popen(["dpkg", "--list"], stdout=subprocess.PIPE, env={'LANG':'C'}) p2 = subprocess.Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=subprocess.PIPE) out,err=p2.communicate() print(out) The dpkg command's output depends on the value of the LANG environment variable. Setting LANG=C in subprocess.Popen will make dpkg's output more like what you see from the terminal. A: There is no need to use grep ! import subprocess p1 = subprocess.Popen(["dpkg", "--list"], stdout=subprocess.PIPE, env={'LANG':'C'}) out,err=p1.communicate() for o in out.split("\n"): if "linux-image" in o: print o
Stdout captured from pipe in Python is truncated
I want to capture the ouput of dpkg --list | grep linux-image in Python 2.6.5 on Ubuntu 10.04. from subprocess import Popen from subprocess import PIPE p1 = Popen(["dpkg", "--list"], stdout=PIPE) p2 = Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=PIPE) stdout = p2.communicate()[0] The content of stdout is: >>> print stdout rc linux-image-2. 2.6.31-14.48 Linux kernel image for version 2.6.31 on x86 ii linux-image-2. 2.6.32-22.36 Linux kernel image for version 2.6.32 on x86 ii linux-image-2. 2.6.32-23.37 Linux kernel image for version 2.6.32 on x86 ii linux-image-2. 2.6.32-24.43 Linux kernel image for version 2.6.32 on x86 ii linux-image-2. 2.6.32-25.44 Linux kernel image for version 2.6.32 on x86 ii linux-image-ge 2.6.32.25.27 Generic Linux kernel image However, this is not the same as running dpkg --list | grep linux-image in a shell: cschol@blabla:~$ dpkg --list | grep linux-image rc linux-image-2.6.31-14-generic 2.6.31-14.48 Linux kernel image for version 2.6.31 on x86 ii linux-image-2.6.32-22-generic 2.6.32-22.36 Linux kernel image for version 2.6.32 on x86 ii linux-image-2.6.32-23-generic 2.6.32-23.37 Linux kernel image for version 2.6.32 on x86 ii linux-image-2.6.32-24-generic 2.6.32-24.43 Linux kernel image for version 2.6.32 on x86 ii linux-image-2.6.32-25-generic 2.6.32-25.44 Linux kernel image for version 2.6.32 on x86 ii linux-image-generic 2.6.32.25.27 Generic Linux kernel image Looking at the first line, one can see that the output in Python is truncated: rc linux-image-2. 2.6.31-14.48 instead of rc linux-image-2.6.31-14-generic 2.6.31-14.48 Why does it do that and is there a way to get exactly the same output in Python?
[ "import subprocess\np1 = subprocess.Popen([\"dpkg\", \"--list\"], stdout=subprocess.PIPE, env={'LANG':'C'})\np2 = subprocess.Popen([\"grep\", \"linux-image\"], stdin=p1.stdout, stdout=subprocess.PIPE)\nout,err=p2.communicate()\nprint(out)\n\nThe dpkg command's output depends on the value of the LANG environment var...
[ 4, 4 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0003848269_pipe_python_subprocess.txt
Q: Handling frame resize in matplotlib animation with WXAgg backend I am doing some animated plotting and using the the matplotlib examples as a guideline. matplotlib examples With the following linked example from that page the animation has some obvious problems when the frame is resized. What is the correct or best way to deal with this? animation_blit_wx.py Thanks A: Take a look at the animation_blit_qt4.py example. You have to check the figure size manually, and if it has changed you need to draw the background again. Heres the part which does that from the qt example, self is a Figure Canvas: current_size = self.ax.bbox.width, self.ax.bbox.height if self.old_size != current_size: self.old_size = current_size self.ax.clear() self.ax.grid() self.draw() self.ax_background = self.copy_from_bbox(self.ax.bbox)
Handling frame resize in matplotlib animation with WXAgg backend
I am doing some animated plotting and using the the matplotlib examples as a guideline. matplotlib examples With the following linked example from that page the animation has some obvious problems when the frame is resized. What is the correct or best way to deal with this? animation_blit_wx.py Thanks
[ "Take a look at the animation_blit_qt4.py example.\nYou have to check the figure size manually, and if it has changed you need to draw the background again. \nHeres the part which does that from the qt example, self is a Figure Canvas:\n current_size = self.ax.bbox.width, self.ax.bbox.height\n if self.old_size !...
[ 1 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0003835109_matplotlib_python_wxpython.txt
Q: Communication from arduino to a browser extension all run locally I am trying to figure out how I would go about taking serial information from an Arduino which controls a Javascript browser extension I have running in an open browser locally on a computer. It would seem that I would need some sort of middleman to internalize the serial readings and pass them to the browser (to activate the functions I have coded). Python? Any answers, help, and reference is greatly appreciated. A: Another option is to use a browser plug-in to access the serial port from javascript: http://code.google.com/p/seriality/ A: A very simple http server in python would look like this from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200, 'OK') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write( "hello" ) HTTPServer(('', 8888), MyServer).serve_forever() in the do_Get method you can add the code necessary to access your arduino program ... ser = serial.Serial('/dev/tty.usbserial', 9600) ser.write('5') ser.readline() ... another option would be coding this in ruby by using webrick as the webserver part require "serialport.so" require 'webrick'; SERIALPORT="/dev/ttyUSB0" s = HTTPServer.new( :Port => 2000 ) class DemoServlet < HTTPServlet::AbstractServlet def getValue() begin sp = SerialPort.new( SERIALPORT, 9600, 8, 1, SerialPort::NONE) sp.read_timeout = 500 sp.write( "... whatever you like to send to your arduino" ) body = sp.readline() sp.close return body rescue puts "cant open serial port" end end def do_GET( req, res ) body = "--.--" body = getValue() res.body = body res['Content-Type'] = "text/plain" end end s.mount( "/test", DemoServlet ) trap("INT"){ s.shutdown } s.start a third option would be using an ethernet-shield on the arduino and skipping the proxy code completely
Communication from arduino to a browser extension all run locally
I am trying to figure out how I would go about taking serial information from an Arduino which controls a Javascript browser extension I have running in an open browser locally on a computer. It would seem that I would need some sort of middleman to internalize the serial readings and pass them to the browser (to activate the functions I have coded). Python? Any answers, help, and reference is greatly appreciated.
[ "Another option is to use a browser plug-in to access the serial port from javascript: http://code.google.com/p/seriality/\n", "A very simple http server in python would look like this\nfrom BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer\n\nclass MyServer(BaseHTTPRequestHandler):\n def do_GET(self):\n...
[ 2, 0 ]
[]
[]
[ "browser", "communication", "python", "serial_port" ]
stackoverflow_0003338323_browser_communication_python_serial_port.txt
Q: Python equivalent of ActionScript 3's restParam In ActionScript 3 (Flash's programming language, very similar to Java - to the point that it's disturbing), if I was defining a function and wanted it to be called with endless parameters, I could do this (restParam, I thought it was called): function annihilateUnicorns(...unicorns):String { for(var i:int = 0; i<unicorns.length; i++) { unicorns[i].splode(); } return "404 Unicorns not found. They sploded."; } (then you could call it with this:) annihilateUnicorns(new Unicorn(), new Unicorn(), new Unicorn(), new Unicorn()); What's cool is that all of those extra parameters are stored in an array. How would I do that in python? This obviously doesn't work: def annihilateUnicorns (...unicorns): for i in unicorns : i.splode() return "404 Unicorns not found. They sploded." Thanks! :D A: def annihilateUnicorns(*unicorns): for i in unicorns: # stored in a list i.splode() return "404 Unicorns not found. They sploded."
Python equivalent of ActionScript 3's restParam
In ActionScript 3 (Flash's programming language, very similar to Java - to the point that it's disturbing), if I was defining a function and wanted it to be called with endless parameters, I could do this (restParam, I thought it was called): function annihilateUnicorns(...unicorns):String { for(var i:int = 0; i<unicorns.length; i++) { unicorns[i].splode(); } return "404 Unicorns not found. They sploded."; } (then you could call it with this:) annihilateUnicorns(new Unicorn(), new Unicorn(), new Unicorn(), new Unicorn()); What's cool is that all of those extra parameters are stored in an array. How would I do that in python? This obviously doesn't work: def annihilateUnicorns (...unicorns): for i in unicorns : i.splode() return "404 Unicorns not found. They sploded." Thanks! :D
[ "def annihilateUnicorns(*unicorns):\n for i in unicorns: # stored in a list\n i.splode()\n return \"404 Unicorns not found. They sploded.\"\n\n" ]
[ 4 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003848454_function_python.txt
Q: Copy strings from multiple lineEdit slots as variable to one textEdit slot in PyQt4 To be more crystal clear, here how the things might work. In python, to create a variable, simply we use var1 = raw_input('your name?') So that when using print 'your name is ' +var1 It will print the string stored in var1. The question is how to make that using Pyqt4? I have 3 lineEdit symbolize as name, age and gender and one textEdit to print strings from lineEdit into this textEdit. it's just like making a phonebook. is it possible? how the code will look like? i'm eagerly to know the answer.. Here i provide some source to make things clearer. This is the ui: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'phonebook.ui' # # Created: Sat Oct 2 15:18:52 2010 # by: PyQt4 UI code generator 4.7.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_phonebook(object): def setupUi(self, phonebook): phonebook.setObjectName("phonebook") phonebook.resize(240, 300) phonebook.setMinimumSize(QtCore.QSize(240, 300)) phonebook.setMaximumSize(QtCore.QSize(240, 300)) self.label = QtGui.QLabel(phonebook) self.label.setGeometry(QtCore.QRect(20, 30, 57, 14)) self.label.setObjectName("label") self.label_2 = QtGui.QLabel(phonebook) self.label_2.setGeometry(QtCore.QRect(20, 60, 57, 14)) self.label_2.setObjectName("label_2") self.lineEdit = QtGui.QLineEdit(phonebook) self.lineEdit.setGeometry(QtCore.QRect(110, 30, 113, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtGui.QLineEdit(phonebook) self.lineEdit_2.setGeometry(QtCore.QRect(110, 60, 113, 20)) self.lineEdit_2.setObjectName("lineEdit_2") self.textEdit = QtGui.QTextEdit(phonebook) self.textEdit.setGeometry(QtCore.QRect(20, 142, 201, 141)) self.textEdit.setObjectName("textEdit") self.pushButton = QtGui.QPushButton(phonebook) self.pushButton.setGeometry(QtCore.QRect(70, 100, 89, 23)) self.pushButton.setObjectName("pushButton") self.retranslateUi(phonebook) QtCore.QMetaObject.connectSlotsByName(phonebook) def retranslateUi(self, phonebook): phonebook.setWindowTitle(QtGui.QApplication.translate("phonebook", "Simple Phonebook", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("phonebook", "Name:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("phonebook", "E-mail:", None, QtGui.QApplication.UnicodeUTF8)) self.lineEdit.setText(QtGui.QApplication.translate("phonebook", "lineEdit", None, QtGui.QApplication.UnicodeUTF8)) self.lineEdit_2.setText(QtGui.QApplication.translate("phonebook", "lineEdit_2", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("phonebook", "Preview", None, QtGui.QApplication.UnicodeUTF8)) This is main source: #! /usr/bin/env python import sys from PyQt4 import QtCore, QtGui from phonebook import Ui_phonebook class Main(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_phonebook() self.ui.setupUi(self) self.center() QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.preview) def preview(self): lineEdit = '"content inside lineEdit"' lineEdit_2 = '"content inside lineEdit_2"' self.ui.textEdit.setText('Name: ' +lineEdit +'\n\nEmail: ' +lineEdit_2) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) main = Main() main.show() sys.exit(app.exec_()) A: When a push-button is clicked in Qt (and PyQt) it emits a signal. You can connect this signal to any slot (in PyQt that would be any Python method) and do whatever you wish in that slot - like look at text from 3 boxes and print something. For example suppose you have a button you created with: self.start_button = QPushButton("&Start") Connect its clicked signal: self.connect(self.start_button, SIGNAL('clicked()'), self.on_start) to the on_start method of your class. In this method, invoke the relevant methods of other widgets to do whatever you wish. A: i have solved this mysteries.. well, all i have to insert is text()!! def preview(self): lineEdit = self.ui.lineEdit.text() lineEdit_2 = self.ui.lineEdit_2.text() self.ui.textEdit.setText('Name: ' +lineEdit +'\n\nEmail: ' +lineEdit_2) yes.. that should make my dreams come true.. thanks to all who put an efford to help me.. =^_^=
Copy strings from multiple lineEdit slots as variable to one textEdit slot in PyQt4
To be more crystal clear, here how the things might work. In python, to create a variable, simply we use var1 = raw_input('your name?') So that when using print 'your name is ' +var1 It will print the string stored in var1. The question is how to make that using Pyqt4? I have 3 lineEdit symbolize as name, age and gender and one textEdit to print strings from lineEdit into this textEdit. it's just like making a phonebook. is it possible? how the code will look like? i'm eagerly to know the answer.. Here i provide some source to make things clearer. This is the ui: # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'phonebook.ui' # # Created: Sat Oct 2 15:18:52 2010 # by: PyQt4 UI code generator 4.7.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_phonebook(object): def setupUi(self, phonebook): phonebook.setObjectName("phonebook") phonebook.resize(240, 300) phonebook.setMinimumSize(QtCore.QSize(240, 300)) phonebook.setMaximumSize(QtCore.QSize(240, 300)) self.label = QtGui.QLabel(phonebook) self.label.setGeometry(QtCore.QRect(20, 30, 57, 14)) self.label.setObjectName("label") self.label_2 = QtGui.QLabel(phonebook) self.label_2.setGeometry(QtCore.QRect(20, 60, 57, 14)) self.label_2.setObjectName("label_2") self.lineEdit = QtGui.QLineEdit(phonebook) self.lineEdit.setGeometry(QtCore.QRect(110, 30, 113, 20)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtGui.QLineEdit(phonebook) self.lineEdit_2.setGeometry(QtCore.QRect(110, 60, 113, 20)) self.lineEdit_2.setObjectName("lineEdit_2") self.textEdit = QtGui.QTextEdit(phonebook) self.textEdit.setGeometry(QtCore.QRect(20, 142, 201, 141)) self.textEdit.setObjectName("textEdit") self.pushButton = QtGui.QPushButton(phonebook) self.pushButton.setGeometry(QtCore.QRect(70, 100, 89, 23)) self.pushButton.setObjectName("pushButton") self.retranslateUi(phonebook) QtCore.QMetaObject.connectSlotsByName(phonebook) def retranslateUi(self, phonebook): phonebook.setWindowTitle(QtGui.QApplication.translate("phonebook", "Simple Phonebook", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("phonebook", "Name:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("phonebook", "E-mail:", None, QtGui.QApplication.UnicodeUTF8)) self.lineEdit.setText(QtGui.QApplication.translate("phonebook", "lineEdit", None, QtGui.QApplication.UnicodeUTF8)) self.lineEdit_2.setText(QtGui.QApplication.translate("phonebook", "lineEdit_2", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("phonebook", "Preview", None, QtGui.QApplication.UnicodeUTF8)) This is main source: #! /usr/bin/env python import sys from PyQt4 import QtCore, QtGui from phonebook import Ui_phonebook class Main(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_phonebook() self.ui.setupUi(self) self.center() QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.preview) def preview(self): lineEdit = '"content inside lineEdit"' lineEdit_2 = '"content inside lineEdit_2"' self.ui.textEdit.setText('Name: ' +lineEdit +'\n\nEmail: ' +lineEdit_2) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) main = Main() main.show() sys.exit(app.exec_())
[ "When a push-button is clicked in Qt (and PyQt) it emits a signal. You can connect this signal to any slot (in PyQt that would be any Python method) and do whatever you wish in that slot - like look at text from 3 boxes and print something.\nFor example suppose you have a button you created with:\n self.start_bu...
[ 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003845658_pyqt4_python.txt
Q: django template does not render complete context I am using templates with django. I am having a problem where the Context is not being rendered. The meta_k is null. The meta_description is not. t = get_template('projects.html') html = t.render(Context({ 'completed': completed, 'current':current, 'description': sp.description, 'project_title':sp.name, 'img':images, 'meta_desc': sp.meta_description, 'meta_k:': sp.meta_keywords })) I can start the server in debug mode in eclipse and So I know sp.meta_keywords is not null. Here is where I call the code in projects.html: {% block meta_keywords %}<br> {% if meta_k %}<br> &nbsp;&nbsp;&nbsp;&nbsp;{{ meta_k }}<br> {% else %}<br> &nbsp;&nbsp;&nbsp;&nbsp;Venkat, Rao, engineer, inventor, entrepreneur, projects, blue dart, control systems, labview<br> {% endif %}<br> {% endblock %} This defaults to the else when I know meta_k should not be null. The complete code can be found here on Google Code. What am I doing wrong? A: Only suggestion for you is that most probably it is bug in your code, for us it will be difficult to debug without running your whole project. So i suggest you experiment on command line and see if you can replicate the bug in simple steps, so that we can try to fix it. I am sure in the process you will find the problematic part e.g. I see your template rendered correctly by my simple context >>> from django.template import Context, Template >>> s = """{% block meta_keywords %}<br> ... {% if meta_k %}<br> ... &nbsp;&nbsp;&nbsp;&nbsp;{{ meta_k }}<br> ... {% else %}<br> ... &nbsp;&nbsp;&nbsp;&nbsp;Venkat, Rao, engineer, inventor, entrepreneur, projects, blue dart, control systems, labview<br> ... {% endif %}<br> ... {% endblock %}""" >>> t = Template(s) >>> c = Context({'meta_k':['a','b','c']}) >>> t.render(c) u'<br>\n<br>\n&nbsp;&nbsp;&nbsp;&nbsp;[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]<br>\n<br>\n' A: So I was just making stupid mistake: In the rendering file I have: html = t.render(Context({'completed': completed, 'current':current, 'description': sp.description, 'project_title':sp.name, 'img':images, 'meta_desc': sp.meta_description, 'meta_k:': sp.meta_keywords) this refers to "meta_k:" note the semicolon in the template I have {% if meta_k %} note no semicolon If I remove the semicolon it works. That was stupid.
django template does not render complete context
I am using templates with django. I am having a problem where the Context is not being rendered. The meta_k is null. The meta_description is not. t = get_template('projects.html') html = t.render(Context({ 'completed': completed, 'current':current, 'description': sp.description, 'project_title':sp.name, 'img':images, 'meta_desc': sp.meta_description, 'meta_k:': sp.meta_keywords })) I can start the server in debug mode in eclipse and So I know sp.meta_keywords is not null. Here is where I call the code in projects.html: {% block meta_keywords %}<br> {% if meta_k %}<br> &nbsp;&nbsp;&nbsp;&nbsp;{{ meta_k }}<br> {% else %}<br> &nbsp;&nbsp;&nbsp;&nbsp;Venkat, Rao, engineer, inventor, entrepreneur, projects, blue dart, control systems, labview<br> {% endif %}<br> {% endblock %} This defaults to the else when I know meta_k should not be null. The complete code can be found here on Google Code. What am I doing wrong?
[ "Only suggestion for you is that most probably it is bug in your code, for us it will be difficult to debug without running your whole project.\nSo i suggest you experiment on command line and see if you can replicate the bug in simple steps, so that we can try to fix it. I am sure in the process you will find the ...
[ 3, -1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003848472_django_google_app_engine_python.txt
Q: Confusion about django app's name I learned Django following django book and the document. In the django book exmaple, the project is called mysite and there's an app called book inside this project. So in this case, the app is called "book". I've no problem with it. My confusion arises in front of reusable apps. Reusable apps usually reside outside the project. For example, django-registration only has an independent folder "registration". So what's its app name? "Registration", right? If that's the case, isn't there some inconsistency regarding the app naming? In the first case, app name seems to be a folder name (or sub package name) under the project while in the 2nd case, the app name is the top package name. I know most of you will say "Why are you obssessed with app name? Just make sure the package structure is correct and django can run without problems." Yes, in most case, app name is nothing but a name. Except in one occasion: specify AUTH_PROFILE_MODULE. As the document explains, To indicate that this model is the user profile model for a given site, fill in the setting AUTH_PROFILE_MODULE with a string consisting of the following items, separated by a dot: The name of the application (case sensitive) in which the user profile model is defined (in other words, the name which was passed to manage.py startapp to create the application). The name of the model (not case sensitive) class. If I have a model as a user profile in a resuable package, I have to know the app name to correctly specify AUTH_PROFILE_MODULE. Does django use certain path searching order to decide the app name? A: The name of the app is the name of the directory, capitalization and all, unless you go to the extra work to change the name in the appropriate __init__.py file. Django apps are, after all, just Python modules, and all the same rules apply. If you ever see an app or module name with different capitalization or other modifications, that doesn't reflect the actual app or module name. Instead, what you're seeing is the result of some "pretty-printing" that the Django admin app is known to do in some cases. This is for display only. A: My confusion arises in front of reusable apps. Reusable apps usually reside outside the project. For example, django-registration only has an independent folder "registration". So what's its app name? "Registration", right? django-registration is the project name. The application name is registration: in application list you are using the application name only: registration in other places you will use import registration If that's the case, isn't there some inconsistency regarding the app naming? In the first case, app name seems to be a folder name (or sub package name) under the project while in the 2nd case, the app name is the top package name. Think of the project as a simple collection of applications: you could store the apps as subfolders, or place them in a separate folder (that must be included in PYTHONPATH). In both cases the application name is the same. Update manage.py adds to the PYTHONPATH both the current folder (so you could use import app.module) and the parent folder (so you can use project.settings and project.urls). So, if you can configure Pydev to add the project folder to the PYTHONPATH, then you could import the apps as app.module, independent of the project name. A: When you deploy and app as a standalone package, it is just another Python package, which happens to implement Django views, templates, template tags, etc. Therefore, Django's search path is the Python search path itself. This is why people say "Just make sure the package structure is correct and django can run without problems." Obviously, if the package name conflicts with someone else's package, you are going to get problems... A: An app name is just the name of the Python module. Nothing more. A python module name is the case name of the root folder of the module, that must contains an init.py file. If you want to know what this name is, go to your site-packages folder and look for your module.
Confusion about django app's name
I learned Django following django book and the document. In the django book exmaple, the project is called mysite and there's an app called book inside this project. So in this case, the app is called "book". I've no problem with it. My confusion arises in front of reusable apps. Reusable apps usually reside outside the project. For example, django-registration only has an independent folder "registration". So what's its app name? "Registration", right? If that's the case, isn't there some inconsistency regarding the app naming? In the first case, app name seems to be a folder name (or sub package name) under the project while in the 2nd case, the app name is the top package name. I know most of you will say "Why are you obssessed with app name? Just make sure the package structure is correct and django can run without problems." Yes, in most case, app name is nothing but a name. Except in one occasion: specify AUTH_PROFILE_MODULE. As the document explains, To indicate that this model is the user profile model for a given site, fill in the setting AUTH_PROFILE_MODULE with a string consisting of the following items, separated by a dot: The name of the application (case sensitive) in which the user profile model is defined (in other words, the name which was passed to manage.py startapp to create the application). The name of the model (not case sensitive) class. If I have a model as a user profile in a resuable package, I have to know the app name to correctly specify AUTH_PROFILE_MODULE. Does django use certain path searching order to decide the app name?
[ "The name of the app is the name of the directory, capitalization and all, unless you go to the extra work to change the name in the appropriate __init__.py file. Django apps are, after all, just Python modules, and all the same rules apply.\nIf you ever see an app or module name with different capitalization or ot...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003848490_django_python.txt
Q: Python comparing two lists Hello I wanna compare two lists like this a=[1,2] b=10,20] compare(a,b) will return True if each element in a is > corresponding element in b so compare( [1,2] > [3,4] ) is True compare( [1,20] > [3,4] ) is False hiow to do this the pythonic way Cheers A: Use zip: len(a) == len(b) and all(j > i for i, j in zip(a, b)) A: I'm not exactly sure what you're looking for since the result shown in your example seems to contradict what you said you wanted returned, nor do you specify what is desired if the length of the two lists are unequal or both are empty. For these reasons, my answer explicitly handles most of those conditions so you can easily change it to suit your needs. I've also made the comparison being done a predicate function, so that can be varied as well. Note especially the last three test cases. BTW, @Mike Axiak's answer if very good if all his implicit assumptions were correct. def compare_all(pred, a, b): """return True if pred() is True when applied to each element in 'a' and its corresponding element in 'b'""" def maxlen(a, b): # local function maxlen.value = max(len(a), len(b)) return maxlen.value if maxlen(a, b): # one or both sequences are non-empty for i in range(maxlen.value): try: if not pred(a[i], b[i]): return False except IndexError: # unequal sequence lengths if len(a) > len(b): return False # second sequence is shorter than first else: return True # first sequence is shorter than second else: return True # pred() was True for all elements in both # of the non-empty equal-length sequences else: # both sequences were empty return False print compare_all(lambda x,y: x>y, [1,2], [3,4]) # False print compare_all(lambda x,y: x>y, [3,4], [1,2]) # True print compare_all(lambda x,y: x>y, [3,4], [1,2,3]) # True print compare_all(lambda x,y: x>y, [3,4,5], [1,2]) # False print compare_all(lambda x,y: x>y, [], []) # False
Python comparing two lists
Hello I wanna compare two lists like this a=[1,2] b=10,20] compare(a,b) will return True if each element in a is > corresponding element in b so compare( [1,2] > [3,4] ) is True compare( [1,20] > [3,4] ) is False hiow to do this the pythonic way Cheers
[ "Use zip:\nlen(a) == len(b) and all(j > i for i, j in zip(a, b))\n\n", "I'm not exactly sure what you're looking for since the result shown in your example seems to contradict what you said you wanted returned, nor do you specify what is desired if the length of the two lists are unequal or both are empty. \nFor ...
[ 10, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003848242_python_python_3.x.txt
Q: How to map a list of data to a list of functions? I have the following Python code: data = ['1', '4.6', 'txt'] funcs = [int, float, str] How to call every function with data in corresponding index as an argument to the function? Now I'm using the code: result = [] for i, func in enumerate(funcs): result.append(func(data[i])) map(funcs, data) don't work with lists of functions ( Is there builtin function to do that simpler? A: You could use zip* to combine many sequences together: zip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...] then you could iterate on this new sequence and make each function apply on the corresponding data. Since you just want to collect them into a list, list comprehension is much better than a for-loop: result = [f(x) for f, x in zip(funcs, data)] Note: * Use itertools.izip if you are using Python 2.x and the lists are very long.) A: [f(d) for d,f in zip(data, funcs)] A: >>> data = ['1', '4.6', 'txt'] >>> funcs = [int, float, str] >>> result = [funcs[pos](x) for pos, x in enumerate(data)] >>> result [1, 4.5999999999999996, 'txt'] >>> A: map() will work with sequences of functions, although perhaps not in the way you thought: data = ['1', '4.6', 'txt'] funcs = [int, float, str] result = list(map(lambda f,d: f(d), funcs, data)) # or result = list(map(lambda d,f: f(d), data, funcs)) A: If you need the values one by one, you can also create generator for values: def my_funcvals(funcs,vals): return ("%s(%r) = %r" %(f.__name__,d, f(d)) for d,f in zip(data, funcs)) data = ['1', '4.6', 'txt'] funcs = [int, float, str] for result in my_funcvals(funcs, data): print result
How to map a list of data to a list of functions?
I have the following Python code: data = ['1', '4.6', 'txt'] funcs = [int, float, str] How to call every function with data in corresponding index as an argument to the function? Now I'm using the code: result = [] for i, func in enumerate(funcs): result.append(func(data[i])) map(funcs, data) don't work with lists of functions ( Is there builtin function to do that simpler?
[ "You could use zip* to combine many sequences together:\nzip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...]\n\nthen you could iterate on this new sequence and make each function apply on the corresponding data. Since you just want to collect them into a list, list comprehension is much better than a for-lo...
[ 9, 2, 2, 2, 0 ]
[]
[]
[ "arguments", "function", "list", "mapping", "python" ]
stackoverflow_0003848829_arguments_function_list_mapping_python.txt
Q: Python: a could be rounded to b in the general case As a part of some unit testing code that I'm writing, I wrote the following function. The purpose of which is to determine if 'a' could be rounded to 'b', regardless of how accurate 'a' or 'b' are. def couldRoundTo(a,b): """Can you round a to some number of digits, such that it equals b?""" roundEnd = len(str(b)) if a == b: return True for x in range(0,roundEnd): if round(a,x) == b: return True return False Here's some output from the function: >>> couldRoundTo(3.934567892987, 3.9) True >>> couldRoundTo(3.934567892987, 3.3) False >>> couldRoundTo(3.934567892987, 3.93) True >>> couldRoundTo(3.934567892987, 3.94) False As far as I can tell, it works. However, I'm scared of relying on it considering I don't have a perfect grasp of issues concerning floating point accuracy. Could someone tell me if this is an appropriate way to implement this function? If not, how could I improve it? A: Could someone tell me if this is an appropriate way to implement this function? It depends. The given function will behave surprisingly if b isn't precisely equal to a value that would normally be obtained directly from decimal-to-binary-float conversion. For example: >>> print(0.1, 0.2/2, 0.3/3) 0.1 0.1 0.1 >>> couldRoundTo(0.123, 0.1) True >>> couldRoundTo(0.123, 0.2/2) True >>> couldRoundTo(0.123, 0.3/3) False This fails because the calculation of 0.3 / 3 results in a slightly different representation than 0.1 and 0.2 / 2 (and round(0.123, 1)). If not, how could I improve it? Rule of thumb: if your calculation specifically involves decimal digits in any way, just use Decimal, to avoid all the lossy base-2 round-tripping. In particular, Decimal includes a helper called quantize that makes this problem trivially easy: from decimal import Decimal def roundable(a, b): a = Decimal(str(a)) b = Decimal(str(b)) return a.quantize(b) == b A: One way to do it: def could_round_to(a, b): (x, y) = map(len, str(b).split('.')) round_format = "%" + "%d.%df"%(x, y) return round_format%a == str(b) First, we take the number of digits before and after the decimal in x and y. Then, we construct a format such as %x.yf. Then, we supply a to the format string. >>> "%2.2f"%123.1234 '123.12' >>> "%2.2f"%123.1264 '123.13' >>> "%3.2f"%000.001 '0.00' Now, all that's left is comparing the strings. A: The only point that I'm afraid of is the conversion from strings to floating points when interpreting floating-point literals (as in http://docs.python.org/reference/lexical_analysis.html#floating-point-literals). I don't know if there is any guarantee that a floating-point literal will evaluate to the floating-point number that is closest to the given string. This mentioned section is the place in the specification where I would expect such a guarantee. For example, Java is much more specific about what to expect from a string literal. From the documentation of Double.valueOf(String): [...] [the argument] is regarded as representing an exact decimal value in the usual "computerized scientific notation" or as an exact hexadecimal value; this exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type double by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic [...] Unless you can find such a guarantee anywhere in the Python documentation, you can be just lucky, because some earlier floating-point libraries (on which Python might rely) convert a string just to a floating-point number nearby, not to the best available. Unfortunately, it seems to me that neither round, nor float, nor the specification for floating-point literaly give you any usable guarantee. A: If you purpose is to test if round function will round to the target, then you are correct. Otherwise (what else is the purpose?) if you are in doubt , you should use decimal module
Python: a could be rounded to b in the general case
As a part of some unit testing code that I'm writing, I wrote the following function. The purpose of which is to determine if 'a' could be rounded to 'b', regardless of how accurate 'a' or 'b' are. def couldRoundTo(a,b): """Can you round a to some number of digits, such that it equals b?""" roundEnd = len(str(b)) if a == b: return True for x in range(0,roundEnd): if round(a,x) == b: return True return False Here's some output from the function: >>> couldRoundTo(3.934567892987, 3.9) True >>> couldRoundTo(3.934567892987, 3.3) False >>> couldRoundTo(3.934567892987, 3.93) True >>> couldRoundTo(3.934567892987, 3.94) False As far as I can tell, it works. However, I'm scared of relying on it considering I don't have a perfect grasp of issues concerning floating point accuracy. Could someone tell me if this is an appropriate way to implement this function? If not, how could I improve it?
[ "\nCould someone tell me if this is an appropriate way to implement this function? \n\nIt depends. The given function will behave surprisingly if b isn't precisely equal to a value that would normally be obtained directly from decimal-to-binary-float conversion.\nFor example:\n>>> print(0.1, 0.2/2, 0.3/3)\n0.1 0.1 ...
[ 3, 1, 0, 0 ]
[]
[]
[ "floating_point", "python", "rounding" ]
stackoverflow_0003848865_floating_point_python_rounding.txt
Q: IndentationError: unindent does not match any outer indentation level def LCS(word_list1, word_list2): m = len(word_list1) n = len(word_list2) print m print n C = [[0] * (n+1) for i in range(m+1)] # IndentationError: unindent does not match any outer indentation level print C i=0 j=0 for word in word_list1: j=0 for word in word_list2: if word_list1[i-1] == word_list2[j-1]: C[i][j] = C[i-1][j-1] + 1 else: C[i][j] = max(word_list1(C[i][j-1], C[i-1][j])) j+=1 i+=1 return C A: It's hard to answer a question on why indentation is incorrect when the question keeps being edited and the indentation corrected. However, I suggest you read PEP8 before writing any more Python code and avoid mixing tabs and spaces. This would explain why you still see an IndentationError on line seven after you have corrected the indentation. I also recommend that you try to run your script using the '-tt' command-line option to determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list' option). A: These two lines C = [[0] * (n+1) for i in range(m+1)] # IndentationError: unindent does not match any outer indentation level print C should be indented at the same level. I.e.: C = [[0] * (n+1) for i in range(m+1)] print C Update Op has corrected the above problem. I checked the code and the error is elsewhere now: for word in word_list2: if word_list1[i-1] == word_list2[j-1]: C[i][j] = C[i-1][j-1] + 1 else: C[i][j] = max(word_list1(C[i][j-1], C[i-1][j])) j+=1 Should be: for word in word_list2: # These lines have been indented extra. if word_list1[i-1] == word_list2[j-1]: C[i][j] = C[i-1][j-1] + 1 else: C[i][j] = max(word_list1(C[i][j-1], C[i-1][j])) j+=1 A: I think its due use of mixed indentation - Tabs and Spaces Recommendation: Use 4 spaces per indentation level, Never mix tabs and spaces. Maximum Line Length: 80 Check your Python - Editor's Setting, GEdit: From Tools -> Preferences -> Editor -> Tab Width = 4 and use Spaces instead of Tabs Eclipse: use Pydev - http://pydev.org VIM: use following vim settings - for vim editor :set tabstop=4 expandtab shiftwidth=4 softtabstop=4
IndentationError: unindent does not match any outer indentation level
def LCS(word_list1, word_list2): m = len(word_list1) n = len(word_list2) print m print n C = [[0] * (n+1) for i in range(m+1)] # IndentationError: unindent does not match any outer indentation level print C i=0 j=0 for word in word_list1: j=0 for word in word_list2: if word_list1[i-1] == word_list2[j-1]: C[i][j] = C[i-1][j-1] + 1 else: C[i][j] = max(word_list1(C[i][j-1], C[i-1][j])) j+=1 i+=1 return C
[ "It's hard to answer a question on why indentation is incorrect when the question keeps being edited and the indentation corrected.\nHowever, I suggest you read PEP8 before writing any more Python code and avoid mixing tabs and spaces. This would explain why you still see an IndentationError on line seven after you...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003849021_python.txt
Q: Python: how to use value stored in a variable to decide which class instance to initiate? I'm building a Django site. I need to model many different product categories such as TV, laptops, women's apparel, men's shoes, etc. Since different product categories have different product attributes, each category has its own separate Model: TV, Laptop, WomensApparel, MensShoes, etc. And for each Model I created a ModelForm. Hence I have TVForm, LaptopForm, WomensApparelForm, MensShoesForm, etc. Users can enter product details by selecting a product category through multi-level drop-down boxes. Once a user has selected a product category, I need to display the corresponding product form. The obvious way to do this is to use a giant if-elif structure: # category is the product category selected by the user if category == "TV": form = TVForm() elif category == "Laptop": form = LaptopForm() elif category == "WomensApparel": form = WomensApparelForm() ... Unfortunately there could be hundreds if not more of categories. So the above method is going to be error-prone and tedious. Is there any way I could use the value of the variable category to directly select and initialize the appropriate ModelForm without resorting to a giant if-elif statement? Something like: # This doesn't work model_form_name = category + "Form" form = model_form_name() Is there any way to do this? A: If all your *Form classes are in the one module (let's call it forms), you can do this: import forms form = getattr(forms, category + "Form")() (Obviously, add whatever verification is necessary, such as catching AttributeError. Security-wise, if you are using a named module rather than the global namespace, it's that little bit harder for someone to inject a new *Form class.) A: One simple way to do this is to maintain a dictionary of category names to form classes. For e.g. categories_and_classes = dict(TV = TVForm, Laptop = LaptopForm, ...) And then you can use the category to look up the form class: form = categories_and_classes.get(category, DefaultForm) Alternately you can use convention, as @Zooba said in his answer. This would work if your forms are uniformly named, say <category name> + Form. A: Sounds like what you need is a mapping, or dictionary in Python. For example, create a dictionary that maps model category names to ModelForm classes. You could have another that maps them to Model classes. Either way you can map the string with the Model name in it to whatever you want. A more "object-oriented" approach would be to just use the a Model class dictionary and add (possibly static) method(s) to each one which return or do what you need done, such as return the appropriate ModelForm. I mean something like this: class TV: @staticmethod def getform(): return TVForm ... class Laptop: @staticmethod def getform(): return LaptopForm ... class WomensApparel: ...etc... Models = { 'TV':TV, 'Laptop':Laptop, 'WomensApparel':WomensApparel, ...etc } form = Models[category].getform() With these two techniques, you won't need to write those kinds of giant if-elif structures -- and if you ever start to, it's a sign it's time to re-think your design.
Python: how to use value stored in a variable to decide which class instance to initiate?
I'm building a Django site. I need to model many different product categories such as TV, laptops, women's apparel, men's shoes, etc. Since different product categories have different product attributes, each category has its own separate Model: TV, Laptop, WomensApparel, MensShoes, etc. And for each Model I created a ModelForm. Hence I have TVForm, LaptopForm, WomensApparelForm, MensShoesForm, etc. Users can enter product details by selecting a product category through multi-level drop-down boxes. Once a user has selected a product category, I need to display the corresponding product form. The obvious way to do this is to use a giant if-elif structure: # category is the product category selected by the user if category == "TV": form = TVForm() elif category == "Laptop": form = LaptopForm() elif category == "WomensApparel": form = WomensApparelForm() ... Unfortunately there could be hundreds if not more of categories. So the above method is going to be error-prone and tedious. Is there any way I could use the value of the variable category to directly select and initialize the appropriate ModelForm without resorting to a giant if-elif statement? Something like: # This doesn't work model_form_name = category + "Form" form = model_form_name() Is there any way to do this?
[ "If all your *Form classes are in the one module (let's call it forms), you can do this:\nimport forms\n\nform = getattr(forms, category + \"Form\")()\n\n(Obviously, add whatever verification is necessary, such as catching AttributeError. Security-wise, if you are using a named module rather than the global namespa...
[ 10, 9, 1 ]
[]
[]
[ "django", "django_forms", "django_models", "metaprogramming", "python" ]
stackoverflow_0003849047_django_django_forms_django_models_metaprogramming_python.txt
Q: WSAEventSelect with FD_ACCEPT, recv returns WSAEWOULDBLOCK I'm trying to setup a socket that won't block on accept(...), using the following code: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 1234)) event = win32event.CreateEvent(None, True, False, None) win32file.WSAEventSelect(sock.fileno(), event, win32file.FD_ACCEPT) sock.listen(5) rc = win32event.WaitForSingleObject(event, win32event.INFINITE) if not rc == win32event.WAIT_OBJECT_0: return conn, addr = sock.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() When a client connects but there's no data, recv returns WSAEWOULDBLOCK. Reading MSDN explains this is the right behavior for non-blocking sockets but when using WSAEventSelect I only specified FD_ACCEPT, without FD_READ. Therefore I expect recv to block when there's no data, and to return with 0 when the connection was gracefully closed. What am I doing wrong? A: Solved this by: adding the following lines before accept: win32file.WSAEventSelect(sock.fileno(), event, 0) sock.setblocking(1)
WSAEventSelect with FD_ACCEPT, recv returns WSAEWOULDBLOCK
I'm trying to setup a socket that won't block on accept(...), using the following code: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 1234)) event = win32event.CreateEvent(None, True, False, None) win32file.WSAEventSelect(sock.fileno(), event, win32file.FD_ACCEPT) sock.listen(5) rc = win32event.WaitForSingleObject(event, win32event.INFINITE) if not rc == win32event.WAIT_OBJECT_0: return conn, addr = sock.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() When a client connects but there's no data, recv returns WSAEWOULDBLOCK. Reading MSDN explains this is the right behavior for non-blocking sockets but when using WSAEventSelect I only specified FD_ACCEPT, without FD_READ. Therefore I expect recv to block when there's no data, and to return with 0 when the connection was gracefully closed. What am I doing wrong?
[ "Solved this by: adding the following lines before accept:\nwin32file.WSAEventSelect(sock.fileno(), event, 0)\nsock.setblocking(1)\n\n" ]
[ 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0003849410_python_winapi.txt
Q: Codechef python runtime error I always get a runtime error using python for submission on codechef. Can some one please help. Tried answering other questions too.. same error Works fine on my comp though!(I use python 2.6.5 on my comp. Answer is checked with python 2.5) This is an easy level question where i get Runtime error http://www.codechef.com/problems/FCTRL/ My code import sys def factorial_zeros(f): i=0 j=0 for x in range (1,f+1): if x%10 == 0: while x%10 == 0: x= x//10 i +=1 while x%5 == 0: x= x//5 j +=1 elif x%5 == 0: while x%5 == 0: x= x//5 j +=1 l = i+j return l l=[] i=int(raw_input()) for x in range(i): f = int(raw_input()) f= factorial_zeros(f) if x == i-1: sys.stdout.write(str(f)) else: print f A: I don't compete/submit at Codechef, but AFAIK it uses Python 2.5 rather than 2.6. Perhaps you are using something that is 2.5-specific? (although I can't find anything that is). Edit: It looks to me now that the problem isn't with Python versions at all. Notice in the problem statement that the input value N can be as large as 10^9. Trying the range(1,f+1) with such a large value of f will cause the interpreter to try to build a list with 10^9 elements. This will clearly exceed the memory limits for this problem on the judge machine, thus causing an uncaught exception that shows up as an RTE to you. FWIW, your approach to solving the problem is wrong. even if you replaced range with xrange to avoid memory limits, you will still end up trying 10^9 iterations which will make your solution time out. A: The thing runs OK both under 2.6 and 2.5, and 2.4 for that matter. i, j = 0, 0 is fine since very ancient Python versions, like 1.5. The program even reads input and computes the results correctly, if slowly. Though I'd try sys.stdin.readline().strip() instead of raw_input(). Unless you specify which RuntimeError you're getting, complete with stacktrace preferably, hardly anyone can help you, all telepaths are on vacation.
Codechef python runtime error
I always get a runtime error using python for submission on codechef. Can some one please help. Tried answering other questions too.. same error Works fine on my comp though!(I use python 2.6.5 on my comp. Answer is checked with python 2.5) This is an easy level question where i get Runtime error http://www.codechef.com/problems/FCTRL/ My code import sys def factorial_zeros(f): i=0 j=0 for x in range (1,f+1): if x%10 == 0: while x%10 == 0: x= x//10 i +=1 while x%5 == 0: x= x//5 j +=1 elif x%5 == 0: while x%5 == 0: x= x//5 j +=1 l = i+j return l l=[] i=int(raw_input()) for x in range(i): f = int(raw_input()) f= factorial_zeros(f) if x == i-1: sys.stdout.write(str(f)) else: print f
[ "I don't compete/submit at Codechef, but AFAIK it uses Python 2.5 rather than 2.6. Perhaps you are using something that is 2.5-specific? (although I can't find anything that is). \nEdit:\nIt looks to me now that the problem isn't with Python versions at all. Notice in the problem statement that the input value N ca...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003846971_python.txt
Q: Is Celery appropriate for use with many small, distributed systems? I'm writing some software which will manage a few hundred small systems in “the field” over an intermittent 3G (or similar) connection. Home base will need to send jobs to the systems in the field (eg, “report on your status”, “update your software”, etc), and the systems in the field will need to send jobs back to the server (eg, “a failure has been detected”, “here is some data”, etc). I've spent some time looking at Celery and it seems to be a perfect fit: celeryd running at home base could collect jobs for the systems in the field, a celeryd running on the field systems could collect jobs for the server, and these jobs could be exchanged as clients become available. So, is Celery a good fit for this problem? Specifically: The majority of tasks will be directed to an individual worker (eg, “send the ‘get_status’ job to ‘system51’”) — will this be a problem? Does it gracefully handle adverse network conditions (like, eg, connections dying)? What functionality is only available if RabbitMQ is being used as a backend? (I'd rather not run RabbitMQ on the field systems) Is there any other reason Celery could make my life difficult if I use it like I've described? Thanks! (it would be valid to suggest that Celery is overkill, but there are other reasons that it would make my life easier, so I would like to consider it) A: The majority of tasks will be directed to an individual worker (eg, “send the ‘get_status’ job to ‘system51’”) — will this be a problem? Not at all. Just create a queue for each worker, e.g. say each node listens to a round robin queue called default and each node has its own queue named after its node name: (a)$ celeryd -n a.example.com -Q default,a.example.com (b)$ celeryd -n b.example.com -Q default,b.example.com (c)$ celeryd -n c.example.com -Q default,c.example.com Routing a task directly to a node is simple: $ get_status.apply_async(args, kwargs, queue="a.example.com") or by configuration using a Router: # Always route "app.get_status" to "a.example.com" CELERY_ROUTES = {"app.get_status": {"queue": "a.example.com"}} Does it gracefully handle adverse network conditions (like, eg, connections dying)? The worker gracefully recovers from broker connection failures. (at least from RabbitMQ, I'm not sure about all the other backends, but this is easy to test and fix (you only need to add the related exceptions to a list) For the client you can always retry sending the task if the connection is down, or you can set up HA with RabbitMQ: http://www.rabbitmq.com/pacemaker.html What functionality is only available if RabbitMQ is being used as a backend? (I'd rather not run RabbitMQ on the field systems) Remote control commands, and only "direct" exchanges are supported (not "topic" or "fanout"). But this will be supported in Kombu (http://github.com/ask/kombu). I would seriously reconsider using RabbitMQ. Why do you think it's not a good fit? IMHO I wouldn't look elsewhere for a system like this, (except maybe ZeroMQ if the system is transient and you don't require message persistence). Is there any other reason Celery could make my life difficult if I use it like I've described? I can't think of anything from what you describe above. Since the concurrency model is multiprocessing it does require some memory (I'm working on adding support for thread pools and eventlet pools, which may help in some cases). it would be valid to suggest that Celery is overkill, but there are other reasons that it would make my life easier, so I would like to consider it) In that case I think you use the word overkill lightly. It really depends on how much code and tests you need to write without it. I think it's better to improve an already existing general solution, and in theory it sounds like it should work well for your application. A: I would probably set up a (django) web service to accept requests. The web service could do the job of validating requests and deflecting bad requests. Then celery can just do the work. This would require the remote devices to poll the web service to see if their jobs were done though. That may or may not be appropriate, depending on what exactly you're doing.
Is Celery appropriate for use with many small, distributed systems?
I'm writing some software which will manage a few hundred small systems in “the field” over an intermittent 3G (or similar) connection. Home base will need to send jobs to the systems in the field (eg, “report on your status”, “update your software”, etc), and the systems in the field will need to send jobs back to the server (eg, “a failure has been detected”, “here is some data”, etc). I've spent some time looking at Celery and it seems to be a perfect fit: celeryd running at home base could collect jobs for the systems in the field, a celeryd running on the field systems could collect jobs for the server, and these jobs could be exchanged as clients become available. So, is Celery a good fit for this problem? Specifically: The majority of tasks will be directed to an individual worker (eg, “send the ‘get_status’ job to ‘system51’”) — will this be a problem? Does it gracefully handle adverse network conditions (like, eg, connections dying)? What functionality is only available if RabbitMQ is being used as a backend? (I'd rather not run RabbitMQ on the field systems) Is there any other reason Celery could make my life difficult if I use it like I've described? Thanks! (it would be valid to suggest that Celery is overkill, but there are other reasons that it would make my life easier, so I would like to consider it)
[ "\nThe majority of tasks will be directed\n to an individual worker (eg, “send the\n ‘get_status’ job to ‘system51’”) —\n will this be a problem?\n\nNot at all. Just create a queue for each worker, e.g. say each node listens to a round robin queue called default and each node has its own queue named after its no...
[ 12, 1 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0003848024_celery_python.txt