title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How to install pycairo on osx?
1,500,866
<p>I am trying to install the <a href="http://cairographics.org/pycairo/">pycairo</a> (Python bindings for the <a href="http://cairographics.org/">cairo graphics library</a>) under OSX.</p> <p>I started with</p> <pre><code>easy_install pycairo </code></pre> <p>and got: </p> <pre><code>Requested 'cairo &gt;= 1.8.8' but version of cairo is 1.0.4 error: Setup script exited with Error: cairo &gt;= 1.8.8 not found </code></pre> <p>So I went to cairo's site and downloaded the latest package (1.8.8) of cairo, and also the latest package of something called pixman (both source packages -- couldn't find osx binaries)</p> <p>unzipped both, each in own directory. for pixman, the regular <code>./configure ; make ; sudo make install</code> worked just find for cairo, ./configure seemed to work, but make failed with:</p> <pre><code>In file included from cairo-analysis-surface.c:37: cairoint.h:71:20: error: pixman.h: No such file or directory </code></pre> <p>What am I doing wrong?</p> <p>And why do I have to struggle so much to get a software library to work on an os that "just works"? Why isn't darwin more like linux?</p>
6
2009-09-30T21:53:36Z
1,500,978
<p>Ok. I solved it. Putting solution here for future reference, it might help someone.</p> <p>Basically, the whole ports/fink system is a bit messed up, and osx doesn't really play nice with the linux-y world.</p> <p>So, the steps I needed to install pycairo on OSX were:</p> <ul> <li>download the latest source versions of pixman, cairo, pycairo</li> <li><p>extract everything. Then:</p> <pre><code>cd PIXMAN_DIR ; ./configure ; make ; sudo make install cd CAIRO_DIR ; cp PIXMAN_DIR/pixman/*.h . ; ./configure ; make ; sudo make install cd PYCAYRO_DIR; locate cairo.pc </code></pre> <p>hopefully, several locations are returned. choose the most likely one (one with newest cairo). For me it was "/opt/local/lib/pkgconfig/cairo.pc" and do:</p> <pre><code>export PKG_CONFIG_PATH=/opt/local/lib/pkgconfig/ </code></pre> <p>after this, still in PYCAIRO_DIR, do: </p> <pre><code>python setup.py install </code></pre></li> </ul> <p>This should do it...</p>
6
2009-09-30T22:29:17Z
[ "python", "osx", "installation", "makefile", "cairo" ]
How to install pycairo on osx?
1,500,866
<p>I am trying to install the <a href="http://cairographics.org/pycairo/">pycairo</a> (Python bindings for the <a href="http://cairographics.org/">cairo graphics library</a>) under OSX.</p> <p>I started with</p> <pre><code>easy_install pycairo </code></pre> <p>and got: </p> <pre><code>Requested 'cairo &gt;= 1.8.8' but version of cairo is 1.0.4 error: Setup script exited with Error: cairo &gt;= 1.8.8 not found </code></pre> <p>So I went to cairo's site and downloaded the latest package (1.8.8) of cairo, and also the latest package of something called pixman (both source packages -- couldn't find osx binaries)</p> <p>unzipped both, each in own directory. for pixman, the regular <code>./configure ; make ; sudo make install</code> worked just find for cairo, ./configure seemed to work, but make failed with:</p> <pre><code>In file included from cairo-analysis-surface.c:37: cairoint.h:71:20: error: pixman.h: No such file or directory </code></pre> <p>What am I doing wrong?</p> <p>And why do I have to struggle so much to get a software library to work on an os that "just works"? Why isn't darwin more like linux?</p>
6
2009-09-30T21:53:36Z
1,811,820
<p>The <code>port</code> command installs the library for the darwinports python installation, which is different to the framework build (so steps 2 and 3 shouldn't work). Try <code>sudo easy_install pycairo</code> instead (although your step 4 should be equivalent to this).</p> <p>Look at <code>which python</code> too, to check that you are in fact running the python you think you are.</p>
3
2009-11-28T06:52:25Z
[ "python", "osx", "installation", "makefile", "cairo" ]
How to install pycairo on osx?
1,500,866
<p>I am trying to install the <a href="http://cairographics.org/pycairo/">pycairo</a> (Python bindings for the <a href="http://cairographics.org/">cairo graphics library</a>) under OSX.</p> <p>I started with</p> <pre><code>easy_install pycairo </code></pre> <p>and got: </p> <pre><code>Requested 'cairo &gt;= 1.8.8' but version of cairo is 1.0.4 error: Setup script exited with Error: cairo &gt;= 1.8.8 not found </code></pre> <p>So I went to cairo's site and downloaded the latest package (1.8.8) of cairo, and also the latest package of something called pixman (both source packages -- couldn't find osx binaries)</p> <p>unzipped both, each in own directory. for pixman, the regular <code>./configure ; make ; sudo make install</code> worked just find for cairo, ./configure seemed to work, but make failed with:</p> <pre><code>In file included from cairo-analysis-surface.c:37: cairoint.h:71:20: error: pixman.h: No such file or directory </code></pre> <p>What am I doing wrong?</p> <p>And why do I have to struggle so much to get a software library to work on an os that "just works"? Why isn't darwin more like linux?</p>
6
2009-09-30T21:53:36Z
1,811,869
<p>It appears you are mixing various install options here. The MacPorts package system <code>port install</code> command should automatically pull in all the dependencies needed for a particular package so the trick is to start with the right top-level project. For python packages, MacPorts has a general convention currently: packages that start with <code>py-</code> are for python 2.4, those with <code>py25-</code> are for 2.5, and <code>py26-</code> for 2.6. There are currently <code>py-cairo</code>, <code>py25-cairo</code>, and <code>py26-cairo</code> packages available in MacPorts.</p> <p>By choosing <code>py-cairo</code> you picked the python2.4 version and you'll probably find that MacPorts built and installed a python2.4 for you (linked at <code>/opt/local/bin/python2.4</code>) and, if you launch it, you'll probably find that you can import cairo there. Now that <em>may</em> be OK for your needs but Python 2.4 is quite old and no longer supported so, if you're just starting, it might be better to start with Python 2.6, one of the two current versions of Python. To do so, all you should need to do is:</p> <pre><code>sudo port install py26-cairo </code></pre> <p>That should bring in any missing dependencies, mainly the MacPorts python2.6, which you can run from <code>/opt/local/bin/python2.6</code>. You may want to change your <code>$PATH</code> in your shell startup script, probably .bash_profile, to put <code>/opt/local/bin</code> early on the search path.</p> <p>Because installing Cairo and its python bindings seems to be fairly complex, it should be easier and better to stick to using a complete MacPorts solution for this. That does mean you've needlessly (and harmlessly) installed a couple of Python instances that you won't need. But if you do want to clean things up a bit, you can easily remove the MacPorts python24 with:</p> <pre><code>sudo port uninstall py-cairo python24 </code></pre> <p>Completely removing the python.org installed python is more complicated. I've explained the process <a href="http://bugs.python.org/issue7107">here</a>. But there's no pressing need to remove either as long as you keep your paths straight.</p>
6
2009-11-28T07:26:38Z
[ "python", "osx", "installation", "makefile", "cairo" ]
How to install pycairo on osx?
1,500,866
<p>I am trying to install the <a href="http://cairographics.org/pycairo/">pycairo</a> (Python bindings for the <a href="http://cairographics.org/">cairo graphics library</a>) under OSX.</p> <p>I started with</p> <pre><code>easy_install pycairo </code></pre> <p>and got: </p> <pre><code>Requested 'cairo &gt;= 1.8.8' but version of cairo is 1.0.4 error: Setup script exited with Error: cairo &gt;= 1.8.8 not found </code></pre> <p>So I went to cairo's site and downloaded the latest package (1.8.8) of cairo, and also the latest package of something called pixman (both source packages -- couldn't find osx binaries)</p> <p>unzipped both, each in own directory. for pixman, the regular <code>./configure ; make ; sudo make install</code> worked just find for cairo, ./configure seemed to work, but make failed with:</p> <pre><code>In file included from cairo-analysis-surface.c:37: cairoint.h:71:20: error: pixman.h: No such file or directory </code></pre> <p>What am I doing wrong?</p> <p>And why do I have to struggle so much to get a software library to work on an os that "just works"? Why isn't darwin more like linux?</p>
6
2009-09-30T21:53:36Z
2,045,043
<p>On Mac OS you can have multiple Python versions installed. You can have even more if you decide to install Python via Fink or MacPorts. When you compile libraries from the source, you should make sure they point to the correct installation.</p> <p>I currently have Python 2.5.1 and Python 2.6.4 installed on my machine, which I can call via <code>python2.5</code> and <code>python</code> respectively. They live in two different folders: <code>/System/Library/Frameworks/Python.framework/Versions/2.5</code>and <code>/Library/Frameworks/Python.framework/Versions/2.6</code></p> <p>I was running into a similar problem when compiling pycairo 1.8.8 from the tarball. The <code>INSTALL</code> file in this case is your friend, as it contains the correct instructions to avoid potential version conflicts. You basically need to specify the correct prefix so that the package will be installed in the correct folder.</p> <pre> $ python -c "import sys; print sys.prefix" # make a note of the python prefix $ ./configure --prefix=[python_prefix] $ make $ make install # may require superuser access </pre> <p>Running these instructions with <code>python2.5</code> and <code>python</code> you will be able to correctly install pycairo for both versions (or for any version installed via MacPorts / Fink).</p>
2
2010-01-11T21:22:21Z
[ "python", "osx", "installation", "makefile", "cairo" ]
How to install pycairo on osx?
1,500,866
<p>I am trying to install the <a href="http://cairographics.org/pycairo/">pycairo</a> (Python bindings for the <a href="http://cairographics.org/">cairo graphics library</a>) under OSX.</p> <p>I started with</p> <pre><code>easy_install pycairo </code></pre> <p>and got: </p> <pre><code>Requested 'cairo &gt;= 1.8.8' but version of cairo is 1.0.4 error: Setup script exited with Error: cairo &gt;= 1.8.8 not found </code></pre> <p>So I went to cairo's site and downloaded the latest package (1.8.8) of cairo, and also the latest package of something called pixman (both source packages -- couldn't find osx binaries)</p> <p>unzipped both, each in own directory. for pixman, the regular <code>./configure ; make ; sudo make install</code> worked just find for cairo, ./configure seemed to work, but make failed with:</p> <pre><code>In file included from cairo-analysis-surface.c:37: cairoint.h:71:20: error: pixman.h: No such file or directory </code></pre> <p>What am I doing wrong?</p> <p>And why do I have to struggle so much to get a software library to work on an os that "just works"? Why isn't darwin more like linux?</p>
6
2009-09-30T21:53:36Z
30,089,130
<p>I found <a href="http://www.pydanny.com/installing-pycairo-on-mountain-lion.html">this</a> instruction very helpful and much less confusing. I am on Yosemite and it worked very well for me. This instruction uses homebrew to install. So if you already have homebrew, these two commands should be helpful:</p> <pre><code>$ brew install cairo --use-clang $ brew install py2cairo </code></pre> <p>For a non-Homebrew installed Python, this instruction suggest to set the PYTHONPATH to find pycairo. You can set your PYTHONPATH in your .bashrc/.profile/.whatever to the following:</p> <pre><code>PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH. </code></pre> <p>I personally didn't need to use this last part of the instruction but it might help you.</p>
6
2015-05-06T23:02:42Z
[ "python", "osx", "installation", "makefile", "cairo" ]
Python Decorator for GAE Web-Service Security Check
1,500,982
<p>In this post, Nick suggested a decoartor: </p> <p><a href="http://stackoverflow.com/questions/1499832/python-webapp-google-app-engine-testing-for-user-pass-in-the-headers/1500047#1500047">http://stackoverflow.com/questions/1499832/python-webapp-google-app-engine-testing-for-user-pass-in-the-headers/1500047#1500047</a></p> <p>I'm writing an API to expose potentially dozens of methods as web-services, so the decorator sounds like a great idea. </p> <p>I tried to start coding one based on this sample: <a href="http://groups.google.com/group/google-appengine/browse%5Fthread/thread/ac51cc32196d62f8/aa6ccd47f217cb9a?lnk=gst&amp;q=timeout#aa6ccd47f217cb9a" rel="nofollow">http://groups.google.com/group/google-appengine/browse%5Fthread/thread/ac51cc32196d62f8/aa6ccd47f217cb9a?lnk=gst&amp;q=timeout#aa6ccd47f217cb9a</a></p> <p>I need it compatible with Python 2.5 to run under Google App Engine (GAE). </p> <p>Here's my attempt. Please just point the way to if I'm on the right track or not. Currently getting an error "Invalid Syntax" on this line: class WSTest(webapp.RequestHandler):</p> <p>My idea is to pass an array of roles to the decorator. These are the only roles (from my db that should have access to each various web service). </p> <pre><code>def BasicAuthentication(roles=[]): def _decorator(func): def _wrapper(*args, **kwds): logging.info("\n\n BasicAuthentication:START:__call__ \n\n") auth = None if 'Authorization' in self.request.headers: auth = self.request.headers['Authorization'] if not auth: self.response.headers['WWW-Authenticate'] = 'Basic realm="MYREALM"' self.response.set_status(401) self.response.out.write("Authorization required") logging.info ("\n\n Authorization required \n\n") return (username, password) = base64.b64decode(auth.split(' ')[1]).split(':') logging.info ("\n\n username = " + username + " password=" + password + "\n\n") isValidUserPass = False usersSimulatedRole = "Admin" #check against database here... if user == "test12" and password == "test34": isValidUserPass = True isValidRole = False if usersSimulatedRole in roles: isValidRole = True #next check that user has one of the roles # TODO if not isValidUserPass: self.response.set_status(403) self.response.out.write("Forbidden: Userid/password combination failed") logging.info("\n\n BasicAuthentication:END:__call__ \n\n") return func(*args, **kwds) return _wrapper return _decorator @BasicAuthentication(["Admin","Worker"]) #list of roles that can run this function class WSTest(webapp.RequestHandler): def get(self): logging.info("\n\n\n WSTest \n\n") ...etc... </code></pre> <p>Thanks, Neal Walters </p>
0
2009-09-30T22:31:37Z
1,501,036
<p>Class decorators were added in <a href="http://docs.python.org/whatsnew/2.6.html#pep-3129-class-decorators" rel="nofollow">Python 2.6</a>.</p> <p>You'll have to manually wrap the class or think of another solution to work under 2.5. How about writing a decorator for the <code>get</code> method instead?</p>
2
2009-09-30T22:42:36Z
[ "python", "google-app-engine", "decorator", "web-services" ]
Python Decorator for GAE Web-Service Security Check
1,500,982
<p>In this post, Nick suggested a decoartor: </p> <p><a href="http://stackoverflow.com/questions/1499832/python-webapp-google-app-engine-testing-for-user-pass-in-the-headers/1500047#1500047">http://stackoverflow.com/questions/1499832/python-webapp-google-app-engine-testing-for-user-pass-in-the-headers/1500047#1500047</a></p> <p>I'm writing an API to expose potentially dozens of methods as web-services, so the decorator sounds like a great idea. </p> <p>I tried to start coding one based on this sample: <a href="http://groups.google.com/group/google-appengine/browse%5Fthread/thread/ac51cc32196d62f8/aa6ccd47f217cb9a?lnk=gst&amp;q=timeout#aa6ccd47f217cb9a" rel="nofollow">http://groups.google.com/group/google-appengine/browse%5Fthread/thread/ac51cc32196d62f8/aa6ccd47f217cb9a?lnk=gst&amp;q=timeout#aa6ccd47f217cb9a</a></p> <p>I need it compatible with Python 2.5 to run under Google App Engine (GAE). </p> <p>Here's my attempt. Please just point the way to if I'm on the right track or not. Currently getting an error "Invalid Syntax" on this line: class WSTest(webapp.RequestHandler):</p> <p>My idea is to pass an array of roles to the decorator. These are the only roles (from my db that should have access to each various web service). </p> <pre><code>def BasicAuthentication(roles=[]): def _decorator(func): def _wrapper(*args, **kwds): logging.info("\n\n BasicAuthentication:START:__call__ \n\n") auth = None if 'Authorization' in self.request.headers: auth = self.request.headers['Authorization'] if not auth: self.response.headers['WWW-Authenticate'] = 'Basic realm="MYREALM"' self.response.set_status(401) self.response.out.write("Authorization required") logging.info ("\n\n Authorization required \n\n") return (username, password) = base64.b64decode(auth.split(' ')[1]).split(':') logging.info ("\n\n username = " + username + " password=" + password + "\n\n") isValidUserPass = False usersSimulatedRole = "Admin" #check against database here... if user == "test12" and password == "test34": isValidUserPass = True isValidRole = False if usersSimulatedRole in roles: isValidRole = True #next check that user has one of the roles # TODO if not isValidUserPass: self.response.set_status(403) self.response.out.write("Forbidden: Userid/password combination failed") logging.info("\n\n BasicAuthentication:END:__call__ \n\n") return func(*args, **kwds) return _wrapper return _decorator @BasicAuthentication(["Admin","Worker"]) #list of roles that can run this function class WSTest(webapp.RequestHandler): def get(self): logging.info("\n\n\n WSTest \n\n") ...etc... </code></pre> <p>Thanks, Neal Walters </p>
0
2009-09-30T22:31:37Z
1,502,482
<p>You need to write a method decorator, not a class decorator: As lost-theory points out, class decorators don't exist in Python 2.5, and they wouldn't work very well in any case, because the RequestHandler class isn't initialized with request data until <em>after</em> it's constructed. A method decorator also gives you more control - eg, you could allow GET requests unauthenticated, but still require authentication for POST requests.</p> <p>Other than that, your decorator looks fine - just apply it to the relevant methods. The only change I would really suggest is replacing the .set_status() calls with .error() calls and remove the response.write calls; this allows you to override .error() on the RequestHandler class to output a nice error page for each possible status code.</p>
2
2009-10-01T07:50:44Z
[ "python", "google-app-engine", "decorator", "web-services" ]
Find current geographic coordinates from Python script
1,501,008
<p>I'm tying to get a certain Python script (although I guess it isn't really the language that's going to matter here) to find out the current geographic location of the machine running it. As you might have guessed, it's a little script that reports my laptop's location when it boots and stuff :)<br/> Is there any free web service or API to do this? I was pretty impressed by Google Maps' ability to pinpoint my house (it was off by only ~5 meters!).</p>
2
2009-09-30T22:36:43Z
1,501,106
<p>I came across this Python script <a href="http://netsekure.org/wp-content/uploads/ip2loc.py" rel="nofollow">http://netsekure.org/wp-content/uploads/ip2loc.py</a> which might be something similar to what you are looking for.</p>
3
2009-09-30T23:01:49Z
[ "python", "api", "geolocation", "location" ]
Find current geographic coordinates from Python script
1,501,008
<p>I'm tying to get a certain Python script (although I guess it isn't really the language that's going to matter here) to find out the current geographic location of the machine running it. As you might have guessed, it's a little script that reports my laptop's location when it boots and stuff :)<br/> Is there any free web service or API to do this? I was pretty impressed by Google Maps' ability to pinpoint my house (it was off by only ~5 meters!).</p>
2
2009-09-30T22:36:43Z
1,501,178
<p>You may be able to use Google's GeoLocation API (API docs <a href="http://code.google.com/apis/gears/geolocation%5Fnetwork%5Fprotocol.html" rel="nofollow">here</a>). From the docs:</p> <p>"Communication is done over HTTP, with Gears making the request using HTTP POST. Both request and response are formatted as JSON, and the content type of both is application/json."</p> <p>The python standard library json module can be found <a href="http://docs.python.org/library/json.html" rel="nofollow">here</a>.</p>
1
2009-09-30T23:23:02Z
[ "python", "api", "geolocation", "location" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,501,133
<p>Maybe something like this:</p> <pre><code>if len(x) == len(set(x)): print "all elements are unique" else: print "elements are not unique" </code></pre>
26
2009-09-30T23:09:26Z
[ "python", "list", "unique" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,501,141
<p>How about this:</p> <pre><code>if len(x) != len(set(x)): raise Exception("throw to caller") </code></pre> <p>This assumes that elements in <code>x</code> are hashable.</p>
7
2009-09-30T23:11:09Z
[ "python", "list", "unique" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,501,202
<p>Hopefully all the items in your sequence are immutable -- if not, you will not be able to call <code>set</code> on the sequence.</p> <pre><code>&gt;&gt;&gt; set( ([1,2], [3,4]) ) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unhashable type: 'list' </code></pre> <p>If you <em>do</em> have mutable items, you can't hash the items and you will pretty much have to repeatedly check through the list:</p> <pre><code>def isUnique(lst): for i,v in enumerate(lst): if v in lst[i+1:]: return False return True </code></pre> <p><code> </code></p> <pre><code>&gt;&gt;&gt; isUnique( ([1,2], [3,4]) ) True &gt;&gt;&gt; isUnique( ([1,2], [3,4], [1,2]) ) False </code></pre>
2
2009-09-30T23:31:47Z
[ "python", "list", "unique" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,501,231
<p>As you build the list you can check to see if the value already exists, e.g:</p> <pre><code>if x in y: raise Exception("Value %s already in y" % x) else: y.append(x) </code></pre> <p>the benefit of this is that the clashing variable will be reported.</p>
1
2009-09-30T23:40:31Z
[ "python", "list", "unique" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,501,460
<p>You could process the list to create a known-to-be-unique copy:</p> <pre><code>def make_unique(seq): t = type(seq) seen = set() return t(c for c in seq if not (c in seen or seen.add(c))) </code></pre> <p>Or if the seq elements are not hashable:</p> <pre><code>def unique1(seq): t = type(seq) seen = [] return t(c for c in seq if not (c in seen or seen.append(c))) </code></pre> <p>And this will keep the items in order (omitting duplicates, of course).</p>
0
2009-10-01T01:22:28Z
[ "python", "list", "unique" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,501,503
<p>The most popular answers are O(N) (good!-) but, as @Paul and @Mark point out, they require the list's items to be hashable. Both @Paul and @Mark's proposed approaches for unhashable items are general but take O(N squared) -- i.e., a lot.</p> <p>If your list's items are not hashable but <em>are</em> comparable, you can do better... here's an approach that always work as fast as feasible given the nature of the list's items.</p> <pre><code>import itertools def allunique(L): # first try sets -- fastest, if all items are hashable try: return len(L) == len(set(L)) except TypeError: pass # next, try sort -- second fastest, if items are comparable try: L1 = sorted(L) except TypeError: pass else: return all(len(list(g))==1 for k, g in itertools.groupby(L1)) # fall back to the slowest but most general approach return all(v not in L[i+1:] for i, L in enumerate(L)) </code></pre> <p>This is O(N) where feasible (all items hashable), O(N log N) as the most frequent fallback (some items unhashable, but all comparable), O(N squared) where inevitable (some items unhashable, e.g. dicts, and some non-comparable, e.g. complex numbers).</p> <p>Inspiration for this code comes from an old recipe by the great Tim Peters, which differed by actually producing a list of unique items (and also was so far ago that <code>set</code> was not around -- it had to use a <code>dict</code>...!-), but basically faced identical issues.</p>
18
2009-10-01T01:45:12Z
[ "python", "list", "unique" ]
What's the most pythonic way to ensure that all elements of a list are different?
1,501,118
<p>I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.</p> <p>This is the way I do it now:</p> <p>If there are two elements:</p> <pre><code>try: assert(x[0] != x[1]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>If there are three:</p> <pre><code>try: assert(x[0] != x[1]) assert(x[0] != x[2]) assert(x[1] != x[2]) except: print debug_info raise Exception("throw to caller") </code></pre> <p>And if I ever have to do this with four elements I'll go crazy.</p> <p>Is there a better way to ensure that all the elements of the list are unique?</p>
8
2009-09-30T23:07:02Z
1,503,165
<p>I would use this:</p> <pre><code>mylist = [1,2,3,4] is_unique = all(mylist.count(x) == 1 for x in mylist) </code></pre>
0
2009-10-01T10:32:14Z
[ "python", "list", "unique" ]
Named and default arguments class arguments in Python
1,501,208
<p>In PHP, I have to pass the arguments in the same order as the arguments are in the constructor.</p> <p>Now, in Python, take</p> <pre><code>listbox = Listbox(root, yscrollcommand=scrollbar.set) </code></pre> <p>for example.</p> <p>If I had passed yscrollcommand=scrollbar.set as the third argument and yscrollcommand was the second argument in the constructor, would I still be able to access scrollbar.set from yscrollcommand inside the listbox constructor?</p> <p>I ask this because even though the arguments are not in the same order, with an equal sign they have a name.</p>
1
2009-09-30T23:33:56Z
1,501,246
<p>Named arguments don't have to be in order.</p> <pre><code>class xyz: def __init__ (self, a='1', b='2'): print a,b xyz(b=3,a=4) xyz(a=5,b=6) &gt;&gt;4 3 &gt;&gt;5 6 </code></pre>
4
2009-09-30T23:44:47Z
[ "python", "arguments", "default", "named" ]
Named and default arguments class arguments in Python
1,501,208
<p>In PHP, I have to pass the arguments in the same order as the arguments are in the constructor.</p> <p>Now, in Python, take</p> <pre><code>listbox = Listbox(root, yscrollcommand=scrollbar.set) </code></pre> <p>for example.</p> <p>If I had passed yscrollcommand=scrollbar.set as the third argument and yscrollcommand was the second argument in the constructor, would I still be able to access scrollbar.set from yscrollcommand inside the listbox constructor?</p> <p>I ask this because even though the arguments are not in the same order, with an equal sign they have a name.</p>
1
2009-09-30T23:33:56Z
1,501,253
<p>It is explained <a href="http://diveintopython.net/power_of_introspection/and_or.html" rel="nofollow">here</a>.</p>
1
2009-09-30T23:47:28Z
[ "python", "arguments", "default", "named" ]
Log output of multiprocessing.Process
1,501,651
<p>Is there a way to log the stdout output from a given Process when using the multiprocessing.Process class in python?</p>
43
2009-10-01T02:44:03Z
1,501,756
<p>You can set <code>sys.stdout = Logger()</code> where <code>Logger</code> is a class whose <code>write</code> method (immediately, or accumulating until a <code>\n</code> is detected) calls <code>logging.info</code> (or any other way you want to log). <a href="https://github.com/jdloft/multiprocess-logging/blob/master/main.py">An example of this in action.</a></p> <p>I'm not sure what you mean by "a given" process (who's given it, what distinguishes it from all others...?), but if you mean you know what process you want to single out that way at the time you instantiate it, then you could wrap its <code>target</code> function (and that only) -- or the <code>run</code> method you're overriding in a <code>Process</code> subclass -- into a wrapper that performs this sys.stdout "redirection" -- and leave other processes alone.</p> <p>Maybe if you nail down the specs a bit I can help in more detail...?</p>
9
2009-10-01T03:29:57Z
[ "python", "logging", "concurrency", "multiprocessing" ]
Log output of multiprocessing.Process
1,501,651
<p>Is there a way to log the stdout output from a given Process when using the multiprocessing.Process class in python?</p>
43
2009-10-01T02:44:03Z
1,501,757
<p>The easiest way might be to just override <code>sys.stdout</code>. Slightly modifying an example from <a href="http://docs.python.org/library/multiprocessing.html#the-process-class">the multiprocessing manual</a>:</p> <pre><code>from multiprocessing import Process import os import sys def info(title): print title print 'module name:', __name__ print 'parent process:', os.getppid() print 'process id:', os.getpid() def f(name): sys.stdout = open(str(os.getpid()) + ".out", "w") info('function f') print 'hello', name if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() q = Process(target=f, args=('fred',)) q.start() p.join() q.join() </code></pre> <p>And running it:</p> <pre> $ ls m.py $ python m.py $ ls 27493.out 27494.out m.py $ cat 27493.out function f module name: __main__ parent process: 27492 process id: 27493 hello bob $ cat 27494.out function f module name: __main__ parent process: 27492 process id: 27494 hello fred </pre>
32
2009-10-01T03:30:09Z
[ "python", "logging", "concurrency", "multiprocessing" ]
Log output of multiprocessing.Process
1,501,651
<p>Is there a way to log the stdout output from a given Process when using the multiprocessing.Process class in python?</p>
43
2009-10-01T02:44:03Z
23,937,468
<p>There are only two things I would add to @Mark Rushakoff answer. When debugging, I found it really useful to change the <code>buffering</code> parameter of my <code>open()</code> calls to 0.</p> <pre><code>sys.stdout = open(str(os.getpid()) + ".out", "a", buffering=0) </code></pre> <p>Otherwise, <strong>madness</strong>, because when <code>tail -f</code>ing the output file the results can be verrry intermittent. <code>buffering=0</code> for <code>tail -f</code>ing great.</p> <p>And for completeness, do yourself a favor and redirect <code>sys.stderr</code> as well.</p> <pre><code>sys.stderr = open(str(os.getpid()) + "_error.out", "a", buffering=0) </code></pre> <p>Also, for convenience you might dump that into a separate process class if you wish, </p> <pre><code>class MyProc(Process): def run(self): # Define the logging in run(), MyProc's entry function when it is .start()-ed # p = MyProc() # p.start() self.initialize_logging() print 'Now output is captured.' # Now do stuff... def initialize_logging(self): sys.stdout = open(str(os.getpid()) + ".out", "a", buffering=0) sys.stderr = open(str(os.getpid()) + "_error.out", "a", buffering=0) print 'stdout initialized' </code></pre> <p><a href="https://gist.github.com/namoopsoo/104dd7c568df17255bb5">Heres a corresponding gist</a></p>
7
2014-05-29T15:51:01Z
[ "python", "logging", "concurrency", "multiprocessing" ]
Parsing out data using BeautifulSoup in Python
1,501,690
<p>I am attempting to use BeautifulSoup to parse through a DOM tree and extract the names of authors. Below is a snippet of HTML to show the structure of the code I'm going to scrape. </p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div class="list-authors"&gt; &lt;span class="descriptor"&gt;Authors:&lt;/span&gt; &lt;a href="/find/astro-ph/1/au:+Lin_D/0/1/0/all/0/1"&gt;Dacheng Lin&lt;/a&gt;, &lt;a href="/find/astro-ph/1/au:+Remillard_R/0/1/0/all/0/1"&gt;Ronald A. Remillard&lt;/a&gt;, &lt;a href="/find/astro-ph/1/au:+Homan_J/0/1/0/all/0/1"&gt;Jeroen Homan&lt;/a&gt; &lt;/div&gt; &lt;div class="list-authors"&gt; &lt;span class="descriptor"&gt;Authors:&lt;/span&gt; &lt;a href="/find/astro-ph/1/au:+Kosovichev_A/0/1/0/all/0/1"&gt;A.G. Kosovichev&lt;/a&gt; &lt;/div&gt; &lt;!--There are many other div tags with this structure--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My point of confusion is that when I do soup.find, it finds the first occurrence of the div tag that I'm searching for. After that, I search for all 'a' link tags. At this stage, how do I extract the authors names from each of the link tags and print them out? Is there a way to do it using BeautifulSoup or do I need to use Regex? How do I continue iterating over every other other div tag and extract the authors names?</p> <pre><code>import re import urllib2,sys from BeautifulSoup import BeautifulSoup, NavigableString html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) try: authordiv = soup.find('div', attrs={'class': 'list-authors'}) links=tds.findAll('a') for link in links: print ''.join(link[0].contents) #Iterate through entire page and print authors except IOError: print 'IO error' </code></pre>
9
2009-10-01T02:59:32Z
1,501,715
<p>Since <code>link</code> is already taken from an iterable, you don't need to subindex <code>link</code> -- you can just do <code>link.contents[0]</code>.</p> <p><code>print link.contents[0]</code> with your new example with two separate <code>&lt;div class="list-authors"&gt;</code> yields:</p> <pre>Dacheng Lin Ronald A. Remillard Jeroen Homan A.G. Kosovichev </pre> <p>So I'm not sure I understand the comment about searching other divs. If they are different classes, you will either need to do a separate <code>soup.find</code> and <code>soup.findAll</code>, or just modify your first <code>soup.find</code>.</p>
1
2009-10-01T03:14:19Z
[ "python", "html", "parsing", "beautifulsoup" ]
Parsing out data using BeautifulSoup in Python
1,501,690
<p>I am attempting to use BeautifulSoup to parse through a DOM tree and extract the names of authors. Below is a snippet of HTML to show the structure of the code I'm going to scrape. </p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div class="list-authors"&gt; &lt;span class="descriptor"&gt;Authors:&lt;/span&gt; &lt;a href="/find/astro-ph/1/au:+Lin_D/0/1/0/all/0/1"&gt;Dacheng Lin&lt;/a&gt;, &lt;a href="/find/astro-ph/1/au:+Remillard_R/0/1/0/all/0/1"&gt;Ronald A. Remillard&lt;/a&gt;, &lt;a href="/find/astro-ph/1/au:+Homan_J/0/1/0/all/0/1"&gt;Jeroen Homan&lt;/a&gt; &lt;/div&gt; &lt;div class="list-authors"&gt; &lt;span class="descriptor"&gt;Authors:&lt;/span&gt; &lt;a href="/find/astro-ph/1/au:+Kosovichev_A/0/1/0/all/0/1"&gt;A.G. Kosovichev&lt;/a&gt; &lt;/div&gt; &lt;!--There are many other div tags with this structure--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My point of confusion is that when I do soup.find, it finds the first occurrence of the div tag that I'm searching for. After that, I search for all 'a' link tags. At this stage, how do I extract the authors names from each of the link tags and print them out? Is there a way to do it using BeautifulSoup or do I need to use Regex? How do I continue iterating over every other other div tag and extract the authors names?</p> <pre><code>import re import urllib2,sys from BeautifulSoup import BeautifulSoup, NavigableString html = urllib2.urlopen(address).read() soup = BeautifulSoup(html) try: authordiv = soup.find('div', attrs={'class': 'list-authors'}) links=tds.findAll('a') for link in links: print ''.join(link[0].contents) #Iterate through entire page and print authors except IOError: print 'IO error' </code></pre>
9
2009-10-01T02:59:32Z
1,501,755
<p>just use findAll for the divs link you do for the links</p> <p>for authordiv in soup.findAll('div', attrs={'class': 'list-authors'}):</p>
12
2009-10-01T03:29:56Z
[ "python", "html", "parsing", "beautifulsoup" ]
Python regex question
1,501,772
<p>I am wondering what would be a pythonic solution for this question.</p> <p><a href="http://stackoverflow.com/questions/1483757/in-aa67bc54c9-is-there-any-way-to-print-aa-67-times-bc-54-times-and-so-on">http://stackoverflow.com/questions/1483757/in-aa67bc54c9-is-there-any-way-to-print-aa-67-times-bc-54-times-and-so-on</a></p>
2
2009-10-01T03:37:11Z
1,501,815
<p>This would be a concise way:</p> <pre><code>import re s = "aa67bc54c9" print ''.join(t * int(n) for t, n in re.findall(r"([a-z]+)([0-9]+)", s)) </code></pre> <p>This solution uses a regular expression to match "one or more letters followed by one or more numbers", searching for all of them in the input string. Then it uses a list comprehension to iterate through each group found, assigning the letters to <code>t</code> and the digits to <code>n</code> in turn. The list generates strings using the string <code>*</code> operator, which repeates a string a given number of times (<code>int()</code> is used to convert the digit string into an integer). Finally, <code>''.join()</code> is used to paste everything together.</p> <p>For the regular expression, <code>[a-z]</code> is a character class consisting of any single (lowercase) letter of the alphabet. <code>[a-z]+</code> means one or more lowercase letters. Similarly, <code>[0-9]+</code> means one or more digits. The grouping parentheses around each component "capture" the characters within them and make them available as a result of the <code>findall()</code> function. There are two groups of parentheses, so there are two output values, which get assigned to <code>t</code> and <code>n</code> in the list comprehension.</p>
3
2009-10-01T03:53:22Z
[ "python", "regex" ]
Python regex question
1,501,772
<p>I am wondering what would be a pythonic solution for this question.</p> <p><a href="http://stackoverflow.com/questions/1483757/in-aa67bc54c9-is-there-any-way-to-print-aa-67-times-bc-54-times-and-so-on">http://stackoverflow.com/questions/1483757/in-aa67bc54c9-is-there-any-way-to-print-aa-67-times-bc-54-times-and-so-on</a></p>
2
2009-10-01T03:37:11Z
1,502,139
<p>Here is my Python solution.</p> <pre><code>import re pat = re.compile("^(\D+)(\d+)(.*)$") def rle_expand(s): lst = [] while True: m = pat.match(s) if m: n = int(m.group(2)) lst.append(m.group(1) * n) else: lst.append(s) break s = m.group(3) return "".join(lst) s = "aa03bc05d9whew" print rle_expand(s) # prints aaaaaabcbcbcbcbcdddddddddwhew s = “aa67bc54c9” print rle_expand(s) # prints: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcccccccccc </code></pre> <p>The problem is basically to expand a run-length encoding. First you have some sort of a pattern, then some digits that specify how many times to repeat the pattern.</p> <p>First we import the <code>re</code> module, to gain access to Python's regular expressions.</p> <p>Next we compile a pattern once, so we can use it later. What will this pattern do?</p> <p>The pattern uses parentheses to mark groups of letters from the string being matched. There are three pairs of parens so this will match three groups. Before the first group is a '^' character, which anchors to the start of the string, and after the last group is a '$' character, which anchors to the end of the string; these aren't strictly necessary in this case. The first group matches anything that is <em>not</em> a digit using the special sequence <code>\D</code>; the <code>+</code> extends it to match a run of one or more instances of not-a-digit. The second group is similar, using <code>\d+</code> to match a run of one or more digits. The third group uses <code>.</code> to match any character, then extends it with <code>*</code> to match a run of 0 or more of any character. (Note that <code>*</code> and <code>+</code> are very similar; it's just that <code>*</code> matches 0 or more of something and <code>+</code> matches one or more.)</p> <p>Using a standard Python idiom, we build a string using a list. We start out with an empty list (called <code>lst</code>). As long as the pattern keeps matching things, we append things to this list. When we are done, we use <code>"".join()</code> to join the list together into a string.</p> <p><code>pat.match()</code> returns an object called a "match object", or <code>None</code> if the match failed. If the match succeeded, we convert match group 2 to an integer, and use Python string repetition operator ("multiply") on match group 1 to do the run-length expansion. After this, we rebind the name <code>s</code> with the results of match group 3, thereby snipping off the part of the string we just processed, and loop. If the match failed, we just append all of <code>s</code> to the list and break out of the loop.</p> <p>Building a list and then using <code>"".join()</code> on the list is a standard Python idiom. It will give good performance with any version of Python. Because Python strings are immutable, you can suffer from very slow performance if you build up a long dynamic string by repeatedly appending to a string; you wind up copying the early parts of the string many times as you build your final string. Python lists can be trivially appended to, and then the final join operation is quite fast. (Recent versions of Python have optimized the case where you repeatedly append to a string, and no longer suffer from the repeated copying in this case.)</p> <p>Greg Hewgill's solution only recognizes lower-case letters from 'a' to 'z' for the expansion text; you could fix that by putting <code>\D</code> instead of <code>[a-z]</code>. His solution uses explicit ranges such as <code>[0-9]</code> where my solution uses the Python shorthand abbreviations such as <code>\d</code>. His solution only expands the run length encoded sequences; if there is a trailing sequence that does not have an integer on it, mine passes that sequence unchanged, while his silently ignores it. However, it must be said that his solution is brutally elegant and I wish I had thought of it. :-)</p>
3
2009-10-01T06:04:30Z
[ "python", "regex" ]
Run a task every hour on the hour with App Engine's cron API
1,501,907
<p>I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.</p> <p>There is an example of running at ask every hour, but this doesn't fit because the "start" of that hour depends on when you deploy the application. That is, if I deploy at 4:37 PM, the cron scripts will get executed at 5:37, 6:37, ... instead of 5:00, 6:00, ...</p> <p>So far the only way that looks like it would work is to have 24 different cron entries, one for the specific hour of each day set to run each day at that specific time. </p> <p>Does anyone know of anything that would let me use a schedule like "every hour at :00" or even "every day 00:00, 01:00, ... 23:00"?</p>
3
2009-10-01T04:36:27Z
1,501,925
<p>Looking over the docs, I agree that your 24 cron entry idea is the only documented way that would work. Not ideal, but should work.</p>
-1
2009-10-01T04:45:51Z
[ "python", "google-app-engine", "cron" ]
Run a task every hour on the hour with App Engine's cron API
1,501,907
<p>I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.</p> <p>There is an example of running at ask every hour, but this doesn't fit because the "start" of that hour depends on when you deploy the application. That is, if I deploy at 4:37 PM, the cron scripts will get executed at 5:37, 6:37, ... instead of 5:00, 6:00, ...</p> <p>So far the only way that looks like it would work is to have 24 different cron entries, one for the specific hour of each day set to run each day at that specific time. </p> <p>Does anyone know of anything that would let me use a schedule like "every hour at :00" or even "every day 00:00, 01:00, ... 23:00"?</p>
3
2009-10-01T04:36:27Z
1,501,960
<p>The docs say you can have 20 cron entries, so you can't have one for every hour of the day.</p> <p>You could run your task every minute and check if it is the first minute of the hour - exit otherwise.</p>
0
2009-10-01T04:56:24Z
[ "python", "google-app-engine", "cron" ]
Run a task every hour on the hour with App Engine's cron API
1,501,907
<p>I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.</p> <p>There is an example of running at ask every hour, but this doesn't fit because the "start" of that hour depends on when you deploy the application. That is, if I deploy at 4:37 PM, the cron scripts will get executed at 5:37, 6:37, ... instead of 5:00, 6:00, ...</p> <p>So far the only way that looks like it would work is to have 24 different cron entries, one for the specific hour of each day set to run each day at that specific time. </p> <p>Does anyone know of anything that would let me use a schedule like "every hour at :00" or even "every day 00:00, 01:00, ... 23:00"?</p>
3
2009-10-01T04:36:27Z
1,502,516
<p>Unfortunately, the cron syntax doesn't let you specify the time for intervals less than a day. What you can do, however, is use the <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">Task Queue</a> for this. Either:</p> <ol> <li>Have a single task queue entry that, when it runs, enqueues a new task with the 'countdown' set to the number of seconds until the next time you want to run.</li> <li>Have a daily cron job that enqueues 24 hourly taskqueue entries at each of the times you want it to run.</li> </ol>
3
2009-10-01T07:58:54Z
[ "python", "google-app-engine", "cron" ]
Run a task every hour on the hour with App Engine's cron API
1,501,907
<p>I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.</p> <p>There is an example of running at ask every hour, but this doesn't fit because the "start" of that hour depends on when you deploy the application. That is, if I deploy at 4:37 PM, the cron scripts will get executed at 5:37, 6:37, ... instead of 5:00, 6:00, ...</p> <p>So far the only way that looks like it would work is to have 24 different cron entries, one for the specific hour of each day set to run each day at that specific time. </p> <p>Does anyone know of anything that would let me use a schedule like "every hour at :00" or even "every day 00:00, 01:00, ... 23:00"?</p>
3
2009-10-01T04:36:27Z
7,402,852
<p>You could do this, and give up the exactly on the hour, but it will be close...</p> <p>(Example came from a app I was debuging)</p> <pre><code>cron: - description: Description of what you want done... url: /script/path/goes/here schedule: every 60 minutes synchronized timezone: America/New_York </code></pre> <p>Below is a screenshot of the logs, the app gets no traffic right now, 99% of those entries are all the cron entry.</p> <p><img src="http://i.stack.imgur.com/DPk1a.png" alt="enter image description here"></p> <p>--- <strong><em>edit</em></strong> ---</p> <p>Just re-read the docs as well and maybe this might be better,</p> <pre><code> schedule: every 60 minutes from 00:00 to 23:59 </code></pre>
3
2011-09-13T13:40:38Z
[ "python", "google-app-engine", "cron" ]
Using CherryPy as a blocking/non-threading server for easier debugging
1,502,431
<p>Is it possible to use the CherrPy server as a blocking/non-threading server (for easier debugging?)</p>
0
2009-10-01T07:37:59Z
1,502,612
<p>No. Not only does the wsgiserver start its own set of worker threads (10 by default, but even if you only specified 1 that's still 1 thread for the listening socket and 1 worker thread). Even if that were not true, if you use the rest of CherryPy (i.e. the engine), it runs that 1 listener thread in a separate thread from the main thread.</p>
2
2009-10-01T08:24:58Z
[ "python", "debugging", "cherrypy" ]
How to pick certain elements of x-tuple returned by a function?
1,502,470
<p>I am a newbie to Python. Consider the function <code>str.partition()</code> which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?</p> <p>I can currently do either:</p> <pre><code># Introduces "part1" variable, which is useless (part0, part1, part2) = str.partition(' ') </code></pre> <p>Or:</p> <pre><code># Multiple calls and statements, again redundancy part0 = str.partition(' ')[0] part2 = str.partition(' ')[2] </code></pre> <p>I would like to be able to do <em>something</em> like this, but cannot:</p> <pre><code>(part0, , part2) = str.partition(' ') # Or: (part0, part2) = str.partition(' ')[0, 2] </code></pre>
2
2009-10-01T07:47:46Z
1,502,486
<p>I think a question I asked some time ago could help you:</p> <p><a href="http://stackoverflow.com/questions/1105101/pythonic-way-to-get-some-rows-of-a-matrix">http://stackoverflow.com/questions/1105101/pythonic-way-to-get-some-rows-of-a-matrix</a></p> <p>NumPy gives you the slice syntax you want to extract various elements using a tuple or list of indices, but I don't think you'd like to convert you list of strings to a numpy.array just to extract a few elements, so maybe you could write a helper:</p> <pre><code>def extract(lst, *indices): return [lst[i] for i in indices] item0, item2 = extract(str.partition(' '), 0, 2) </code></pre>
2
2009-10-01T07:52:31Z
[ "python", "list", "tuples", "iterable-unpacking" ]
How to pick certain elements of x-tuple returned by a function?
1,502,470
<p>I am a newbie to Python. Consider the function <code>str.partition()</code> which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?</p> <p>I can currently do either:</p> <pre><code># Introduces "part1" variable, which is useless (part0, part1, part2) = str.partition(' ') </code></pre> <p>Or:</p> <pre><code># Multiple calls and statements, again redundancy part0 = str.partition(' ')[0] part2 = str.partition(' ')[2] </code></pre> <p>I would like to be able to do <em>something</em> like this, but cannot:</p> <pre><code>(part0, , part2) = str.partition(' ') # Or: (part0, part2) = str.partition(' ')[0, 2] </code></pre>
2
2009-10-01T07:47:46Z
1,502,487
<p>Correct, you can not take several ad hoc elements out of a list of tuple in one go.</p> <pre><code>part0, part1, part2 = str.partition(' ') </code></pre> <p>Is the way to go. Don't worry about part1, if you don't need it, you don't need it. It's common to call it "dummy" or "unused" to show that it's not used.</p> <p>You CAN be ugly with:</p> <pre><code>part0, part2 = str.partition(' ')[::2] </code></pre> <p>In this specific case, but that's obfuscating and not nice towards others. ;)</p>
4
2009-10-01T07:52:34Z
[ "python", "list", "tuples", "iterable-unpacking" ]
How to pick certain elements of x-tuple returned by a function?
1,502,470
<p>I am a newbie to Python. Consider the function <code>str.partition()</code> which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?</p> <p>I can currently do either:</p> <pre><code># Introduces "part1" variable, which is useless (part0, part1, part2) = str.partition(' ') </code></pre> <p>Or:</p> <pre><code># Multiple calls and statements, again redundancy part0 = str.partition(' ')[0] part2 = str.partition(' ')[2] </code></pre> <p>I would like to be able to do <em>something</em> like this, but cannot:</p> <pre><code>(part0, , part2) = str.partition(' ') # Or: (part0, part2) = str.partition(' ')[0, 2] </code></pre>
2
2009-10-01T07:47:46Z
1,502,488
<p>Underscore is often used as a name for stuff you do not need, so something like this would work:</p> <pre><code>part0, _, part2 = str.partition(' ') </code></pre> <p>In this particular case, you could do this, but it isn't a pretty solution:</p> <pre><code>part0, part2 = str.partition(' ')[::2] </code></pre> <p>A more esoteric solution:</p> <pre><code>from operator import itemgetter part0, part2 = itemgetter(0, 2)(str.partition(' ')) </code></pre>
13
2009-10-01T07:52:38Z
[ "python", "list", "tuples", "iterable-unpacking" ]
How to pick certain elements of x-tuple returned by a function?
1,502,470
<p>I am a newbie to Python. Consider the function <code>str.partition()</code> which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?</p> <p>I can currently do either:</p> <pre><code># Introduces "part1" variable, which is useless (part0, part1, part2) = str.partition(' ') </code></pre> <p>Or:</p> <pre><code># Multiple calls and statements, again redundancy part0 = str.partition(' ')[0] part2 = str.partition(' ')[2] </code></pre> <p>I would like to be able to do <em>something</em> like this, but cannot:</p> <pre><code>(part0, , part2) = str.partition(' ') # Or: (part0, part2) = str.partition(' ')[0, 2] </code></pre>
2
2009-10-01T07:47:46Z
1,504,687
<p>you could also use <code>str.split(' ', 1)</code> instead of <code>str.partition(' ')</code></p> <p>you'll get back a list instead of a tuple, but you won't get the separator back</p>
1
2009-10-01T15:35:51Z
[ "python", "list", "tuples", "iterable-unpacking" ]
How to pick certain elements of x-tuple returned by a function?
1,502,470
<p>I am a newbie to Python. Consider the function <code>str.partition()</code> which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?</p> <p>I can currently do either:</p> <pre><code># Introduces "part1" variable, which is useless (part0, part1, part2) = str.partition(' ') </code></pre> <p>Or:</p> <pre><code># Multiple calls and statements, again redundancy part0 = str.partition(' ')[0] part2 = str.partition(' ')[2] </code></pre> <p>I would like to be able to do <em>something</em> like this, but cannot:</p> <pre><code>(part0, , part2) = str.partition(' ') # Or: (part0, part2) = str.partition(' ')[0, 2] </code></pre>
2
2009-10-01T07:47:46Z
1,506,065
<p>This is how I would do it:</p> <pre><code>all_parts = str.partition(' ') part0, part2 = all_parts[0], all_parts[2] </code></pre>
0
2009-10-01T19:49:32Z
[ "python", "list", "tuples", "iterable-unpacking" ]
Paster cannot stop daemon
1,502,568
<p>I'm using the following command in my pylons app in an attempt to stop the daemon on the server:</p> <pre><code>paster serve --daemon dev.ini stop </code></pre> <p>This is the error I get:</p> <pre><code>No PID file exists in paster.pid Could not stop daemon; aborting </code></pre> <p>Wondering how I can stop this daemon so I can reload dev.ini.</p> <p>Thanks!</p>
3
2009-10-01T08:14:41Z
1,502,706
<p>kill the process.</p>
0
2009-10-01T08:46:38Z
[ "python", "command-line", "ssh", "pylons", "paster" ]
Does keyczar python library provide functionality to verify signatures signed using x509 PEM certificates?
1,502,682
<p>I could not find a method to parse x509 pem files. I tried using ParseX509 of utils module which threw up. </p>
0
2009-10-01T08:41:57Z
30,472,624
<p>There is <a href="https://pypi.python.org/pypi/pycrypto" rel="nofollow"><code>pycrypto</code></a> with its <a href="http://pythonhosted.org/pycrypto/" rel="nofollow">old school docs</a>:</p> <blockquote> <p>This is a collection of both secure hash functions (such as SHA256 and RIPEMD160), and various encryption algorithms (AES, DES, RSA, ElGamal, etc.).</p> </blockquote> <p>And I think your question is a duplicate from <a href="http://stackoverflow.com/questions/12911373/how-do-i-use-a-x509-certificate-with-pycrypto">How do I use a X509 certificate with PyCrypto?</a></p>
0
2015-05-27T03:27:52Z
[ "python", "openssl", "keyczar" ]
basic unique ModelForm field for Google App Engine
1,502,818
<p>I do not care about concurrency issues.</p> <p>It is relatively easy to build unique form field:</p> <pre><code>from django import forms class UniqueUserEmailField(forms.CharField): def clean(self, value): self.check_uniqueness(super(UniqueUserEmailField, self).clean(value)) def check_uniqueness(self, value): same_user = users.User.all().filter('email', value).get() if same_user: raise forms.ValidationError('%s already_registered' % value) </code></pre> <p>so one could add users on-the-fly. Editing existing user is tricky. This field would not allow to save user having other user email. At the same time it would not allow to save a user with the same email. What code do you use to put a field with uniqueness check into ModelForm?</p>
0
2009-10-01T09:06:20Z
1,503,024
<p>quick and dirty way would be:</p> <ol> <li>make check_uniqueness classmethod</li> <li><p>use custom field check in ModelForm, like this:</p> <pre><code>class User(forms.ModelForm): email = forms.EmailField() def clean_email(self): data = self.cleaned_data['email'] original = self.instance.email if original == data: return data UniqueUserEmailField.check_uniqueness(data) return data </code></pre></li> </ol> <p>better options?</p>
1
2009-10-01T10:00:58Z
[ "python", "django", "google-app-engine", "app-engine-patch" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
1,503,075
<p>My naive solution:</p> <pre><code>def arePermsEqualParity(perm0, perm1): """Check if 2 permutations are of equal parity. Assume that both permutation lists are of equal length and have the same elements. No need to check for these conditions. """ transCount = 0 for loc in range(len(perm0) - 1): # Do (len - 1) transpositions if perm0[loc] != perm1[loc]: sloc = perm1.index(perm0[loc]) # Find position in perm1 perm1[loc], perm1[sloc] = perm1[sloc], perm1[loc] # Swap in perm1 transCount += 1 # Even number of transpositions means equal parity if (transCount % 2) == 0: return True else: return False </code></pre>
4
2009-10-01T10:12:53Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
1,503,144
<p>A minor variant of the previous answer - copy perm1, and save array lookups.</p> <pre><code>def arePermsEqualParity(perm0, perm1): """Check if 2 permutations are of equal parity. Assume that both permutation lists are of equal length and have the same elements. No need to check for these conditions. """ perm1 = perm1[:] ## copy this list so we don't mutate the original transCount = 0 for loc in range(len(perm0) - 1): # Do (len - 1) transpositions p0 = perm0[loc] p1 = perm1[loc] if p0 != p1: sloc = perm1[loc:].index(p0)+loc # Find position in perm1 perm1[loc], perm1[sloc] = p0, p1 # Swap in perm1 transCount += 1 # Even number of transpositions means equal parity if (transCount % 2) == 0: return True else: return False </code></pre>
4
2009-10-01T10:26:33Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
1,503,487
<p>My intuition tells me that, just counting the differences between the two permutations will give you one more than the number of swaps need to get from one to the other. This in turn will give you the parity.</p> <p>This means that you don't need to do the swaps in your code at all.</p> <p>For example:</p> <pre><code>ABCD, BDCA. </code></pre> <p>There are three differences, hence two swaps are needed to permute one into the other, hence you have even parity.</p> <p>Another:</p> <pre><code>ABCD, CDBA. </code></pre> <p>There are four differences, hence three swaps, hence odd parity. </p>
0
2009-10-01T11:46:40Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
1,503,598
<p>Here is my tweak of your code</p> <ul> <li>Use list() to copy perm1 - this means you can pass tuples, etc into the function, making it more generic</li> <li>Use enumerate() in the for loop instead of len(..) and array lookups for neater code</li> <li>Make a perm1_map and keep it up to date to stop an expensive O(N) search on perm1, and an expensive list slice</li> <li>return the boolean directly rather than the if ... return True else return False</li> </ul> <p>Here is it</p> <pre><code>def arePermsEqualParity(perm0, perm1): """Check if 2 permutations are of equal parity. Assume that both permutation lists are of equal length and have the same elements. No need to check for these conditions. """ perm1 = list(perm1) ## copy this into a list so we don't mutate the original perm1_map = dict((v, i) for i,v in enumerate(perm1)) transCount = 0 for loc, p0 in enumerate(perm0): p1 = perm1[loc] if p0 != p1: sloc = perm1_map[p0] # Find position in perm1 perm1[loc], perm1[sloc] = p0, p1 # Swap in perm1 perm1_map[p0], perm1_map[p1] = sloc, loc # Swap the map transCount += 1 # Even number of transpositions means equal parity return (transCount % 2) == 0 </code></pre>
6
2009-10-01T12:14:01Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
1,504,565
<p>If we combine both permutations, the result will have even parity when each permutation has the same parity, and odd parity if they have different parity. So if we solve the <strong>parity problem</strong> it's trivial to compare two different permutations.</p> <p><strong>Parity</strong> can be determined as follows: pick an arbitrary element, find the position that the permutation moves this to, repeat until you get back to the one you started with. You have now found a cycle: the permutation rotates all these elements round by one position. You need one swap less than the number of elements in the cycle to undo it. Now pick another element you haven't dealt with yet and repeat until you've seen every element. Observe that in total you needed one swap per element minus one swap per cycle.</p> <p>Time complexity is O(N) in the size of the permutation. Note that although we have a loop within a loop, the inner loop can only ever iterate once for any element in the permutation.</p> <pre><code>def parity(permutation): permutation = list(permutation) length = len(permutation) elements_seen = [False] * length cycles = 0 for index, already_seen in enumerate(elements_seen): if already_seen: continue cycles += 1 current = index while not elements_seen[current]: elements_seen[current] = True current = permutation[current] return (length-cycles) % 2 == 0 def arePermsEqualParity(perm0, perm1): perm0 = list(perm0) return parity([perm0[i] for i in perm1]) </code></pre> <p>Also, just for fun, here's a much less efficient but much shorter implementation of the parity function based on the definition in Wikipedia (returning True for even and False for odd):</p> <pre><code>def parity(p): return sum( 1 for (x,px) in enumerate(p) for (y,py) in enumerate(p) if x&lt;y and px&gt;py )%2==0 </code></pre>
6
2009-10-01T15:15:13Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
1,512,146
<p>Here's slightly refactored <a href="http://stackoverflow.com/questions/1503072/how-to-check-if-permutations-have-equal-parity/1504565#1504565">Weeble's answer</a>:</p> <pre><code>def arePermsEqualParity(perm0, perm1): """Whether permutations are of equal parity.""" return parity(combine(perm0, perm1)) def combine(perm0, perm1): """Combine two permutations into one.""" return map(perm0.__getitem__, perm1) def parity(permutation): """Return even parity for the `permutation`.""" return (len(permutation) - ncycles(permutation)) % 2 == 0 def ncycles(permutation): """Return number of cycles in the `permutation`.""" ncycles = 0 seen = [False] * len(permutation) for i, already_seen in enumerate(seen): if not already_seen: ncycles += 1 # mark indices that belongs to the cycle j = i while not seen[j]: seen[j] = True j = permutation[j] return ncycles </code></pre>
2
2009-10-02T22:41:14Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
4,215,652
<p>The solution with the dictionary is bugged. This is the debug version:</p> <pre><code>def arePermsEqualParity(perm0, perm1): """Check if 2 permutations are of equal parity. Assume that both permutation lists are of equal length and have the same elements. No need to check for these conditions. """ perm1 = list(perm1) ## copy this into a list so we don't mutate the original perm1_map = dict((v, i) for i,v in enumerate(perm1)) transCount = 0 for loc, p0 in enumerate(perm0): p1 = perm1[loc] if p0 != p1: sloc = perm1_map[p0] # Find position in perm1 perm1[loc], perm1[sloc] = p0, p1 # Swap in perm1 perm1_map[p0], perm1_map[p1] = loc, sloc # Swap the map transCount += 1 # Even number of transpositions means equal parity return (transCount % 2) == 0 </code></pre> <p>The only differences is that the swap in the dictionary was not made correctly.</p>
2
2010-11-18T14:13:08Z
[ "python", "list", "permutation", "parity" ]
How to check if permutations have equal parity?
1,503,072
<p>I am looking for a way to check if 2 <strong>permutations</strong> (represented by lists) are of the <strong>same <a href="http://en.wikipedia.org/wiki/Parity%5Fof%5Fa%5Fpermutation">parity</a></strong>. Note that I am not interested if they are <em>even</em> or <em>odd</em> parity, just the equality.</p> <p>I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achieve the same in lesser, more elegant Python code.</p>
9
2009-10-01T10:11:59Z
6,271,461
<pre><code>def equalparity(p,q): return sum([p[q[i]] &gt; p[q[j]] for i in range(len(p)) for j in range(i)]) % 2 == 0 </code></pre>
0
2011-06-07T20:49:32Z
[ "python", "list", "permutation", "parity" ]
Dynamic column formatting in SQL - and a backend to store the formatting
1,503,621
<p>I'm trying to create a system in Python in which one can select a number of rows from a set of tables, which are to be formatted in a user-defined way. Let's say the table <code>a</code> has a set of columns, some of which include a <code>date</code> or <code>timestamp</code> value. The user-defined format for each column should be stored in another table, and queried and applied on the main query at runtime.</p> <p>Let me give you an example: There are different ways of formatting a date column, e.g. using</p> <pre><code>SELECT to_char(column, 'YYYY-MM-DD') FROM table; </code></pre> <p>in PostgreSQL. </p> <p>For example, I'd like the second parameter of the <code>to_char()</code> builtin to be queried dynamically from another table at runtime, and then applied if it has a value. </p> <p>Reading the definition from a table as such is not that much of a problem, rather than creating a database scheme which would receive data from a user interface from which a user can select which formatting instructions to apply to the different columns. The user should be able to pick the user's set of columns to be included in the user's query, as well as the user's user defined formatting for each column. </p> <p>I've been thinking about doing this in an elegant and efficient way for some days now, but to no avail. Having the user put in the user's desired definition in a text field and including it in a query would pretty much generate an invitation for SQL injection attacks (although I could use <code>escape()</code> functions), and storing every possible combination doesn't seem feasible to me either. </p>
1
2009-10-01T12:16:58Z
1,504,004
<p>It seems to me a <a href="http://www.google.com/search?q=postgresql+stored+procedures" rel="nofollow">stored procedure</a> or a sub-select would work well here, though I haven't tested it. Let's say you store a <code>date_format</code> for each user in the <code>users</code> table.</p> <pre><code>SELECT to_char((SELECT date_format FROM users WHERE users.id=123), column) FROM table; </code></pre> <p>Your mileage may vary.</p>
0
2009-10-01T13:34:32Z
[ "python", "sql", "database", "database-design", "postgresql" ]
Dynamic column formatting in SQL - and a backend to store the formatting
1,503,621
<p>I'm trying to create a system in Python in which one can select a number of rows from a set of tables, which are to be formatted in a user-defined way. Let's say the table <code>a</code> has a set of columns, some of which include a <code>date</code> or <code>timestamp</code> value. The user-defined format for each column should be stored in another table, and queried and applied on the main query at runtime.</p> <p>Let me give you an example: There are different ways of formatting a date column, e.g. using</p> <pre><code>SELECT to_char(column, 'YYYY-MM-DD') FROM table; </code></pre> <p>in PostgreSQL. </p> <p>For example, I'd like the second parameter of the <code>to_char()</code> builtin to be queried dynamically from another table at runtime, and then applied if it has a value. </p> <p>Reading the definition from a table as such is not that much of a problem, rather than creating a database scheme which would receive data from a user interface from which a user can select which formatting instructions to apply to the different columns. The user should be able to pick the user's set of columns to be included in the user's query, as well as the user's user defined formatting for each column. </p> <p>I've been thinking about doing this in an elegant and efficient way for some days now, but to no avail. Having the user put in the user's desired definition in a text field and including it in a query would pretty much generate an invitation for SQL injection attacks (although I could use <code>escape()</code> functions), and storing every possible combination doesn't seem feasible to me either. </p>
1
2009-10-01T12:16:58Z
1,504,076
<p>Pull the dates out as Unix timestamps and format them in Python:</p> <pre><code>SELECT DATE_PART('epoch', TIMESTAMP(my_col)) FROM my_table; my_date = datetime.datetime.fromtimestamp(row[0]) # Or equivalent for your toolkit </code></pre> <p>I've found a couple of advantages to this approach: unix timestamps are the most space-efficient common format (this approach is effectively language neutral) and because the language you're querying the database in is richer than the underlying database, giving you plenty of options if you start wanting to do friendlier formatting like "today", "yesterday", "last week", "June 23rd".</p> <p>I don't know what sort of application you're developing but if it's something like a web app which will be used by multiple people I'd also consider storing your database values in UTC so you can apply user-specific timezone settings when formatting without having to consider them for all of your database operations.</p>
0
2009-10-01T13:48:26Z
[ "python", "sql", "database", "database-design", "postgresql" ]
Fixture loading works with loaddata but fails silently in unit test in Django
1,504,255
<p>I can load the fixture file in my django application by using loaddata:</p> <pre><code>manage.py loaddata palamut </code></pre> <p>The fixture <code>palamut.yaml</code> is in the directory <code>palamut/fixtures/</code> </p> <p>I have a unit test module <code>service_tests.py</code> in <code>palamut/tests/</code>. Its content is here:</p> <pre><code>import unittest from palamut.models import * from palamut.service import * from palamut.pforms import * class ServiceTest(unittest.TestCase): fixtures = ['palamut.yaml'] def test_convert_vensim(self): game_definition = GameDefinition.objects.get(pk=1) </code></pre> <p>This unit test gives the following error:</p> <pre><code>DoesNotExist: GameDefinition matching query does not exist. </code></pre> <p>I debugged the script, and found out that the fixture is not loaded in the unit test module. </p> <p>Do you have any suggestions about the cause of this behavior?</p> <p>By the way, test logs don't contain anything related to fixture loading. </p>
4
2009-10-01T14:21:21Z
1,504,290
<p>Your TestCase should be an instance of django.test.TestCase, not unittest.TestCase</p>
9
2009-10-01T14:26:14Z
[ "python", "django", "unit-testing", "fixtures" ]
Fitting a bimodal distribution to a set of values
1,504,378
<p>Given a 1D array of values, what is the simplest way to figure out what the best fit bimodal distribution to it is, where each 'mode' is a normal distribution? Or in other words, how can you find the combination of two normal distributions that bests reproduces the 1D array of values?</p> <p>Specifically, I'm interested in implementing this in python, but answers don't have to be language specific.</p> <p>Thanks!</p>
6
2009-10-01T14:43:09Z
1,504,481
<p>I suggest using the awesome <a href="http://www.scipy.org/" rel="nofollow">scipy</a> package. It provides a few methods for optimisation.</p> <p>There's a big fat caveat with simply applying a pre-defined least square fit or something along those lines. </p> <p>Here are a few problems you will run into:</p> <ol> <li>Noise larger than second/both peaks.</li> <li>Partial peak - your data is cut of at one of the borders.</li> <li>Sampling - width of peaks are smaller than your sampled data.</li> <li>It isn't normal - you'll get some result ...</li> <li>Overlap - If peaks overlap you'll find that often one peak is fitted correctly but the second will apporach zero...</li> </ol>
0
2009-10-01T15:01:33Z
[ "python", "algorithm" ]
Fitting a bimodal distribution to a set of values
1,504,378
<p>Given a 1D array of values, what is the simplest way to figure out what the best fit bimodal distribution to it is, where each 'mode' is a normal distribution? Or in other words, how can you find the combination of two normal distributions that bests reproduces the 1D array of values?</p> <p>Specifically, I'm interested in implementing this in python, but answers don't have to be language specific.</p> <p>Thanks!</p>
6
2009-10-01T14:43:09Z
1,504,590
<p>What you are trying to do is called a Gaussian Mixture model. The standard approach to solving this is using Expectation Maximization, scipy svn includes a section on machine learning and em called <a href="http://scipy.org/scikits.html" rel="nofollow">scikits</a>. I use it a a fair bit.</p>
4
2009-10-01T15:20:00Z
[ "python", "algorithm" ]
Fitting a bimodal distribution to a set of values
1,504,378
<p>Given a 1D array of values, what is the simplest way to figure out what the best fit bimodal distribution to it is, where each 'mode' is a normal distribution? Or in other words, how can you find the combination of two normal distributions that bests reproduces the 1D array of values?</p> <p>Specifically, I'm interested in implementing this in python, but answers don't have to be language specific.</p> <p>Thanks!</p>
6
2009-10-01T14:43:09Z
4,597,393
<p>I am just trying to understand why one needs to fit a bimodal distributing for a 1D array? What are the advantages of doing this?</p>
0
2011-01-04T19:11:06Z
[ "python", "algorithm" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,739
<p>The <code>is</code> keyword is a test for object identity while <code>==</code> is a value comparison.</p> <p>If you use <code>is</code>, the result will be true if and only if the object is the same object. However, <code>==</code> will be true any time the values of the object are the same.</p>
77
2009-10-01T15:45:02Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,740
<p>I think it has to do with the fact that, when the 'is' comparison evaluates to false, two distinct objects are used. If it evaluates to true, that means internally it's using the same exact object and not creating a new one, possibly because you created them within a fraction of 2 or so seconds and because there isn't a large time gap in between it's optimized and uses the same object.</p> <p>This is why you should be using the equality operator <code>==</code>, not <code>is</code>, to compare the value of a string object.</p> <pre><code>&gt;&gt;&gt; s = 'one' &gt;&gt;&gt; s2 = 'two' &gt;&gt;&gt; s is s2 False &gt;&gt;&gt; s2 = s2.replace('two', 'one') &gt;&gt;&gt; s2 'one' &gt;&gt;&gt; s2 is s False &gt;&gt;&gt; </code></pre> <p>In this example, I made s2, which was a different string object previously equal to 'one' but it is not the same object as <code>s</code>, because the interpreter did not use the same object as I did not initially assign it to 'one', if I had it would have made them the same object.</p>
9
2009-10-01T15:45:07Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,742
<p><code>is</code> is identity testing, <code>==</code> is equality testing. what happens in your code would be emulated in the interpreter like this:</p> <pre><code>&gt;&gt;&gt; a = 'pub' &gt;&gt;&gt; b = ''.join(['p', 'u', 'b']) &gt;&gt;&gt; a == b True &gt;&gt;&gt; a is b False </code></pre> <p>so, no wonder they're not the same, right?</p> <p>In other words: <code>is</code> is the <code>id(a) == id(b)</code></p>
857
2009-10-01T15:45:20Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,756
<p>From my limited experience with python, <code>is</code> is used to compare two objects to see if they are the same object as opposed to two different objects with the same value. <code>==</code> is used to determine if the values are identical. </p> <p>Here is a good example:</p> <pre><code>&gt;&gt;&gt; s1 = u'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s1 is s2 False &gt;&gt;&gt; s1 == s2 True </code></pre> <p><code>s1</code> is a unicode string, and <code>s2</code> is a normal string. They are not the same type, but are the same value.</p>
13
2009-10-01T15:48:07Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,829
<p>I believe that this is known as "interned" strings. Python does this, so does Java, and so do C and C++ when compiling in optimized modes.</p> <p>If you use two identical strings, instead of wasting memory by creating two string objects, all interned strings with the same contents point to the same memory.</p> <p>This results in the Python "is" operator returning True because two strings with the same contents are pointing at the same string object. This will also happen in Java and in C.</p> <p>This is only useful for memory savings though. You cannot rely on it to test for string equality, because the various interpreters and compilers and JIT engines cannot always do it.</p>
7
2009-10-01T15:59:38Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,848
<p>SilentGhost and others are correct here. <code>is</code> is used for <em>identity</em> comparison, while <code>==</code> is used for <em>equality</em> comparison.</p> <p>The reason this works interactively is that (most) string literals are <a href="http://en.wikipedia.org/wiki/String_interning">interned</a> by default. From Wikipedia:</p> <blockquote> <p>Interned strings speed up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on hash tables with string keys. Without interning, checking that two different strings are equal involves examining every character of both strings. This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fills up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.</p> </blockquote> <p>So, when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't <em>always</em> happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)</p> <p>Since in your interactive session both strings are actually stored in the same memory location, they have the same <em>identity</em>, so the <code>is</code> operator works as expected. But if you construct a string by some other method (even if that string contains <em>exactly</em> the same characters), then the string may be <em>equal</em>, but it is not <em>the same string</em> -- that is, it has a different <em>identity</em>, because it is stored in a different place in memory.</p>
285
2009-10-01T16:02:14Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,504,870
<p>One last thing to note, you may use the intern function to ensure that you're getting a reference to the same string:</p> <pre><code>&gt;&gt;&gt; a = intern('a') &gt;&gt;&gt; a2 = intern('a') &gt;&gt;&gt; a is a2 True </code></pre> <p>As pointed out above, you should probably not be doing is to determine equality on strings. But this may be helpful to know if you have some kind of weird requirement to use <code>is</code>.</p> <p>Note that the intern function got moved from being a built in function to being in the module <code>sys</code> for Python 3.</p>
34
2009-10-01T16:04:48Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,505,189
<p>If you're not sure what you're doing, use the '=='. If you have a little more knowledge about it you can use 'is' for known objects like 'None'.</p> <p>Otherwise you'll end up wondering why things doesn't work and why this happens:</p> <pre><code>&gt;&gt;&gt; a = 1 &gt;&gt;&gt; b = 1 &gt;&gt;&gt; b is a True &gt;&gt;&gt; a = 6000 &gt;&gt;&gt; b = 6000 &gt;&gt;&gt; b is a False </code></pre> <p>I'm not even sure if some things are guaranteed to stay the same between different python versions/implementations.</p>
17
2009-10-01T16:57:09Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
1,505,779
<p>This is a side note, but in idiomatic python, you will often see things like:</p> <pre><code>if x is None: # some clauses </code></pre> <p>This is safe, because <a href="http://docs.python.org/library/stdtypes.html#the-null-object">there is guaranteed to be one instance of the Null Object (i.e., None)</a>.</p>
18
2009-10-01T18:51:32Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
16,269,793
<p><code>is</code> is identity testing, <code>==</code> is equality testing. What this means is that <code>is</code> is a way to check whether two things are the <em>same</em> things, or just equivalent. </p> <p>Say you've got a simple <code>person</code> object. If it is named 'Jack' and is '23' years old, it's equivalent to another 23yr old Jack, but its not the same person.</p> <pre><code>class Person(object): def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return self.name == other.name and self.age == other.age jack1 = Person('Jack', 23) jack2 = Person('Jack', 23) jack1 == jack2 #True jack1 is jack2 #False </code></pre> <p>They're the same age, but they're not the same instance of person. A string might be equivalent to another, but it's not the same object.</p>
18
2013-04-29T00:56:52Z
[ "python", "string", "comparison" ]
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
1,504,717
<p>I've got a Python program where two variables are set to the value <code>'public'</code>. In a conditional expression I have the comparison <code>var1 is var2</code> which fails, but if I change it to <code>var1 == var2</code> it returns <code>True</code>.</p> <p>Now if I open my Python interpreter and do the same "is" comparison, it succeeds.</p> <pre><code>&gt;&gt;&gt; s1 = 'public' &gt;&gt;&gt; s2 = 'public' &gt;&gt;&gt; s2 is s1 True </code></pre> <p>What am I missing here?</p>
593
2009-10-01T15:40:14Z
25,208,597
<p>I am answering the question even though the question is to old because no answers above quotes the language reference</p> <p>Actually the is operator checks for identity and == operator checks for equality,</p> <p><strong><em>From Language Reference:</em></strong></p> <p>Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations <strong>that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed</strong>. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)</p> <p>so from above statement we can infer that the strings which is an immutable type may fail when checked with "is" and may checked succeed when checked with "is"</p> <p>The same applies for int,tuple which are also immutable types</p>
7
2014-08-08T17:04:58Z
[ "python", "string", "comparison" ]
Automatically remove *.pyc files and otherwise-empty directories when I check out a new branch
1,504,724
<p>So here's an interesting situation when using git and python, and I'm sure it happens for other situations as well.</p> <p>Let's say I make a git repo with a folder /foo/. In that folder I put /foo/program.py. I run program.py and program.pyc is created. I have *.pyc in the .gitignore file, so git doesn't track it. </p> <p>Now let's say I make another branch, dev. In this dev branch, I remove the /foo/ folder entirely.</p> <p>Now I switch back to the master branch, and /foo/ reappears. I run the program.py and the program.pyc file reappears. All is well.</p> <p>I switch back to my dev branch. The /foo/ directory should disappear. It only exists in the master branch, not the dev branch. However, it is still there. Why? Because the ignored program.pyc file prevents the folder from being deleted when switching branches.</p> <p>The solution to this problem is to recursively delete all *.pyc files before switching branches. I can do that easily with this command.</p> <pre><code>find . -name "*.pyc" -exec rm '{}' ';' </code></pre> <p>The problem is that it is annoying to have to remember to do this almost every time I change branches. I could make an alias for this command, but then I still have to remember to type it every time I change branches. I could also make an alias for git-branch, but that's no good either. The git branch command does other things besides just change branches, and I don't want to delete all pyc files every time I use it. Heck, I might even use it in a non-python repo, then what?</p> <p>Is there a way to set a git hook that only executes when I change branches? Or is there some other way to set all *.pyc files to get erased whenever I switch branches?</p>
48
2009-10-01T15:41:22Z
1,504,760
<p>There is a <code>post-checkout</code> hook, to be placed in .git/hooks/post-checkout. There's probably a sample there, possibly named .sample or possibly not executable, depending on your git version. Short description: it gets three parameters, the previous HEAD, the new HEAD, and a flag which is 1 if the branch changed and 0 if it was merely a file checkout. See <code>man githooks</code> for more information! You should be able to write a shell script to do what you need and put it there.</p> <p>Edit: I realize you're looking to do this pre-checkout, so that the checkout automatically cleans up directories which become empty. There's no pre-checkout hook, though, so you'll have to use your script to remove the directories too.</p> <p>Another note: Aliases are part of gitconfig, which can be local to a repository (in .git/config, not ~/.gitconfig). If you choose to do this with aliases (for git-checkout, not git-branch) you can easily put them only in python-related repositories. Also in this case, I'd make an alias specifically for this purpose (e.g. cc for checkout clean). You can still use checkout (or another aliased form of it) if you don't want to clean up pyc files.</p>
40
2009-10-01T15:48:41Z
[ "git", "python", "bash" ]
Automatically remove *.pyc files and otherwise-empty directories when I check out a new branch
1,504,724
<p>So here's an interesting situation when using git and python, and I'm sure it happens for other situations as well.</p> <p>Let's say I make a git repo with a folder /foo/. In that folder I put /foo/program.py. I run program.py and program.pyc is created. I have *.pyc in the .gitignore file, so git doesn't track it. </p> <p>Now let's say I make another branch, dev. In this dev branch, I remove the /foo/ folder entirely.</p> <p>Now I switch back to the master branch, and /foo/ reappears. I run the program.py and the program.pyc file reappears. All is well.</p> <p>I switch back to my dev branch. The /foo/ directory should disappear. It only exists in the master branch, not the dev branch. However, it is still there. Why? Because the ignored program.pyc file prevents the folder from being deleted when switching branches.</p> <p>The solution to this problem is to recursively delete all *.pyc files before switching branches. I can do that easily with this command.</p> <pre><code>find . -name "*.pyc" -exec rm '{}' ';' </code></pre> <p>The problem is that it is annoying to have to remember to do this almost every time I change branches. I could make an alias for this command, but then I still have to remember to type it every time I change branches. I could also make an alias for git-branch, but that's no good either. The git branch command does other things besides just change branches, and I don't want to delete all pyc files every time I use it. Heck, I might even use it in a non-python repo, then what?</p> <p>Is there a way to set a git hook that only executes when I change branches? Or is there some other way to set all *.pyc files to get erased whenever I switch branches?</p>
48
2009-10-01T15:41:22Z
1,810,193
<p>Just copying and updating a good solution by Apreche that was buried in the comments:</p> <p>Save this shell script to the file <code>/path/to/repo/.git/hooks/post-checkout</code>, and make it executable.</p> <pre><code>#! /bin/sh # Start from the repository root. cd ./$(git rev-parse --show-cdup) # Delete .pyc files and empty directories. find . -name "*.pyc" -delete find . -type d -empty -delete </code></pre>
33
2009-11-27T18:46:39Z
[ "git", "python", "bash" ]
Automatically remove *.pyc files and otherwise-empty directories when I check out a new branch
1,504,724
<p>So here's an interesting situation when using git and python, and I'm sure it happens for other situations as well.</p> <p>Let's say I make a git repo with a folder /foo/. In that folder I put /foo/program.py. I run program.py and program.pyc is created. I have *.pyc in the .gitignore file, so git doesn't track it. </p> <p>Now let's say I make another branch, dev. In this dev branch, I remove the /foo/ folder entirely.</p> <p>Now I switch back to the master branch, and /foo/ reappears. I run the program.py and the program.pyc file reappears. All is well.</p> <p>I switch back to my dev branch. The /foo/ directory should disappear. It only exists in the master branch, not the dev branch. However, it is still there. Why? Because the ignored program.pyc file prevents the folder from being deleted when switching branches.</p> <p>The solution to this problem is to recursively delete all *.pyc files before switching branches. I can do that easily with this command.</p> <pre><code>find . -name "*.pyc" -exec rm '{}' ';' </code></pre> <p>The problem is that it is annoying to have to remember to do this almost every time I change branches. I could make an alias for this command, but then I still have to remember to type it every time I change branches. I could also make an alias for git-branch, but that's no good either. The git branch command does other things besides just change branches, and I don't want to delete all pyc files every time I use it. Heck, I might even use it in a non-python repo, then what?</p> <p>Is there a way to set a git hook that only executes when I change branches? Or is there some other way to set all *.pyc files to get erased whenever I switch branches?</p>
48
2009-10-01T15:41:22Z
26,320,535
<p>My solution is <strong>more compatible with git</strong>: Git removes only enpty directories where any file has been deleted by checkout. It doesn't search the complete workcopy tree. That is useful for big repositories or repositories with a very big ignored tree, like virtual environments by <a href="https://testrun.org/tox/" rel="nofollow">tox</a> package for testing many different with Python versions etc. </p> <p>My first implementation explains the principle very clearly: Only pyc files <strong>related to files under version control</strong> are cleaned. It's for reasons of efficiency and unwanted side effects.</p> <pre><code>#!/bin/bash # A hook that removes orphan "*.pyc" files for "*.py" beeing deleted. # It doesn not clean anything e.g. for .py files deleted manually. oldrev="$1" newrev="$2" # ignored param: branchcheckout="$3" for x in $(git diff --name-only --diff-filter=DR $oldrev..$newrev | grep "\.py$") do if test -a ${x}c &amp;&amp; ! test -a ${x}; then rm ${x}c fi done </code></pre> <p>The <code>post-checkout</code> hook receive the three useful parameters that allow to get known exactly which files have been deleted by the git checkout, without searching the complete tree.</p> <p>After reading the question I rewrote my hook code to Python and extended it according to your requirements about empty directories.</p> <p>My complete short <strong>source code</strong> <em>(Python)</em> is in<br> <strong><a href="https://gist.github.com/hynekcer/476a593a3fc584278b87#file-post-checkout-py" rel="nofollow">https://gist.github.com/hynekcer/476a593a3fc584278b87#file-post-checkout-py</a></strong></p> <p>The doc string:</p> <pre><code>""" A hook to git that removes orphan files "*.pyc" and "*.pyo" for "*.py" beeing deleted or renamed by git checkout. It also removes their empty parent directories. Nothing is cleaned for .py files deleted manually or by "git rm" etc. Place it to "my_local_repository/.git/hooks/post-checkout" and make it executable """ </code></pre> <ul> <li><p>The problem with *.pyc files is <strong>not important for Python 3</strong>, because *.pyc files in <code>__pycache__</code> can not be executed without the related *.py* file in its parent directory.</p></li> <li><p>No change directory is necessary, because hooks are started everytimes in the root of the repository.</p></li> <li>Cache directories for compiled code <code>__pycache__</code> are cleaned completely, because they are never important (don't take part in any binary distribution) and also for high efficiency because deleting by parts <code>__pycache__/some_name.*.pyc</code> could be slow.</li> </ul>
2
2014-10-12T00:09:39Z
[ "git", "python", "bash" ]
Automatically remove *.pyc files and otherwise-empty directories when I check out a new branch
1,504,724
<p>So here's an interesting situation when using git and python, and I'm sure it happens for other situations as well.</p> <p>Let's say I make a git repo with a folder /foo/. In that folder I put /foo/program.py. I run program.py and program.pyc is created. I have *.pyc in the .gitignore file, so git doesn't track it. </p> <p>Now let's say I make another branch, dev. In this dev branch, I remove the /foo/ folder entirely.</p> <p>Now I switch back to the master branch, and /foo/ reappears. I run the program.py and the program.pyc file reappears. All is well.</p> <p>I switch back to my dev branch. The /foo/ directory should disappear. It only exists in the master branch, not the dev branch. However, it is still there. Why? Because the ignored program.pyc file prevents the folder from being deleted when switching branches.</p> <p>The solution to this problem is to recursively delete all *.pyc files before switching branches. I can do that easily with this command.</p> <pre><code>find . -name "*.pyc" -exec rm '{}' ';' </code></pre> <p>The problem is that it is annoying to have to remember to do this almost every time I change branches. I could make an alias for this command, but then I still have to remember to type it every time I change branches. I could also make an alias for git-branch, but that's no good either. The git branch command does other things besides just change branches, and I don't want to delete all pyc files every time I use it. Heck, I might even use it in a non-python repo, then what?</p> <p>Is there a way to set a git hook that only executes when I change branches? Or is there some other way to set all *.pyc files to get erased whenever I switch branches?</p>
48
2009-10-01T15:41:22Z
26,325,326
<p>Another option is to not solve this as a git problem at all, but as a Python problem. You can use the <code>PYTHONDONTWRITEBYTECODE</code> environment variable to prevent Python from writing .pyc files in the first place. Then you won't have anything to clean up when you switch branches.</p>
3
2014-10-12T12:54:09Z
[ "git", "python", "bash" ]
Communicate with backend job from web server or web page
1,504,729
<p>I have an "appliance" (for lack of better description) running linux.</p> <p>Currently I ssh into the box to launch jobs. This isn't friendly enough for my users, so I'm putting together a simple web UI to launch the script. A job runs for anywhere from 10 seconds to several hours. The web UI needs to reflect the status of the job.</p> <p>I've solved similar problems in the past by running a daemon on the server that watches a spool directory (or db table) for new job requests, spawns a process, monitors the process, and provides info for the web UI in a db table or status file. The web UI then drops job requests into a spool dir (db) and occasionally check the status file (db). This might be overkill for this task.</p> <p>For the current task, I am considering spawning the job from the cgi and occasionally checking a status file that the job writes as it progresses or exits.</p> <p>My question: is there a better (simpler/faster-to-write/more robust) way to do this? Are there existing patterns or tools that I should know about?</p> <p>(Python solutions are ideal.)</p> <p>Thanks.</p>
0
2009-10-01T15:42:48Z
1,504,839
<p>I'm not sure if I understood your problem correctly, but I assume you have multiple "jobs" that can run simultaneously and want them to show on web page whether they are complete or not?</p> <p>When launching a job the web page (python &amp; mod_wsgi for example) would launch a python script that would enter the job into, let's say sqlite database and run the job, once the job completes, the script updates the entry for the job so that it is marked as complete</p> <p>The status page would just show the stuff from the sqlite.</p> <p>What you want to put in to the DB in addition to the job ID and perhaps start/end times depends on what you want to show on your job status web page</p> <p>On a sidenote - if the "jobs" are compilations, meet <a href="http://hudson-ci.org/" rel="nofollow">Hudson</a></p>
0
2009-10-01T16:00:52Z
[ "python", "linux", "backend" ]
Communicate with backend job from web server or web page
1,504,729
<p>I have an "appliance" (for lack of better description) running linux.</p> <p>Currently I ssh into the box to launch jobs. This isn't friendly enough for my users, so I'm putting together a simple web UI to launch the script. A job runs for anywhere from 10 seconds to several hours. The web UI needs to reflect the status of the job.</p> <p>I've solved similar problems in the past by running a daemon on the server that watches a spool directory (or db table) for new job requests, spawns a process, monitors the process, and provides info for the web UI in a db table or status file. The web UI then drops job requests into a spool dir (db) and occasionally check the status file (db). This might be overkill for this task.</p> <p>For the current task, I am considering spawning the job from the cgi and occasionally checking a status file that the job writes as it progresses or exits.</p> <p>My question: is there a better (simpler/faster-to-write/more robust) way to do this? Are there existing patterns or tools that I should know about?</p> <p>(Python solutions are ideal.)</p> <p>Thanks.</p>
0
2009-10-01T15:42:48Z
1,504,890
<p>I do this in a number of projects. A web-app (mostly Python/CGI) that spawns a separate python script (using subprocess) which instantly <a href="http://pypi.python.org/pypi/python-daemon/1.5" rel="nofollow">daemonizes itself</a> to do the work. The web-app then continues to issue AJAX requests to check on the daemon process progress (I use simple txt files for communication, database would probably be better). One nice touch is to have the daemon email the end user once it finishes (with a link to retrieve results). This way the user can close their web browser on those jobs that take hours.</p>
2
2009-10-01T16:07:06Z
[ "python", "linux", "backend" ]
Python as a Windows Watchdog
1,504,794
<p>Hi I'm considering using Python to make a watchdog app on Windows XP that will perform the following actions:</p> <ul> <li>Restart Windows at a given time.</li> <li>Start an exe application.</li> <li>Run a timer to check: is an application still running</li> </ul> <p>I know of the existence of PyWin32, but I hear that the API is not complete. So my question is can Python perform these actions on Windows? </p>
2
2009-10-01T15:54:13Z
1,504,889
<p>Since you only want this to work on Windows, the easiest way to do that is to use <a href="http://docs.python.org/library/os.html" rel="nofollow">os.system</a> and make system-specific calls from within a Python program. </p> <p>Use the built in Windows tool to run programs at a particular time.</p> <p>Use shutdown -r to reboot Windows. </p> <p>Use tasklist to list all processes, then search that list. If you need to manipulate a process as well, the best way I know of is the COM method described <a href="http://74.125.113.132/search?q=cache%3A8BxqRjSz9kYJ%3Amail.python.org/pipermail/python-list/2000-May/035338.html+windows+find+process&amp;cd=2&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="nofollow">here</a>.</p>
2
2009-10-01T16:07:03Z
[ "python", "winapi" ]
Visual representation of nodes in Python
1,505,131
<p>I have data that I want to represent visually. The actual data is a tree made up of nodes. Each node has a bunch of data associated with it, but as far as this question goes, I just want a way to represent a tree visually using Python. Any ideas?</p> <p>The different solutions that popped in my head were to use a GUI library like WxPython or PyQT, or maybe even a PDF generator like ReportLab. I'm hoping there's a library out there that deals closer with data so that I don't have to think out the plotting locations of all the nodes.</p>
1
2009-10-01T16:48:05Z
1,505,155
<p>Not sure if this is applicable to your situation, but have you looked at <a href="http://www.graphviz.org/" rel="nofollow">graphviz</a>? It has decent python bindings for it and I've used it for visualizing dependencies which sometimes end up looking like trees.</p>
5
2009-10-01T16:52:52Z
[ "python" ]
Visual representation of nodes in Python
1,505,131
<p>I have data that I want to represent visually. The actual data is a tree made up of nodes. Each node has a bunch of data associated with it, but as far as this question goes, I just want a way to represent a tree visually using Python. Any ideas?</p> <p>The different solutions that popped in my head were to use a GUI library like WxPython or PyQT, or maybe even a PDF generator like ReportLab. I'm hoping there's a library out there that deals closer with data so that I don't have to think out the plotting locations of all the nodes.</p>
1
2009-10-01T16:48:05Z
1,505,330
<p>Consider using a textual representation of the tree. Otherwise, I'd go with graphviz (dotty, actually).</p> <pre><code>[root] +------child1 +------child2 +-------child3 +-------child4 </code></pre> <p>To show the same tree in graphviz, put this in a text file:</p> <pre><code>digraph graphname { root -&gt; child1; root -&gt; child2; child2 -&gt; child3; child2 -&gt; child4; } </code></pre> <p>Then run dotty on it, or your tool or choice.</p>
0
2009-10-01T17:31:43Z
[ "python" ]
Visual representation of nodes in Python
1,505,131
<p>I have data that I want to represent visually. The actual data is a tree made up of nodes. Each node has a bunch of data associated with it, but as far as this question goes, I just want a way to represent a tree visually using Python. Any ideas?</p> <p>The different solutions that popped in my head were to use a GUI library like WxPython or PyQT, or maybe even a PDF generator like ReportLab. I'm hoping there's a library out there that deals closer with data so that I don't have to think out the plotting locations of all the nodes.</p>
1
2009-10-01T16:48:05Z
1,505,746
<p>Instead of using graphviz directly, consider using the visualization tools included in <a href="http://networkx.lanl.gov/" rel="nofollow">NetworkX</a>. The graph objects there are excellent for many purposes.</p>
2
2009-10-01T18:45:42Z
[ "python" ]
Python: json.loads chokes on escapes
1,505,454
<p>I have an application that is sending a JSON object (formatted with Prototype) to an ASP server. On the server, the Python 2.6 "json" module tries to loads() the JSON, but it's choking on some combination of backslashes. Observe:</p> <pre><code>&gt;&gt;&gt; s '{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' &gt;&gt;&gt; tmp = json.loads(s) Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; {... blah blah blah...} File "C:\Python26\lib\json\decoder.py", line 155, in JSONString return scanstring(match.string, match.end(), encoding, strict) ValueError: Invalid \escape: line 1 column 58 (char 58) &gt;&gt;&gt; s[55:60] u'ost\\d' </code></pre> <p>So column 58 is the escaped-backslash. I thought this WAS properly escaped! UNC is <code>\\host\dir\file.exe</code>, so I just doubled up on slashes. But apparently this is no good. Can someone assist? As a last resort I'm considering converting the \ to / and then back again, but this seems like a real hack to me.</p> <p>Thanks in advance!</p>
11
2009-10-01T17:53:17Z
1,505,477
<p>The correct json is:</p> <pre><code>r'{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' </code></pre> <p>Note the letter <code>r</code> if you omit it you need to escape <code>\</code> for Python too.</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; d = json.loads(s) &gt;&gt;&gt; d.keys() [u'FileExists', u'Path', u'Version'] &gt;&gt;&gt; d.values() [True, u'\\\\host\\dir\\file.exe', u'4.3.2.1'] </code></pre> <p>Note the difference:</p> <pre><code>&gt;&gt;&gt; repr(d[u'Path']) "u'\\\\\\\\host\\\\dir\\\\file.exe'" &gt;&gt;&gt; str(d[u'Path']) '\\\\host\\dir\\file.exe' &gt;&gt;&gt; print d[u'Path'] \\host\dir\file.exe </code></pre> <p>Python REPL prints by default the <code>repr(obj)</code> for an object <code>obj</code>:</p> <pre><code>&gt;&gt;&gt; class A: ... __str__ = lambda self: "str" ... __repr__ = lambda self: "repr" ... &gt;&gt;&gt; A() repr &gt;&gt;&gt; print A() str </code></pre> <p>Therefore your original <code>s</code> string is not properly escaped for JSON. It contains unescaped <code>'\d'</code> and <code>'\f'</code>. <code>print s</code> must show <code>'\\d'</code> otherwise it is not correct JSON.</p> <p>NOTE: JSON string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes (<a href="http://json.org">json.org</a>). I've skipped encoding issues (namely, transformation from byte strings to unicode and vice versa) in the above examples.</p>
16
2009-10-01T17:58:41Z
[ "python", "json", "escaping" ]
Python: json.loads chokes on escapes
1,505,454
<p>I have an application that is sending a JSON object (formatted with Prototype) to an ASP server. On the server, the Python 2.6 "json" module tries to loads() the JSON, but it's choking on some combination of backslashes. Observe:</p> <pre><code>&gt;&gt;&gt; s '{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' &gt;&gt;&gt; tmp = json.loads(s) Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; {... blah blah blah...} File "C:\Python26\lib\json\decoder.py", line 155, in JSONString return scanstring(match.string, match.end(), encoding, strict) ValueError: Invalid \escape: line 1 column 58 (char 58) &gt;&gt;&gt; s[55:60] u'ost\\d' </code></pre> <p>So column 58 is the escaped-backslash. I thought this WAS properly escaped! UNC is <code>\\host\dir\file.exe</code>, so I just doubled up on slashes. But apparently this is no good. Can someone assist? As a last resort I'm considering converting the \ to / and then back again, but this seems like a real hack to me.</p> <p>Thanks in advance!</p>
11
2009-10-01T17:53:17Z
1,505,593
<pre><code>&gt;&gt;&gt; s '{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' &gt;&gt;&gt; print s {"FileExists": true, "Version": "4.3.2.1", "Path": "\\host\dir\file.exe"} </code></pre> <p>You've not actually escaped the string, so it's trying to parse invalid escape codes like <code>\d</code> or <code>\f</code>. Consider using a well-tested JSON encoder, such as <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="nofollow">json2.js</a>.</p>
1
2009-10-01T18:19:26Z
[ "python", "json", "escaping" ]
Python: json.loads chokes on escapes
1,505,454
<p>I have an application that is sending a JSON object (formatted with Prototype) to an ASP server. On the server, the Python 2.6 "json" module tries to loads() the JSON, but it's choking on some combination of backslashes. Observe:</p> <pre><code>&gt;&gt;&gt; s '{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' &gt;&gt;&gt; tmp = json.loads(s) Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; {... blah blah blah...} File "C:\Python26\lib\json\decoder.py", line 155, in JSONString return scanstring(match.string, match.end(), encoding, strict) ValueError: Invalid \escape: line 1 column 58 (char 58) &gt;&gt;&gt; s[55:60] u'ost\\d' </code></pre> <p>So column 58 is the escaped-backslash. I thought this WAS properly escaped! UNC is <code>\\host\dir\file.exe</code>, so I just doubled up on slashes. But apparently this is no good. Can someone assist? As a last resort I'm considering converting the \ to / and then back again, but this seems like a real hack to me.</p> <p>Thanks in advance!</p>
11
2009-10-01T17:53:17Z
37,805,536
<p>Since the exception gives you the index of the offending escape character, this little hack I developed might be nice :)</p> <pre><code>def fix_JSON(json_message=None): result = None try: result = json.loads(json_message) except Exception as e: # Find the offending character index: idx_to_replace = int(e.message.split(' ')[-1].replace(')','')) # Remove the offending character: json_message = list(json_message) json_message[idx_to_replace] = ' ' new_message = ''.join(json_message) return fix_JSON(json_message=new_message) return result </code></pre>
1
2016-06-14T07:25:18Z
[ "python", "json", "escaping" ]
PHP Import Foreign Class' Method into MyClass
1,505,621
<p>Wondering if this is possible in PHP Land:</p> <p>Let's say I have a class as follows:</p> <pre><code>class myClass{ var $myVar; ... myMethod(){ $this-&gt;myVar = 10; } } </code></pre> <p>and another class:</p> <pre><code>class anotherClass { ... addFive(){ $this-&gt;myVar += 5; } } </code></pre> <p>The 'anotherClass' is 3500 lines long and I just want the single 'addFive' method to use in myClass. </p> <ul> <li>Is there a way I can import the function and be able to call it in my class and the $this would reference the myClass object?</li> <li>Is this good/bad practice?</li> <li>(optional) How does this work in Python? (Just curious as I'm starting to learn Python)</li> </ul>
0
2009-10-01T18:24:25Z
1,505,645
<p>If your myClass <a href="http://uk.php.net/manual/en/language.oop5.inheritance.php" rel="nofollow">extends</a> anotherClass it inherits all the methods and properties of anotherClass (except those marked private).</p> <pre><code>class AnotherClass { protected $myVar; public function addFive(){ $this-&gt;myVar += 5; } } class MyClass extends AnotherClass { public function __construct() { $this-&gt;myVar = 0; } public function myMethod(){ $this-&gt;myVar = 10; } } $m = new MyClass; $m-&gt;myMethod(); $m-&gt;addFive(); var_dump($m); </code></pre> <p>prints</p> <pre><code>object(MyClass)#1 (1) { ["myVar":protected]=&gt; int(15) } </code></pre>
0
2009-10-01T18:29:38Z
[ "php", "python", "oop", "closures", "anonymous-methods" ]
PHP Import Foreign Class' Method into MyClass
1,505,621
<p>Wondering if this is possible in PHP Land:</p> <p>Let's say I have a class as follows:</p> <pre><code>class myClass{ var $myVar; ... myMethod(){ $this-&gt;myVar = 10; } } </code></pre> <p>and another class:</p> <pre><code>class anotherClass { ... addFive(){ $this-&gt;myVar += 5; } } </code></pre> <p>The 'anotherClass' is 3500 lines long and I just want the single 'addFive' method to use in myClass. </p> <ul> <li>Is there a way I can import the function and be able to call it in my class and the $this would reference the myClass object?</li> <li>Is this good/bad practice?</li> <li>(optional) How does this work in Python? (Just curious as I'm starting to learn Python)</li> </ul>
0
2009-10-01T18:24:25Z
1,505,668
<p>A better approach would be to move the complex method into its own class. Then both of your classes can instantiate it, pass any necessary data, and call the method.</p>
2
2009-10-01T18:33:06Z
[ "php", "python", "oop", "closures", "anonymous-methods" ]
PHP Import Foreign Class' Method into MyClass
1,505,621
<p>Wondering if this is possible in PHP Land:</p> <p>Let's say I have a class as follows:</p> <pre><code>class myClass{ var $myVar; ... myMethod(){ $this-&gt;myVar = 10; } } </code></pre> <p>and another class:</p> <pre><code>class anotherClass { ... addFive(){ $this-&gt;myVar += 5; } } </code></pre> <p>The 'anotherClass' is 3500 lines long and I just want the single 'addFive' method to use in myClass. </p> <ul> <li>Is there a way I can import the function and be able to call it in my class and the $this would reference the myClass object?</li> <li>Is this good/bad practice?</li> <li>(optional) How does this work in Python? (Just curious as I'm starting to learn Python)</li> </ul>
0
2009-10-01T18:24:25Z
1,505,727
<p>The easiest way to do this is have one class extend the other</p> <pre><code>class myClass extends anotherClass { } </code></pre> <p>The myClass class now has access to all the methods of anotherClass that are public or protected.</p> <p>If you only want the class to have <strong>one</strong> method of the other, or it's not practical to have one class extends from the other, there's nothing built into PHP that will allow you to do this. The concept you're looking to Google for is "Mixin", as in Mix In one class's functionality with another. There's an <a href="http://www.jansch.nl/2006/08/23/mixins-in-php/" rel="nofollow">article or two</a> on some patterns you could try to achieve this functionality in PHP, but I've never tried it myself.</p> <p>Good idea/Bad Idea? Once you have the technique down it's convenient and useful, but costs you in performance and makes it harder for a newcomer to grok what you're doing with your code, especially (but not limited to) someone less familiar with OO concepts. </p>
2
2009-10-01T18:41:57Z
[ "php", "python", "oop", "closures", "anonymous-methods" ]
Network programming abstraction, decomposition
1,505,744
<p>I have a problem as follows:</p> <p>Server process 1</p> <ul> <li>Constantly sends updates that occur to a datastore</li> </ul> <p>Server process 2</p> <ul> <li>Clients contact the server, which queries the datastore, and returns a result</li> </ul> <p>The thing is, the results that process 1 and process 2 are sending back the client are totally different and unrelated.</p> <p>How does one decompose this? Do you just have one process constantly sending data, and define the protocol to have a bit which corresponds to whether the return type is 1 or 2?</p> <p>Do you have two processes? How do they share the datastore then (it is just a structure not a database)?</p> <p>Thanks!</p>
0
2009-10-01T18:45:27Z
1,506,213
<p>Why not use a database instead of "just a structure"? Both relational and non-relational DBs offer many practical advantages (separate processes using them, take care of replication [[and/or snapshots, backups, ...]], rich functionality if you need it for the "queries", and so on, and so forth).</p> <p>Worst case, the "just a structure" can be handled by a third process that's entirely dedicated to it (basically mimicking what any DB engine would offer -- though the engine would probably do it better and faster;-), allowing you to at least keep a good decomposition (with the two server processes both interacting with the "datastore process").</p>
0
2009-10-01T20:16:28Z
[ "python", "networking", "network-programming", "twisted" ]
Network programming abstraction, decomposition
1,505,744
<p>I have a problem as follows:</p> <p>Server process 1</p> <ul> <li>Constantly sends updates that occur to a datastore</li> </ul> <p>Server process 2</p> <ul> <li>Clients contact the server, which queries the datastore, and returns a result</li> </ul> <p>The thing is, the results that process 1 and process 2 are sending back the client are totally different and unrelated.</p> <p>How does one decompose this? Do you just have one process constantly sending data, and define the protocol to have a bit which corresponds to whether the return type is 1 or 2?</p> <p>Do you have two processes? How do they share the datastore then (it is just a structure not a database)?</p> <p>Thanks!</p>
0
2009-10-01T18:45:27Z
1,506,347
<p>If you can restrict yourself to Twisted, I recommend to use <a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html" rel="nofollow">Perspective Broker</a>. It's essentially an RPC system, and doesn't care much about the notion of "client" and "server" - either the initiator of a TCP connection or the responder can start RPC calls in PB. </p> <p>So server 1 would accept registration calls with a callback object, and call the callback whenever it has new data available. Server 2 provides various RPC operations as clients require them. If they operate on the very same data, I would put both servers into a single process.</p>
1
2009-10-01T20:41:30Z
[ "python", "networking", "network-programming", "twisted" ]
Network programming abstraction, decomposition
1,505,744
<p>I have a problem as follows:</p> <p>Server process 1</p> <ul> <li>Constantly sends updates that occur to a datastore</li> </ul> <p>Server process 2</p> <ul> <li>Clients contact the server, which queries the datastore, and returns a result</li> </ul> <p>The thing is, the results that process 1 and process 2 are sending back the client are totally different and unrelated.</p> <p>How does one decompose this? Do you just have one process constantly sending data, and define the protocol to have a bit which corresponds to whether the return type is 1 or 2?</p> <p>Do you have two processes? How do they share the datastore then (it is just a structure not a database)?</p> <p>Thanks!</p>
0
2009-10-01T18:45:27Z
1,507,023
<p>It sounds like you want to stream your series of ints "somewhere" and also collect them in a datastore. In my system I am streaming sensor readings into a database and also allowing them to go directly to web clients, giving them live power readings. I've written a blog entry on why a <a href="http://blog.gridspy.co.nz/2009/09/database-meet-realtime-data-logging.html" rel="nofollow">database is not suitable for live data</a> - though it is perfect for saving the data for later analysis.</p> <p>I'd have the first server process be a twisted server that uses <a href="https://launchpad.net/txamqp" rel="nofollow">txamp</a> to stream the ints to <a href="http://www.rabbitmq.com/" rel="nofollow">RabbitMQ</a>. Any clients that want live data can subscribe to the stream in RabbitMQ, also using Txamp. Web browser clients can use <a href="http://orbited.org/" rel="nofollow">Orbited</a> <a href="http://cometdaily.com/2008/10/10/scalable-real-time-web-architecture-part-2-a-live-graph-with-orbited-morbidq-and-jsio/" rel="nofollow">here is a worked example</a>.</p> <p>In your design server 1 saves to the database. You could instead have server3 collect data from RabbitMQ and stream it to the database. I plan to have a server that collects chunks of data and render graphs to store to a central fileshare. </p> <p>Don't create your own messaging system, RabbitMQ is well tested, scalable, and can persist your "messages" (raw data) if something goes wrong.</p>
1
2009-10-01T23:28:36Z
[ "python", "networking", "network-programming", "twisted" ]
Making a portable (exe) with Python 3.1?
1,505,783
<p>Is there a way to make a portable/stand-alone exe for python apps? </p> <p>I've read about p2exe but it doesn't support the latest version. I'm reluctant to go to 2.6 because I'd rather stay with the latest version instead of worrying about incompatibilities as soon as 2.6 becomes too outdated.</p>
7
2009-10-01T18:52:02Z
1,505,819
<p>cx_freeze has worked for me. Here's a link. The page claims to support 3.1. Good luck!</p> <p><a href="http://cx-freeze.sourceforge.net/">http://cx-freeze.sourceforge.net/</a></p>
13
2009-10-01T19:00:18Z
[ "python", "py2exe" ]
blackle.com queries
1,505,958
<p>I'm trying to query blackle.com for searches, but I get an 403 HTTP error. Can somebody point out what is wrong here?</p> <pre><code>#!/usr/bin/env python import urllib2 ss = raw_input('Please enter search string: ') response = "http://www.google.com/cse?cx=013269018370076798483:gg7jrrhpsy4&amp;cof=FORID:1&amp;q=" + ss + "&amp;sa=Search" urllib2.urlopen(response) html = response.read() print html </code></pre>
0
2009-10-01T19:26:21Z
1,506,257
<p>HTTP 403 means "forbidden" (see <a href="http://www.checkupdown.com/status/E403.html" rel="nofollow">here</a> for a good explanation): google.com doesn't want to let you access that resource. Since it does let <em>browsers</em> access it, presumably it's identifying you as a robot (automated code, not interactive user browser), through user agent checking and the like. Have you checked robots.txt to see if you SHOULD be allowed to access such URLs? In <a href="http://www.google.com/robots.txt" rel="nofollow">http://www.google.com/robots.txt</a> I see one line:</p> <pre><code>Disallow: /cse? </code></pre> <p>which means robots are NOT allowed here. See <a href="http://en.wikipedia.org/wiki/Robots%5Fexclusion%5Fstandard" rel="nofollow">here</a> for explanations of robots.txt, <a href="http://docs.python.org/library/robotparser.html" rel="nofollow">here</a> for the standard Python library module <code>roboparser</code> that makes it easy for a Python program to understand a robots.txt file.</p> <p>You could try fooling google's detection of "robots" vs humans, e.g. by falsifying your user agent header and so on, and maybe you'd get away with it for a while, but do you really want to deliberately violate the terms of use and get into a fight about it with google...?</p>
2
2009-10-01T20:26:06Z
[ "python", "search" ]
How to use export with Python on Linux
1,506,010
<p>I need to make an export like this in Python :</p> <pre><code># export MY_DATA="my_export" </code></pre> <p>I've tried to do :</p> <pre><code># -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') </code></pre> <p>But when I list export, "MY_DATA" not appear :</p> <pre><code># export </code></pre> <p>How I can do an export with Python without saving "my_export" into a file ?</p>
26
2009-10-01T19:39:35Z
1,506,022
<p>You could try os.environ["MY_DATA"] instead.</p>
2
2009-10-01T19:41:35Z
[ "python", "linux", "export" ]
How to use export with Python on Linux
1,506,010
<p>I need to make an export like this in Python :</p> <pre><code># export MY_DATA="my_export" </code></pre> <p>I've tried to do :</p> <pre><code># -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') </code></pre> <p>But when I list export, "MY_DATA" not appear :</p> <pre><code># export </code></pre> <p>How I can do an export with Python without saving "my_export" into a file ?</p>
26
2009-10-01T19:39:35Z
1,506,046
<p>You actually want to do</p> <pre><code>import os os.environ["MY_DATA"] = "my_export" </code></pre>
38
2009-10-01T19:46:21Z
[ "python", "linux", "export" ]
How to use export with Python on Linux
1,506,010
<p>I need to make an export like this in Python :</p> <pre><code># export MY_DATA="my_export" </code></pre> <p>I've tried to do :</p> <pre><code># -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') </code></pre> <p>But when I list export, "MY_DATA" not appear :</p> <pre><code># export </code></pre> <p>How I can do an export with Python without saving "my_export" into a file ?</p>
26
2009-10-01T19:39:35Z
1,506,108
<p>Not that simple:</p> <pre><code>python -c "import os; os.putenv('MY_DATA','1233')" $ echo $MY_DATA # &lt;- empty </code></pre> <p>But:</p> <pre><code>python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')" $ echo $MY_DATA #&lt;- 123 </code></pre>
7
2009-10-01T19:58:30Z
[ "python", "linux", "export" ]
How to use export with Python on Linux
1,506,010
<p>I need to make an export like this in Python :</p> <pre><code># export MY_DATA="my_export" </code></pre> <p>I've tried to do :</p> <pre><code># -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') </code></pre> <p>But when I list export, "MY_DATA" not appear :</p> <pre><code># export </code></pre> <p>How I can do an export with Python without saving "my_export" into a file ?</p>
26
2009-10-01T19:39:35Z
1,506,185
<p><code>export</code> is a command that you give directly to the shell (e.g. <code>bash</code>), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.</p> <p>Here's what's happening with you try <code>os.system('export MY_DATA="my_export"')</code>...</p> <pre><code>/bin/bash process, command `python yourscript.py` forks python subprocess |_ /usr/bin/python process, command `os.system()` forks /bin/sh subprocess |_ /bin/sh process, command `export ...` changes local environment </code></pre> <p>When the bottom-most <code>/bin/sh</code> subprocess finishes running your <code>export ...</code> command, then it's discarded, along with the environment that you have just changed.</p>
42
2009-10-01T20:11:47Z
[ "python", "linux", "export" ]
How to use export with Python on Linux
1,506,010
<p>I need to make an export like this in Python :</p> <pre><code># export MY_DATA="my_export" </code></pre> <p>I've tried to do :</p> <pre><code># -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') </code></pre> <p>But when I list export, "MY_DATA" not appear :</p> <pre><code># export </code></pre> <p>How I can do an export with Python without saving "my_export" into a file ?</p>
26
2009-10-01T19:39:35Z
8,938,108
<p>os.system ('/home/user1/exportPath.ksh')</p> <p>exportPath.ksh:</p> <p><code>export PATH=MY_DATA="my_export"</code></p>
-6
2012-01-20T07:33:14Z
[ "python", "linux", "export" ]
How to use export with Python on Linux
1,506,010
<p>I need to make an export like this in Python :</p> <pre><code># export MY_DATA="my_export" </code></pre> <p>I've tried to do :</p> <pre><code># -*- python-mode -*- # -*- coding: utf-8 -*- import os os.system('export MY_DATA="my_export"') </code></pre> <p>But when I list export, "MY_DATA" not appear :</p> <pre><code># export </code></pre> <p>How I can do an export with Python without saving "my_export" into a file ?</p>
26
2009-10-01T19:39:35Z
21,412,705
<p>Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.</p> <pre><code>$(python -c 'print "export MY_DATA=my_export"') </code></pre> <p>(you can also enclose the statement in backticks in some shells ``)</p>
4
2014-01-28T17:35:41Z
[ "python", "linux", "export" ]
Duplicate Insertions in Database using sqlite, sqlalchemy, python
1,506,023
<p>I am learning Python and, through the help of online resources and people on this site, am getting the hang of it. In this first script of mine, in which I'm parsing Twitter RSS feed entries and inserting the results into a database, there is one remaining problem that I cannot fix. Namely, duplicate entries are being inserted into one of the tables.</p> <p>As a bit of background, I originally found a base script on HalOtis.com for downloading RSS feeds and then modified it in several ways: 1) modified to account for idiosyncracies in Twitter RSS feeds (it's not separated into content, title, URL, etc.); 2) added tables for "hashtags" and for the many-to-many relationship (entry_tag table); 3) changed table set-up to sqlalchemy; 4) made some ad hoc changes to account for weird unicode problems that were occurring. As a result, the code is ugly in places, but it has been a good learning experience and now works--except that it keeps inserting duplicates in the "entries" table. </p> <p>Since I'm not sure what would be most helpful to people, I've pasted in the entire code below, with some comments in a few places to point out what I think is most important. </p> <p>I would really appreciate any help with this. Thanks!</p> <p>Edit: Somebody suggested I provide a schema for the database. I've never done this before, so if I'm not doing it right, bear with me. I am setting up four tables:</p> <ol> <li>RSSFeeds, which contains a list of Twitter RSS feeds </li> <li>RSSEntries, which contains a list of individual entries downloaded (after parsing) from each of the feeds (with columns for content, hashtags, date, url)</li> <li>Tags, which contains a list of all the hashtags that are found in individual entries (Tweets)</li> <li>entry_tag, which contains columns allowing me to map tags to entries. </li> </ol> <p>In short, the script below grabs the five test RSS feeds from the RSS Feeds table, downloads the 20 latest entries / tweets from each feed, parses the entries, and puts the information into the RSS Entries, Tags, and entry_tag tables. </p> <pre><code>#!/usr/local/bin/python import sqlite3 import threading import time import Queue from time import strftime import re from string import split import feedparser from django.utils.encoding import smart_str, smart_unicode from sqlalchemy import schema, types, ForeignKey, select, orm from sqlalchemy import create_engine engine = create_engine('sqlite:///test98.sqlite', echo=True) metadata = schema.MetaData(engine) metadata.bind = engine def now(): return datetime.datetime.now() #set up four tables, with many-to-many relationship RSSFeeds = schema.Table('feeds', metadata, schema.Column('id', types.Integer, schema.Sequence('feeds_seq_id', optional=True), primary_key=True), schema.Column('url', types.VARCHAR(1000), default=u''), ) RSSEntries = schema.Table('entries', metadata, schema.Column('id', types.Integer, schema.Sequence('entries_seq_id', optional=True), primary_key=True), schema.Column('feed_id', types.Integer, schema.ForeignKey('feeds.id')), schema.Column('short_url', types.VARCHAR(1000), default=u''), schema.Column('content', types.Text(), nullable=False), schema.Column('hashtags', types.Unicode(255)), schema.Column('date', types.String()), ) tag_table = schema.Table('tag', metadata, schema.Column('id', types.Integer, schema.Sequence('tag_seq_id', optional=True), primary_key=True), schema.Column('tagname', types.Unicode(20), nullable=False, unique=True), ) entrytag_table = schema.Table('entrytag', metadata, schema.Column('id', types.Integer, schema.Sequence('entrytag_seq_id', optional=True), primary_key=True), schema.Column('entryid', types.Integer, schema.ForeignKey('entries.id')), schema.Column('tagid', types.Integer, schema.ForeignKey('tag.id')), ) metadata.create_all(bind=engine, checkfirst=True) # Insert test set of Twitter RSS feeds stmt = RSSFeeds.insert() stmt.execute( {'url': 'http://twitter.com/statuses/user_timeline/14908909.rss'}, {'url': 'http://twitter.com/statuses/user_timeline/52903246.rss'}, {'url': 'http://twitter.com/statuses/user_timeline/41902319.rss'}, {'url': 'http://twitter.com/statuses/user_timeline/29950404.rss'}, {'url': 'http://twitter.com/statuses/user_timeline/35699859.rss'}, ) #These 3 lines for threading process (see HalOtis.com for example) THREAD_LIMIT = 20 jobs = Queue.Queue(0) rss_to_process = Queue.Queue(THREAD_LIMIT) #connect to sqlite database and grab the 5 test RSS feeds conn = engine.connect() feeds = conn.execute('SELECT id, url FROM feeds').fetchall() #This block contains all the parsing and DB insertion def store_feed_items(id, items): """ Takes a feed_id and a list of items and stores them in the DB """ for entry in items: conn.execute('SELECT id from entries WHERE short_url=?', (entry.link,)) #note: entry.summary contains entire feed entry for Twitter, #i.e., not separated into content, etc. s = unicode(entry.summary) test = s.split() tinyurl2 = [i for i in test if i.startswith('http://')] hashtags2 = [i for i in s.split() if i.startswith('#')] content2 = ' '.join(i for i in s.split() if i not in tinyurl2+hashtags2) content = unicode(content2) tinyurl = unicode(tinyurl2) hashtags = unicode (hashtags2) print hashtags date = strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed) #Insert parsed feed data into entries table #THIS IS WHERE DUPLICATES OCCUR result = conn.execute(RSSEntries.insert(), {'feed_id': id, 'short_url': tinyurl, 'content': content, 'hashtags': hashtags, 'date': date}) entry_id = result.last_inserted_ids()[0] #Look up tag identifiers and create any that don't exist: tags = tag_table tag_id_query = select([tags.c.tagname, tags.c.id], tags.c.tagname.in_(hashtags2)) tag_ids = dict(conn.execute(tag_id_query).fetchall()) for tag in hashtags2: if tag not in tag_ids: result = conn.execute(tags.insert(), {'tagname': tag}) tag_ids[tag] = result.last_inserted_ids()[0] #insert data into entrytag table if hashtags2: conn.execute(entrytag_table.insert(), [{'entryid': entry_id, 'tagid': tag_ids[tag]} for tag in hashtags2]) #Rest of file completes the threading process def thread(): while True: try: id, feed_url = jobs.get(False) # False = Don't wait except Queue.Empty: return entries = feedparser.parse(feed_url).entries rss_to_process.put((id, entries), True) # This will block if full for info in feeds: # Queue them up jobs.put([info['id'], info['url']]) for n in xrange(THREAD_LIMIT): t = threading.Thread(target=thread) t.start() while threading.activeCount() &gt; 1 or not rss_to_process.empty(): # That condition means we want to do this loop if there are threads # running OR there's stuff to process try: id, entries = rss_to_process.get(False, 1) # Wait for up to a second except Queue.Empty: continue store_feed_items(id, entries) </code></pre>
0
2009-10-01T19:41:41Z
1,506,453
<p>It looks like you included SQLAlchemy into a previously existing script that didn't use SQLAlchemy. There are too many moving parts here that none of us apparently understand well enough.</p> <p>I would recommend starting from scratch. Don't use threading. Don't use sqlalchemy. To start maybe don't even use an SQL database. Write a script that collects the information you want in the simplist possible way into a simple data structure using simple loops and maybe a time.sleep(). Then when that works you can add in storage to an SQL database, and I really don't think writing SQL statements directly is much harder than using an ORM and it's easier to debug IMHO. There is a good chance you will never need to add threading.</p> <p>"If you think you are smart enough to write multi-threaded programs, you're not." -- James Ahlstrom.</p>
2
2009-10-01T20:59:02Z
[ "python", "sqlite", "twitter", "sqlalchemy", "duplicates" ]
Delete all visible cookies raises an exception
1,506,315
<p>I am using selenium with a python client. When doing selenium.delete_all_visible_cookies I get the exception: <br></p> <blockquote> <p>ERROR: Command execution failure. Please search the forum at <a href="http://clearspace.openqa.org" rel="nofollow">http://clearspace.openqa.org</a> for error details from the log window. The error message is: malformed URI sequence</p> </blockquote> <p>The log window's error is:</p> <pre><code>error(1254427481456): Exception details: message -&gt; malformed URI sequence, fileName -&gt; http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js, lineNumber -&gt; 1169, stack -&gt; ("WSS_GW",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1169 ("WSS_GW",".mysite","/",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1208 ("WSS_GW",".mysite","/",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1213 ("WSS_GW",".mysite","/",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1236 ("WSS_GW","mysite","/",[object XPCCrossOriginWrapper])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1248 ("","")@http://localhost:4444/selenium-server/core/scripts/selenium-api.js:2607 ("","")@http://localhost:4444/selenium-server/core/scripts/htmlutils.js:60 ([object Object],[object Object])@http://localhost:4444/selenium-server/core/scripts/selenium-commandhandlers.js:310 ()@http://localhost:4444/selenium-server/core/scripts/selenium-executionloop.js:112 (-10)@http://localhost:4444/selenium-server/core/scripts/selenium-executionloop.js:78 (-10)@http://localhost:4444/selenium-server/core/scripts/htmlutils.js:60 , name -&gt; URIError </code></pre> <p>Any idea what's going on?</p>
2
2009-10-01T20:35:03Z
1,511,139
<p>This is a bug, see here: <a href="http://clearspace.openqa.org/message/68779" rel="nofollow">http://clearspace.openqa.org/message/68779</a></p>
1
2009-10-02T18:33:08Z
[ "python", "exception", "selenium", "cookies" ]
Delete all visible cookies raises an exception
1,506,315
<p>I am using selenium with a python client. When doing selenium.delete_all_visible_cookies I get the exception: <br></p> <blockquote> <p>ERROR: Command execution failure. Please search the forum at <a href="http://clearspace.openqa.org" rel="nofollow">http://clearspace.openqa.org</a> for error details from the log window. The error message is: malformed URI sequence</p> </blockquote> <p>The log window's error is:</p> <pre><code>error(1254427481456): Exception details: message -&gt; malformed URI sequence, fileName -&gt; http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js, lineNumber -&gt; 1169, stack -&gt; ("WSS_GW",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1169 ("WSS_GW",".mysite","/",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1208 ("WSS_GW",".mysite","/",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1213 ("WSS_GW",".mysite","/",[object HTMLDocument])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1236 ("WSS_GW","mysite","/",[object XPCCrossOriginWrapper])@http://localhost:4444/selenium-server/core/scripts/selenium-browserbot.js:1248 ("","")@http://localhost:4444/selenium-server/core/scripts/selenium-api.js:2607 ("","")@http://localhost:4444/selenium-server/core/scripts/htmlutils.js:60 ([object Object],[object Object])@http://localhost:4444/selenium-server/core/scripts/selenium-commandhandlers.js:310 ()@http://localhost:4444/selenium-server/core/scripts/selenium-executionloop.js:112 (-10)@http://localhost:4444/selenium-server/core/scripts/selenium-executionloop.js:78 (-10)@http://localhost:4444/selenium-server/core/scripts/htmlutils.js:60 , name -&gt; URIError </code></pre> <p>Any idea what's going on?</p>
2
2009-10-01T20:35:03Z
7,144,722
<p>To see the bug: <a href="http://jira.openqa.org/browse/SEL-712" rel="nofollow">http://jira.openqa.org/browse/SEL-712</a></p>
1
2011-08-22T08:19:52Z
[ "python", "exception", "selenium", "cookies" ]
Need a HTTPS-capable Python XML-RPC server
1,506,379
<p>I already have a very simple threading XML-RPC server in Python:</p> <pre><code>from SocketServer import ThreadingMixIn class AsyncXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer): pass server = AsyncXMLRPCServer(('localhost', 9999)) server.register_instance(some_object()) server.serve_forever() </code></pre> <p>Now I want to make it accessible exclusively over https. What do I do?</p>
0
2009-10-01T20:47:00Z
1,506,438
<p>The standard library doesn't support HTTPS servers. There is a <a href="http://code.activestate.com/recipes/496786/">Cookbook Recipe</a> using an OpenSSL module. There is also a <a href="http://www.etopian.com/portfolio/https-python-xmlrpc-server-w-authentication">Twisted solution</a>.</p>
5
2009-10-01T20:57:06Z
[ "python", "ssl", "https", "xml-rpc" ]
How to run multiple Tornado processes/threads/frontends?
1,506,463
<p>In the tornado documentation they show how they can have a very large through-put from <a href="http://www.tornadoweb.org/documentation#performance">4 frontends</a>. I'd like to run an app in the same way, and would like to have the frontends running as daemon processes managed with an init.d script*. </p> <p>I'm fairly new to Python so don't really know where to start. Currently I'm starting the Tornado server manually in the terminal, passing in a new port number each time. </p> <p>I've tried using the <a href="http://pypi.python.org/pypi/python-daemon">python-daemon package</a> in conjunction with the <a href="http://pypi.python.org/pypi/lockfile">lockfile package</a> but the lockfiles that are created don't have the process ids in them and I can't see how to then kill the processes gracefully later on.</p> <p>I don't really know where to go from here, and the Tornado docs leave a large chunk out regarding deployment.</p> <p><sub>* If there's a better way to manage the processes so that they can be monitored and managed as a group then please let me know.</sub></p>
5
2009-10-01T21:00:17Z
1,506,654
<p>Try <a href="http://supervisord.org/">Supervisor</a>. It's great for managing multiple daemon processes. You configure your applications in the supervisord.conf file and supervisord itself is launched from an init.d script.</p>
6
2009-10-01T21:38:58Z
[ "python", "deployment", "tornado" ]
How to run multiple Tornado processes/threads/frontends?
1,506,463
<p>In the tornado documentation they show how they can have a very large through-put from <a href="http://www.tornadoweb.org/documentation#performance">4 frontends</a>. I'd like to run an app in the same way, and would like to have the frontends running as daemon processes managed with an init.d script*. </p> <p>I'm fairly new to Python so don't really know where to start. Currently I'm starting the Tornado server manually in the terminal, passing in a new port number each time. </p> <p>I've tried using the <a href="http://pypi.python.org/pypi/python-daemon">python-daemon package</a> in conjunction with the <a href="http://pypi.python.org/pypi/lockfile">lockfile package</a> but the lockfiles that are created don't have the process ids in them and I can't see how to then kill the processes gracefully later on.</p> <p>I don't really know where to go from here, and the Tornado docs leave a large chunk out regarding deployment.</p> <p><sub>* If there's a better way to manage the processes so that they can be monitored and managed as a group then please let me know.</sub></p>
5
2009-10-01T21:00:17Z
1,751,660
<p>I can vouch for Supervisor too. We have been using tornado in production with 4 instances using supervisor and it is working uber smooth</p>
1
2009-11-17T20:48:08Z
[ "python", "deployment", "tornado" ]
Validating Google Optimizer javascript code via HTMLParser
1,506,496
<p>I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing.</p> <p>However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error:</p> <pre><code>raise PTRuntimeError(str(self._v_errors)) - Warning: Compilation failed - Warning: &lt;class 'HTMLParser.HTMLParseError'&gt;: bad end tag: u"&lt;/sc'+'ript&gt;", at line 45, column 44 PTRuntimeError: ['Compilation failed', '&lt;class \'HTMLParser.HTMLParseError\'&gt;: bad end tag: u"&lt;/sc\'+\'ript&gt;", at line 45, column 44'] </code></pre> <p>As I see it I have two options:</p> <ul> <li><p>Rewrite the code so it passes (my JS-foo is weak, no idea where to start).</p></li> <li><p>Make HTMLParser ignore the code. I've tried CDATA tags with no success. I've also tried putting the js in an external file and linking to it, but this <em>seems</em> to break the optimizer functionality.</p></li> </ul> <p>The suspect code:</p> <pre><code>&lt;!-- Google Website Optimizer Control Script --&gt; &lt;script&gt; &lt;![CDATA[ function utmx_section(){}function utmx(){} (function(){var k='1010538027',d=document,l=d.location,c=d.cookie;function f(n){ if(c){var i=c.indexOf(n+'=');if(i&gt;-1){var j=c.indexOf(';',i);return c.substring(i+n. length+1,j&lt;0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash; d.write('&lt;sc'+'ript src="'+ 'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com' +'/siteopt.js?v=1&amp;utmxkey='+k+'&amp;utmx='+(x?x:'')+'&amp;utmxx='+(xx?xx:'')+'&amp;utmxtime=' +new Date().valueOf()+(h?'&amp;utmxhash='+escape(h.substr(1)):'')+ '" type="text/javascript" charset="utf-8"&gt;&lt;/sc'+'ript&gt;')})(); ]]&gt; &lt;/script&gt;&lt;script&gt;utmx("url",'A/B');&lt;/script&gt; &lt;!-- End of Google Website Optimizer Control Script --&gt; </code></pre>
1
2009-10-01T21:06:21Z
1,506,561
<p>Given the parser's weakness, you could try breaking up the parts of the CDATA that it's trying to interpret as tags, e.g. where you now have <code>&lt;/sc'+'ript&gt;'</code> try <code>&lt;'+'/sc'+'ript&gt;'</code> etc (<code>+</code> does string catenation in JS, just like in Python, so it will put back together again the tags you break up this way, just like the tags that are already broken up in the original).</p> <p>If that keeps giving parse errors, lose the CDATA and change every <code>&lt;</code> into <code>&amp;lt;</code>, every <code>&gt;</code> into <code>&amp;gt;</code> -- not sure if JS will handle that but it's worth a try... good luck!</p>
1
2009-10-01T21:18:25Z
[ "javascript", "python", "zope", "google-website-optimizer", "zpt" ]
Validating Google Optimizer javascript code via HTMLParser
1,506,496
<p>I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing.</p> <p>However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error:</p> <pre><code>raise PTRuntimeError(str(self._v_errors)) - Warning: Compilation failed - Warning: &lt;class 'HTMLParser.HTMLParseError'&gt;: bad end tag: u"&lt;/sc'+'ript&gt;", at line 45, column 44 PTRuntimeError: ['Compilation failed', '&lt;class \'HTMLParser.HTMLParseError\'&gt;: bad end tag: u"&lt;/sc\'+\'ript&gt;", at line 45, column 44'] </code></pre> <p>As I see it I have two options:</p> <ul> <li><p>Rewrite the code so it passes (my JS-foo is weak, no idea where to start).</p></li> <li><p>Make HTMLParser ignore the code. I've tried CDATA tags with no success. I've also tried putting the js in an external file and linking to it, but this <em>seems</em> to break the optimizer functionality.</p></li> </ul> <p>The suspect code:</p> <pre><code>&lt;!-- Google Website Optimizer Control Script --&gt; &lt;script&gt; &lt;![CDATA[ function utmx_section(){}function utmx(){} (function(){var k='1010538027',d=document,l=d.location,c=d.cookie;function f(n){ if(c){var i=c.indexOf(n+'=');if(i&gt;-1){var j=c.indexOf(';',i);return c.substring(i+n. length+1,j&lt;0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash; d.write('&lt;sc'+'ript src="'+ 'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com' +'/siteopt.js?v=1&amp;utmxkey='+k+'&amp;utmx='+(x?x:'')+'&amp;utmxx='+(xx?xx:'')+'&amp;utmxtime=' +new Date().valueOf()+(h?'&amp;utmxhash='+escape(h.substr(1)):'')+ '" type="text/javascript" charset="utf-8"&gt;&lt;/sc'+'ript&gt;')})(); ]]&gt; &lt;/script&gt;&lt;script&gt;utmx("url",'A/B');&lt;/script&gt; &lt;!-- End of Google Website Optimizer Control Script --&gt; </code></pre>
1
2009-10-01T21:06:21Z
1,506,571
<p>My guess is the parser doesn't like the fact that </p> <pre><code>&lt;/sc'+'ript&gt; </code></pre> <p>is split in two. Which is perfectly valid javascript but may confuse the htmlparser?</p> <p>Might want to try </p> <pre><code>&lt;'+'/sc'+'ript&gt;' </code></pre>
0
2009-10-01T21:19:37Z
[ "javascript", "python", "zope", "google-website-optimizer", "zpt" ]
Validating Google Optimizer javascript code via HTMLParser
1,506,496
<p>I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing.</p> <p>However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error:</p> <pre><code>raise PTRuntimeError(str(self._v_errors)) - Warning: Compilation failed - Warning: &lt;class 'HTMLParser.HTMLParseError'&gt;: bad end tag: u"&lt;/sc'+'ript&gt;", at line 45, column 44 PTRuntimeError: ['Compilation failed', '&lt;class \'HTMLParser.HTMLParseError\'&gt;: bad end tag: u"&lt;/sc\'+\'ript&gt;", at line 45, column 44'] </code></pre> <p>As I see it I have two options:</p> <ul> <li><p>Rewrite the code so it passes (my JS-foo is weak, no idea where to start).</p></li> <li><p>Make HTMLParser ignore the code. I've tried CDATA tags with no success. I've also tried putting the js in an external file and linking to it, but this <em>seems</em> to break the optimizer functionality.</p></li> </ul> <p>The suspect code:</p> <pre><code>&lt;!-- Google Website Optimizer Control Script --&gt; &lt;script&gt; &lt;![CDATA[ function utmx_section(){}function utmx(){} (function(){var k='1010538027',d=document,l=d.location,c=d.cookie;function f(n){ if(c){var i=c.indexOf(n+'=');if(i&gt;-1){var j=c.indexOf(';',i);return c.substring(i+n. length+1,j&lt;0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash; d.write('&lt;sc'+'ript src="'+ 'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com' +'/siteopt.js?v=1&amp;utmxkey='+k+'&amp;utmx='+(x?x:'')+'&amp;utmxx='+(xx?xx:'')+'&amp;utmxtime=' +new Date().valueOf()+(h?'&amp;utmxhash='+escape(h.substr(1)):'')+ '" type="text/javascript" charset="utf-8"&gt;&lt;/sc'+'ript&gt;')})(); ]]&gt; &lt;/script&gt;&lt;script&gt;utmx("url",'A/B');&lt;/script&gt; &lt;!-- End of Google Website Optimizer Control Script --&gt; </code></pre>
1
2009-10-01T21:06:21Z
4,036,242
<p>One other option you have is to place the code in an external file and reference it instead of embedding it directly into the code. I've done this and it works well. That's always an easier way if you don't want the validator to crawl any javascript or css.</p>
-1
2010-10-27T18:05:26Z
[ "javascript", "python", "zope", "google-website-optimizer", "zpt" ]
Validating Google Optimizer javascript code via HTMLParser
1,506,496
<p>I'm trying to include the Google Website Optimizer JavaScript code, below, in a Zope3 page template. It's used for for A/B testing.</p> <p>However, the template html parser, which I believe is the standard Python HTMLParser module, throws the following error:</p> <pre><code>raise PTRuntimeError(str(self._v_errors)) - Warning: Compilation failed - Warning: &lt;class 'HTMLParser.HTMLParseError'&gt;: bad end tag: u"&lt;/sc'+'ript&gt;", at line 45, column 44 PTRuntimeError: ['Compilation failed', '&lt;class \'HTMLParser.HTMLParseError\'&gt;: bad end tag: u"&lt;/sc\'+\'ript&gt;", at line 45, column 44'] </code></pre> <p>As I see it I have two options:</p> <ul> <li><p>Rewrite the code so it passes (my JS-foo is weak, no idea where to start).</p></li> <li><p>Make HTMLParser ignore the code. I've tried CDATA tags with no success. I've also tried putting the js in an external file and linking to it, but this <em>seems</em> to break the optimizer functionality.</p></li> </ul> <p>The suspect code:</p> <pre><code>&lt;!-- Google Website Optimizer Control Script --&gt; &lt;script&gt; &lt;![CDATA[ function utmx_section(){}function utmx(){} (function(){var k='1010538027',d=document,l=d.location,c=d.cookie;function f(n){ if(c){var i=c.indexOf(n+'=');if(i&gt;-1){var j=c.indexOf(';',i);return c.substring(i+n. length+1,j&lt;0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash; d.write('&lt;sc'+'ript src="'+ 'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com' +'/siteopt.js?v=1&amp;utmxkey='+k+'&amp;utmx='+(x?x:'')+'&amp;utmxx='+(xx?xx:'')+'&amp;utmxtime=' +new Date().valueOf()+(h?'&amp;utmxhash='+escape(h.substr(1)):'')+ '" type="text/javascript" charset="utf-8"&gt;&lt;/sc'+'ript&gt;')})(); ]]&gt; &lt;/script&gt;&lt;script&gt;utmx("url",'A/B');&lt;/script&gt; &lt;!-- End of Google Website Optimizer Control Script --&gt; </code></pre>
1
2009-10-01T21:06:21Z
5,025,484
<p>Actually, this problem is trivial to solve by avoiding the HTML parser all together. Simply put the google Control Script into a separate file or object as Javascript and pull it into the page with a TAL include.</p> <p>The HTML parser is not used when the file is brought in as Javascript.</p>
1
2011-02-17T05:43:17Z
[ "javascript", "python", "zope", "google-website-optimizer", "zpt" ]