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 |
|---|---|---|---|---|---|---|---|---|---|
Django admin, custom error message? | 1,369,548 | <p>I would like to know how to show an error message in the Django admin.</p>
<p>I have a private user section on my site where the user can create requests using "points". A request takes 1 or 2 points from the user's account (depending on the two type of request), so if the account has 0 points the user cant make any requests... in the private user section all this is fine, but the user can also call the company and make a request by phone, and in this case I need the admin to show a custom error message in the case of the user points being 0.</p>
<p>Any help will be nice :)</p>
<p>Thanks guys</p>
| 7 | 2009-09-02T19:04:23Z | 1,369,683 | <p>I've used the built-in Message system for this sort of thing. This is the feature that prints the yellow bars at the top of the screen when you've added/changed an object. You can easily use it yourself:</p>
<pre><code>request.user.message_set.create(message='Message text here')
</code></pre>
<p>See <a href="http://docs.djangoproject.com/en/1.1/topics/auth/#messages" rel="nofollow">the documentation</a>.</p>
| 4 | 2009-09-02T19:35:04Z | [
"python",
"django",
"django-admin"
] |
Django admin, custom error message? | 1,369,548 | <p>I would like to know how to show an error message in the Django admin.</p>
<p>I have a private user section on my site where the user can create requests using "points". A request takes 1 or 2 points from the user's account (depending on the two type of request), so if the account has 0 points the user cant make any requests... in the private user section all this is fine, but the user can also call the company and make a request by phone, and in this case I need the admin to show a custom error message in the case of the user points being 0.</p>
<p>Any help will be nice :)</p>
<p>Thanks guys</p>
| 7 | 2009-09-02T19:04:23Z | 1,369,708 | <p>One way to do that is by overriding the ModelForm for the admin page. That allows you to write custom validation methods and return errors of your choosing very cleanly. Like this in admin.py:</p>
<pre><code>from django.contrib import admin
from models import *
from django import forms
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def clean_points(self):
points = self.cleaned_data['points']
if points.isdigit() and points < 1:
raise forms.ValidationError("You have no points!")
return points
class MyModelAdmin(admin.ModelAdmin):
form = MyForm
admin.site.register(MyModel, MyModelAdmin)
</code></pre>
<p>Hope that helps!</p>
| 18 | 2009-09-02T19:42:28Z | [
"python",
"django",
"django-admin"
] |
Django admin, custom error message? | 1,369,548 | <p>I would like to know how to show an error message in the Django admin.</p>
<p>I have a private user section on my site where the user can create requests using "points". A request takes 1 or 2 points from the user's account (depending on the two type of request), so if the account has 0 points the user cant make any requests... in the private user section all this is fine, but the user can also call the company and make a request by phone, and in this case I need the admin to show a custom error message in the case of the user points being 0.</p>
<p>Any help will be nice :)</p>
<p>Thanks guys</p>
| 7 | 2009-09-02T19:04:23Z | 15,477,092 | <p>Django versions < 1.2 <a href="https://docs.djangoproject.com/en/1.4/ref/contrib/messages/" rel="nofollow">https://docs.djangoproject.com/en/1.4/ref/contrib/messages/</a></p>
<pre><code>from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
</code></pre>
| 1 | 2013-03-18T12:40:50Z | [
"python",
"django",
"django-admin"
] |
Better resources to learn buildout | 1,369,664 | <p>I am trying to grasp a bit more of buildout with <a href="http://grok.zope.org/documentation/tutorial/introduction-to-zc.buildout/tutorial-all-pages">this tutorial</a>, but unlike a tutorial, it seems like a cut and paste of presentation slides.
I don't have a really clear idea of what the purpose of buildout is, and how it positions itself with scons and setuptools. Would you be so kind to provide details on these issues?</p>
<p>Thanks!</p>
| 12 | 2009-09-02T19:31:15Z | 1,369,917 | <p>I quite like the <a href="http://plone.org/documentation/tutorial/buildout" rel="nofollow">Plone Buildout Tutorial</a>.</p>
<p>It gives a reasonable overview of how it all works and the ways in which you can extend a simple buildout file.</p>
<p>Here is the <a href="http://docs.plone.org/old-reference-manuals/buildout/index.html" rel="nofollow">new link to Plone Buildout Tutorial</a>.</p>
| 6 | 2009-09-02T20:22:36Z | [
"python",
"resources",
"buildout"
] |
Better resources to learn buildout | 1,369,664 | <p>I am trying to grasp a bit more of buildout with <a href="http://grok.zope.org/documentation/tutorial/introduction-to-zc.buildout/tutorial-all-pages">this tutorial</a>, but unlike a tutorial, it seems like a cut and paste of presentation slides.
I don't have a really clear idea of what the purpose of buildout is, and how it positions itself with scons and setuptools. Would you be so kind to provide details on these issues?</p>
<p>Thanks!</p>
| 12 | 2009-09-02T19:31:15Z | 1,485,581 | <p>The most useful resource that I found so far are the videos from pycon 2009 on Setuptools, Distutils and Buildout.</p>
<p><a href="http://pycon.blip.tv/file/2061520/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 1</a></p>
<p><a href="http://pycon.blip.tv/file/2061678/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 2</a> </p>
<p><a href="http://pycon.blip.tv/file/2061724/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 3</a></p>
<p>Check it out.</p>
| 3 | 2009-09-28T05:44:21Z | [
"python",
"resources",
"buildout"
] |
Better resources to learn buildout | 1,369,664 | <p>I am trying to grasp a bit more of buildout with <a href="http://grok.zope.org/documentation/tutorial/introduction-to-zc.buildout/tutorial-all-pages">this tutorial</a>, but unlike a tutorial, it seems like a cut and paste of presentation slides.
I don't have a really clear idea of what the purpose of buildout is, and how it positions itself with scons and setuptools. Would you be so kind to provide details on these issues?</p>
<p>Thanks!</p>
| 12 | 2009-09-02T19:31:15Z | 1,684,930 | <p>Using <a href="http://www.buildout.org/" rel="nofollow">buildout.org</a> might be a good way for you to learn more about buildout.</p>
| 0 | 2009-11-06T01:56:27Z | [
"python",
"resources",
"buildout"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,369,733 | <p>Frankly speaking, the first version, where everything is in one line, is a pain to read.<br />
The second one is maybe a little too verbose (something in the middle would be appreciated) but it is definitely better.</p>
<p>I would not care too much about micro optimizations because of Python internals, and focus only on readable code.</p>
<p>By the way: the two (initial) versions are not doing the same thing.<br />
In the former, you first strip, then split, while in the latter you first split and then strip (furthermore, only the first element).<br />
Again, I think you overlooked this because the former version is quite difficult to focus on.<br />
Then, analyzing the two (updated) versions with <code>dis</code> (<a href="http://docs.python.org/library/dis.html" rel="nofollow">python disassembler</a>) showed no real difference between the two codes, only the order how the function names are being looked up. It is possible that this may have an impact on performance. </p>
<p>While we are on this, you could get some performance improvement just by binding eval to a local variable, before the loop. I would expect that after that change, there should be no difference in time between the two versions.<br />
For example:</p>
<pre><code>eval_ = eval
for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval_(c)
numbers.append(d)
</code></pre>
<p>We are mostly talking about micro-optimizations, but this aliasing is actually a technique that may be very useful in several circumstances.</p>
| 7 | 2009-09-02T19:46:53Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,369,748 | <p>A one liner doesn't mean smaller or faster code. And I would expect that the eval() line would throw off performance measurements quite a bit. </p>
<p>Do you see similar performance differences without eval ?</p>
| 2 | 2009-09-02T19:49:05Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,369,774 | <p>Your code isn't exploded in the same order. The compact version goes:</p>
<pre><code>A > B > C > D > E
</code></pre>
<p>while your exploded version goes </p>
<pre><code>B > C > A > D > E
</code></pre>
<p>The effect is that strip() is being deferred 2 steps down, which may affect performance depending on what the input is.</p>
| 15 | 2009-09-02T19:52:16Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,369,779 | <p>The method calls are also not in the same order:</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>should be:</p>
<pre><code>for line in lines:
numbers.append(eval(line.split()[0].strip()))
</code></pre>
| 4 | 2009-09-02T19:53:10Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,369,880 | <p>I agree with Roberto Liffredo; don't worry about that small of a performance improvement; code that is easier to understand, debug, and change is its own reward.</p>
<p>As for what's going on: the terse code and the expanded code don't do quite the same things. <code>line.strip().split()</code> first strips the line and then splits it; your expanded code splits the line first, and then calls <code>strip()</code> on the first word from the line. Now, the <code>strip()</code> isn't needed here; it's stripping white space from the end of the line, and words returned by <code>split()</code> never have any. Thus, in your expanded version, <code>strip()</code> has absolutely no work to do.</p>
<p>Without benchmarking, I can't be certain, but I think that <code>strip()</code> having no work to do is the key. In the one-line version, <code>strip()</code> sometimes has work to do; so it will strip the whitespace, building a new string object, and then return that string object. Then, that new string object will be split and discarded. The extra work of creating and discarding string objects is likely what is making the one-line solution slower. Compare that with the expanded version, where <code>strip()</code> simply looks at the string, decides it has no work to do, and returns the string unmodified.</p>
<p>In summary, I predict that a one-liner equivalent to your expanded code will be slightly faster than your expanded code. Try benchmarking this:</p>
<pre><code>for line in lines:
numbers.append(eval(line.split()[0].strip()))
</code></pre>
<p>If you want to be completely thorough, you could benchmark both versions with the <code>strip()</code> removed completely. You just don't need it. Or, you could pre-process your input file, making sure that there is no leading or trailing white space on any input line, and thus never any work for <code>strip()</code> to do, and you will probably see the benchmarks work as you would expect.</p>
<p>If you really want to make a hobby out of optimizing for speed here, you could call split with a "maxsplit" argument; you don't need to process the whole string as you are throwing away everything after the first split. Thus you could call <code>split(None, 1)</code>. You can get rid of the <code>strip()</code>, of course. And you would then have:</p>
<pre><code>for line in lines:
numbers.append(eval(line.split(None, 1)[0]))
</code></pre>
<p>If you knew the numbers were always integers, you could call <code>int()</code> instead of <code>eval()</code>, for a speed improvement and security improvement.</p>
| 3 | 2009-09-02T20:15:01Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,369,924 | <p>Also, sometimes it's tricky to run benchmarks. Did you re-run the benchmarks multiple times and take the best of several runs? Is there any chance that caching effects give a performance advantage to the second Python program you run? Have you tried making your input file ten times bigger, so your program will take about ten times longer to run?</p>
| 3 | 2009-09-02T20:24:23Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,370,142 | <p>I haven't benchmarked it, but one factor in the time differences is that you have to do several variable lookups in the second function.</p>
<p><a href="http://www.python.org/doc/essays/list2str.html" rel="nofollow">From Python Patterns - An Optimization Anecdote</a>:</p>
<blockquote>
<p>This is because local variable lookups are much faster than global or built-in variable lookups: the Python "compiler" optimizes most function bodies so that for local variables, no dictionary lookup is necessary, but a simple array indexing operation is sufficient. </p>
</blockquote>
<p>So, local variable lookups <em>do</em> have a cost associated. Let's take a look at the disassembled functions:</p>
<p>First, making sure I have the same defined functions as you:</p>
<pre><code>>>> def a(lines):
for line in lines:
numbers.append(eval(line.strip().split()[0]))
>>> def b(lines):
for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>Now, let's compare their disassembled values:</p>
<pre><code>>>> import dis
>>> dis.dis(a)
2 0 SETUP_LOOP 49 (to 52)
3 LOAD_FAST 0 (lines)
6 GET_ITER
>> 7 FOR_ITER 41 (to 51)
10 STORE_FAST 1 (line)
3 13 LOAD_GLOBAL 0 (numbers)
16 LOAD_ATTR 1 (append)
19 LOAD_GLOBAL 2 (eval)
22 LOAD_FAST 1 (line)
25 LOAD_ATTR 3 (strip)
28 CALL_FUNCTION 0
31 LOAD_ATTR 4 (split)
34 CALL_FUNCTION 0
37 LOAD_CONST 1 (0)
40 BINARY_SUBSCR
41 CALL_FUNCTION 1
44 CALL_FUNCTION 1
47 POP_TOP
48 JUMP_ABSOLUTE 7
>> 51 POP_BLOCK
>> 52 LOAD_CONST 0 (None)
55 RETURN_VALUE
>>> dis.dis(b)
2 0 SETUP_LOOP 73 (to 76)
3 LOAD_FAST 0 (lines)
6 GET_ITER
>> 7 FOR_ITER 65 (to 75)
10 STORE_FAST 1 (line)
3 13 LOAD_FAST 1 (line)
16 LOAD_ATTR 0 (strip)
19 CALL_FUNCTION 0
22 STORE_FAST 2 (a)
4 25 LOAD_FAST 2 (a)
28 LOAD_ATTR 1 (split)
31 CALL_FUNCTION 0
34 STORE_FAST 3 (b)
5 37 LOAD_FAST 3 (b)
40 LOAD_CONST 1 (0)
43 BINARY_SUBSCR
44 STORE_FAST 4 (c)
6 47 LOAD_GLOBAL 2 (eval)
50 LOAD_FAST 4 (c)
53 CALL_FUNCTION 1
56 STORE_FAST 5 (d)
7 59 LOAD_GLOBAL 3 (numbers)
62 LOAD_ATTR 4 (append)
65 LOAD_FAST 5 (d)
68 CALL_FUNCTION 1
71 POP_TOP
72 JUMP_ABSOLUTE 7
>> 75 POP_BLOCK
>> 76 LOAD_CONST 0 (None)
79 RETURN_VALUE
</code></pre>
<p>It's a lot of information, but we can see the second method is riddled with <code>STORE_FAST</code>, <code>LOAD_FAST</code> pairs due to the local variables being used. That <em>might</em> be enough to cause your small timing differences, (perhaps) in addition to the different operation order as others have mentioned.</p>
| 3 | 2009-09-02T21:10:13Z | [
"python",
"optimization"
] |
Why is my "exploded" Python code actually running faster? | 1,369,697 | <p>I'm in an introductory comp-sci class (after doing web programming for years) and became curious about how much speed I was gaining, if any, with my one-liners.</p>
<pre><code>for line in lines:
numbers.append(eval(line.strip().split()[0]))
</code></pre>
<p>So I wrote the same thing with painfully explicit assignments and ran them against each other.</p>
<pre><code>for line in lines:
a = line.split()
b = a[0]
c = b.strip()
d = eval(c)
numbers.append(d)
</code></pre>
<p>The second one runs a consistent 30ms <em>faster</em> (on my FreeBSD shell account; see Edit #2) with an input file of 100K lines! Of course this is on a total run time of 3 seconds, so the percentage isn't large...but I'm really surprised to see all those explicit named assignments somehow <em>helping</em>.</p>
<p>There's a <a href="http://stackoverflow.com/questions/1362997/encapsulation-severely-hurts-performance">recent thread</a> on the performance of functions as opposed to inline code, but this seems even more basic. What gives? Should I be writing lovingly fulsomely verbose code and telling my sneering colleagues it's for performance reasons? (Thankfully, a list-comprehension version runs about 10ms faster yet, so my cherished compactness isn't totally out the window.)</p>
<p><strong><em>EDIT:</em></strong> Thanks for the tip on my sloppy expansion of the code. You're all correct that the second one should really be:</p>
<pre><code>for line in lines:
a = line.strip()
b = a.split()
c = b[0]
d = eval(c)
numbers.append(d)
</code></pre>
<p>However, even once I've fixed that, my timings are 2.714s, 2.652s, and 2.624s respectively, for the one-liner, the fully-exploded form, and the list comprehension (not pictured). So my question stands!</p>
<p><strong><em>EDIT #2:</em></strong> It's interesting that the answer doesn't seem to be obvious even to a bunch of knowledgeable folks, which makes me feel a bit better about the question! I'll probably play with dis a bit on my own now, in this and similar circumstances, and see what turns up. By all means keep tinkering with the thread if you want, but <strong>I'm going to declare my received answer to be "huh, that's interesting; must be something deep."</strong> Especially since the behavior isn't consistent across machines, as steveha pointed out -- the slight difference goes the other direction on my Debian and Windows installs. Thanks to everyone who's contributed!</p>
| 3 | 2009-09-02T19:40:11Z | 1,370,822 | <p>Okay, enough theorizing. I created a file with one million lines, with random amounts of white space (0 to 4 spaces, usually 0) at beginning and end of each line. And I ran your one-liner, your expanded version, and my own list comprehension version (as fast as I know how to make it).</p>
<p>My results? (Each one is the best of three trials):</p>
<pre><code>one-line: 13.208s
expanded: 26.321s
listcomp: 13.024s
</code></pre>
<p>I tested under Ubuntu 9.04, 32-bit, with Python 2.6.2 (CPython, of course).</p>
<p>So I am completely unable to explain why you saw the expanded one running faster, given that it ran <em>half</em> as fast on my computer.</p>
<p>Here's the Python program I used to generate my test data:</p>
<pre><code>import random
f = open("/tmp/junk.txt", "w")
r = random.Random()
def randws():
n = r.randint(0, 10) - 4
if n < 0 or n > 4:
n = 0
return " " * n
for i in xrange(1000000):
s0 = randws()
n = r.randint(0, 256)
s1 = randws()
f.write("%s%d%s\n" % (s0, n, s1))
</code></pre>
<p>Here's my list comprehension program:</p>
<pre><code>lines = open("/tmp/junk.txt")
numbers = [eval(line.split(None, 1)[0]) for line in lines]
</code></pre>
<p>P.S. Here is a nice, fast version that can handle both <code>int</code> and <code>float</code> values.</p>
<pre><code>lines = open("/tmp/junk.txt")
def val(x):
try:
return int(x)
except ValueError:
pass
try:
return float(x)
except StandardError:
return 0
numbers = [val(line.split(None, 1)[0]) for line in lines]
</code></pre>
<p>Its best-of-three time was: 2.161s</p>
| 2 | 2009-09-03T00:14:07Z | [
"python",
"optimization"
] |
How would you query Picasa from a Google App Engine app? Data API or Url Fetch? | 1,369,861 | <p>How would you query Picasa from a Google App Engine app? Data API or Url Fetch? What are the pros and cons of using either method?</p>
<p><strong>[Edit]</strong><br />
I would like to be able to query a specific album in Picasa and list all the photos in it.
Code examples to do this in python are much appreciated.</p>
| 0 | 2009-09-02T20:10:47Z | 1,369,908 | <p>Your question is a little off, since the Data API is exposed through RESTful URLs, so both methods are ultimately a "URL Fetch".</p>
<p>The Data API works quite well, though. It gives you access to nearly all the functionality of Picasa, and responses are sent back and forth in well-formed, well-documented XML. Google's documentation for the API is very good.</p>
<p>If you only need access to limited publicly available content (like a photostream) then you can do this at a very basic level by just fetching the feed url and parsing that... but even for that you can get the same data with more configuration options via the Data API URLs.</p>
<p>I'm not sure what code samples you'd like... it really depends what you actually want to <em>do</em> with Picasa.</p>
| 2 | 2009-09-02T20:19:43Z | [
"python",
"api",
"google-app-engine",
"picasa",
"urlfetch"
] |
Python .pth Files Aren't Working | 1,369,947 | <p>Directories listed in my .pth configuration file aren't appearing in sys.path.</p>
<p>The contents of configuration file, named <code>some_code_dirs.pth</code>:</p>
<pre><code>/home/project
</code></pre>
<p>Paths to the file:</p>
<pre><code>/usr/lib/python2.6/site-packages/some_code_dirs.pth
/usr/lib/python2.6/some_code_dirs.pth
</code></pre>
<p>Check on sys variables in the python interpreter:</p>
<pre><code>>>> print sys.prefix
'/usr'
>>> print sys.exec_prefix
'/usr'
</code></pre>
<p>All this seems as required in the Python <a href="http://docs.python.org/library/site.html" rel="nofollow">documentation</a>, but sys.path doesn't include the /home/project directory. </p>
<p>Note that the interpreter <em>does</em> add the directory after:</p>
<pre><code>>>> site.addsitedir('/usr/lib/python2.6/site-packages')
</code></pre>
<p>What am I missing here?</p>
| 6 | 2009-09-02T20:31:34Z | 1,370,034 | <p>What OS are you using? On my Ubuntu 9.04 system that directory is not in sys.path.
Try putting it into <code>/usr/lib/python2.6/dist-packages</code>. Notice that it is <strong>dist</strong> instead of <strong>site</strong>.</p>
| 4 | 2009-09-02T20:51:52Z | [
"python",
"pythonpath"
] |
Python .pth Files Aren't Working | 1,369,947 | <p>Directories listed in my .pth configuration file aren't appearing in sys.path.</p>
<p>The contents of configuration file, named <code>some_code_dirs.pth</code>:</p>
<pre><code>/home/project
</code></pre>
<p>Paths to the file:</p>
<pre><code>/usr/lib/python2.6/site-packages/some_code_dirs.pth
/usr/lib/python2.6/some_code_dirs.pth
</code></pre>
<p>Check on sys variables in the python interpreter:</p>
<pre><code>>>> print sys.prefix
'/usr'
>>> print sys.exec_prefix
'/usr'
</code></pre>
<p>All this seems as required in the Python <a href="http://docs.python.org/library/site.html" rel="nofollow">documentation</a>, but sys.path doesn't include the /home/project directory. </p>
<p>Note that the interpreter <em>does</em> add the directory after:</p>
<pre><code>>>> site.addsitedir('/usr/lib/python2.6/site-packages')
</code></pre>
<p>What am I missing here?</p>
| 6 | 2009-09-02T20:31:34Z | 1,370,276 | <p>I had a <a href="http://stackoverflow.com/questions/1159650/how-to-use-a-custom-site-package-using-pth-files-for-python-2-6">similar problem</a> a while ago. Check the encoding of your pth-file. It seems that pth-files are silently ignored if encoded in UTF-8 with BOM.</p>
| 0 | 2009-09-02T21:37:43Z | [
"python",
"pythonpath"
] |
show *only* docstring in Sphinx documentation | 1,370,283 | <p>Sphinx has a feature called <code>automethod</code> that extracts the documentation from a method's docstring and embeds that into the documentation. But it not only embeds the docstring, but also the method signature (name + arguments). How do I embed <em>only</em> the docstring (excluding the method signature)?</p>
<p>ref: <a href="http://sphinx.pocoo.org/ext/autodoc.html">http://sphinx.pocoo.org/ext/autodoc.html</a></p>
| 9 | 2009-09-02T21:39:09Z | 1,384,673 | <p>I think what you're looking for is:</p>
<pre><code>from sphinx.ext import autodoc
class DocsonlyMethodDocumenter(autodoc.MethodDocumenter):
def format_args(self):
return None
autodoc.add_documenter(DocsonlyMethodDocumenter)
</code></pre>
<p>per <a href="http://bitbucket.org/birkenfeld/sphinx/src/tip/sphinx/ext/autodoc.py">the current sources</a> this should allow overriding what class is responsible for documenting methods (older versions of <code>add_documenter</code> forbade such overrides, but now they're explicitly allowed). Having <code>format_args</code> return None, of course, is THE documented way in <code>autodoc</code> to say "don't bother with the signature".</p>
<p>I think this is the clean, architected way to perform this task, and, as such, preferable to monkeypatching alternatives. If you need to live with some old versions of <code>sphinx</code> however you may indeed have to monkeypatch (<code>autodoc.MethodDocumenter.format_args=lambda _:None</code> -- eek!-) though I would recommend upgrading <code>sphinx</code> to the current version as a better approach if at all feasible in your specific deployment.</p>
| 14 | 2009-09-06T01:37:46Z | [
"python",
"documentation",
"python-sphinx"
] |
What is this piece of Python code doing? | 1,370,604 | <p>This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for.</p>
<pre><code>x, y = x + 3 * y, 4 * x + 1 * y
</code></pre>
<p>Is this a special Python syntax?</p>
| 8 | 2009-09-02T23:03:11Z | 1,370,624 | <pre><code>x, y = x + 3 * y, 4 * x + 1 * y
</code></pre>
<p>is the equivalent of:</p>
<pre><code>x = x + 3 * y
y = 4 * x + 1 * y
</code></pre>
<p><strong>EXCEPT</strong> that it uses the original values for x and y in both calculations - because the new values for x and y aren't assigned until both calculations are complete.</p>
<p>The generic form is:</p>
<pre><code>x,y = a,b
</code></pre>
<p>where a and b are expressions the values of which get assigned to x and y respectively. You can actually assign any tuple (set of comma-separated values) to any tuple of variables of the same size - for instance,</p>
<pre><code>x,y,z = a,b,c
</code></pre>
<p>would also work, but</p>
<pre><code>w,x,y,z = a,b,c
</code></pre>
<p>would not because the number of values in the right-hand tuple doesn't match the number of variables in the left-hand tuple.</p>
| 16 | 2009-09-02T23:06:50Z | [
"python",
"math",
"syntax"
] |
What is this piece of Python code doing? | 1,370,604 | <p>This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for.</p>
<pre><code>x, y = x + 3 * y, 4 * x + 1 * y
</code></pre>
<p>Is this a special Python syntax?</p>
| 8 | 2009-09-02T23:03:11Z | 1,370,631 | <p>It's an assignment to a <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">tuple</a>, also called <em>sequence unpacking</em>. Probably it's clearer when you add parenthesis around the tuples:</p>
<pre><code>(x, y) = (x + 3 * y, 4 * x + 1 * y)
</code></pre>
<p>The value <code>x + 3 * y</code> is assigned to <code>x</code> and the value <code>4 * x + 1 * y</code> is assigned to <code>y</code>.</p>
<p>It is equivalent to this:</p>
<pre><code>x_new = x + 3 * y
y_new = 4 * x + 1 * y
x = x_new
y = y_new
</code></pre>
| 12 | 2009-09-02T23:09:14Z | [
"python",
"math",
"syntax"
] |
What is this piece of Python code doing? | 1,370,604 | <p>This following is a snippet of Python code I found that solves a mathematical problem. What exactly is it doing? I wasn't too sure what to Google for.</p>
<pre><code>x, y = x + 3 * y, 4 * x + 1 * y
</code></pre>
<p>Is this a special Python syntax?</p>
| 8 | 2009-09-02T23:03:11Z | 1,375,316 | <p>I also recently saw this referred to as "simultaneous assignment", which seems to capture the spirit of several of the answers.</p>
| 0 | 2009-09-03T19:03:59Z | [
"python",
"math",
"syntax"
] |
group by year, month, day in a sqlalchemy | 1,370,997 | <p>I want "DBSession.query(Article).group_by(Article.created.month).all()"</p>
<p>But this query can't using</p>
<p>How do I do this using SQLAlchemy?</p>
| 9 | 2009-09-03T01:19:10Z | 1,371,029 | <p>assuming you db engine actually supports functions like <code>MONTH()</code>, you can try</p>
<pre><code>import sqlalchemy as sa
DBSession.query(Article).group_by( sa.func.year(Article.created), sa.func.month(Article.created)).all()
</code></pre>
<p>else you can group in python like</p>
<pre><code>from itertools import groupby
def grouper( item ):
return item.created.year, item.created.month
for ( (year, month), items ) in groupby( query_result, grouper ):
for item in items:
# do stuff
</code></pre>
| 22 | 2009-09-03T01:34:25Z | [
"python",
"sqlalchemy"
] |
group by year, month, day in a sqlalchemy | 1,370,997 | <p>I want "DBSession.query(Article).group_by(Article.created.month).all()"</p>
<p>But this query can't using</p>
<p>How do I do this using SQLAlchemy?</p>
| 9 | 2009-09-03T01:19:10Z | 3,795,778 | <p><strong>THC4k answer works</strong> but I just want to add that <code>query_result</code> need to be already <strong>sorted</strong> to get <code>itertools.groupby</code> working the way you want.</p>
<pre><code>query_result = DBSession.query(Article).order_by(Article.created).all()
</code></pre>
<p>Here is the explanation in the <a href="http://docs.python.org/library/itertools.html#itertools.groupby">itertools.groupby docs</a>:</p>
<blockquote>
<p>The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQLâs GROUP BY which aggregates common elements regardless of their input order.</p>
</blockquote>
| 9 | 2010-09-25T22:05:29Z | [
"python",
"sqlalchemy"
] |
Django - flush response? | 1,371,020 | <p>I am sending an AJAX request to a Django view that can potentially take a lot of time. It goes through some well-defined steps, however, so I would like to print status indicators to the user letting it know when it is finished doing a certain thing and has moved on to the next.</p>
<p>If I was using PHP it might look like this, using the <a href="http://www.php.net/flush" rel="nofollow">flush</a> function:</p>
<pre><code>do_something();
print 'Done doing something!';
flush();
do_something_else();
print 'Done doing something else!';
flush();
</code></pre>
<p>How would I go about doing the same with Django? Looking at <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#id3" rel="nofollow">the documentation</a> I see that HttpResponse objects have a flush method, but all it has to say is that "This method makes an HttpResponse instance a file-like object." - I'm not sure that's what I want. I'm having a hard time wrapping my head around how this could be done in Django since I have to return the response and don't really have a control of when the content goes to the browser.</p>
| 6 | 2009-09-03T01:29:31Z | 1,371,061 | <p>Most webservers (eg. FCGI/SCGI) do their own buffering, HTTP clients do their own, and so on. It's very difficult to actually get data flushed out in this way and for the client to actually receive it, because it's not a typical operation.</p>
<p>The closest to what you're trying to do would be to pass an iterator to HttpResponse, and to do the work in a generator; something like this:</p>
<pre><code>def index(request):
def do_work():
step_1()
yield "step 1 complete"
step_2()
yield "step 2 complete"
step_3()
yield "step 3 complete"
return HttpResponse(do_work())
</code></pre>
<p>... but this won't <em>necessarily</em> flush. (Not tested code, but you get the idea; see <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators</a>.)</p>
<p>Most of the infrastructure is simply not expecting a piecemeal response. Even if Django isn't buffering, your front-end server might be, and the client probably is, too. That's why most things use pull updates for this: a separate interface to query the status of a long-running request.</p>
<p>(I'd like to be able to do reliable push updates for this sort of thing, too...)</p>
| 8 | 2009-09-03T01:50:23Z | [
"python",
"django"
] |
Django - flush response? | 1,371,020 | <p>I am sending an AJAX request to a Django view that can potentially take a lot of time. It goes through some well-defined steps, however, so I would like to print status indicators to the user letting it know when it is finished doing a certain thing and has moved on to the next.</p>
<p>If I was using PHP it might look like this, using the <a href="http://www.php.net/flush" rel="nofollow">flush</a> function:</p>
<pre><code>do_something();
print 'Done doing something!';
flush();
do_something_else();
print 'Done doing something else!';
flush();
</code></pre>
<p>How would I go about doing the same with Django? Looking at <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#id3" rel="nofollow">the documentation</a> I see that HttpResponse objects have a flush method, but all it has to say is that "This method makes an HttpResponse instance a file-like object." - I'm not sure that's what I want. I'm having a hard time wrapping my head around how this could be done in Django since I have to return the response and don't really have a control of when the content goes to the browser.</p>
| 6 | 2009-09-03T01:29:31Z | 1,371,078 | <p>I'm not sure you need to use the flush() function.</p>
<p>Your AJAX request should just go to a django view.</p>
<p>If your steps can be broken down, keep it simple and create a view for each step.
That way one one process completes you can update the user and start the next request via AJAX.</p>
<p><strong>views.py</strong></p>
<pre><code>def do_something(request):
# stuff here
return HttpResponse()
def do_something_else(request):
# more stuff
return HttpResponse()
</code></pre>
| 4 | 2009-09-03T01:58:34Z | [
"python",
"django"
] |
Weird python behaviour on machine with ARM CPU | 1,371,228 | <p>What could possibly cause this weird python behaviour?</p>
<pre><code>Python 2.6.2 (r262:71600, May 31 2009, 03:55:41)
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> .1
1251938906.2350719
>>> .1
0.23507189750671387
>>> .1
0.0
>>> .1
-1073741823.0
>>> .1
-1073741823.0
>>> .1
-1073741823.0
>>>
</code></pre>
<p>It gives the same output for <code>0.1</code>, <code>0.5</code>, <code>5.1</code>, <code>0.0</code>, etc.. Integers are echoed back at me correctly, but anything with a decimal point gives me the crazy numbers.</p>
<p>This is a python binary compiled for ARM, installed via <a href="http://www.nslu2-linux.org/wiki/Optware/HomePage" rel="nofollow">Optware</a> on a Synology DiskStation 101j.</p>
<p>Has anyone seen anything like this before?</p>
| 10 | 2009-09-03T02:59:57Z | 1,371,551 | <p>Maybe it's compiled for the wrong <a href="http://en.wikipedia.org/wiki/ARM%5Farchitecture#VFP" rel="nofollow">VFP</a> version.</p>
<p>Or your ARM has no VFP and needs to use software emulation instead, but the python binary tries to use hardware.</p>
<p><hr /></p>
<p><strong>EDIT</strong></p>
<p>Your DS-101j build on <strong>FW IXP420 BB</strong> cpu, which is <strong>Intel XScale (armv5b)</strong> (<a href="http://oinkzwurgl.org/diskstation%5Fhardware" rel="nofollow">link</a>). It has no hardware floating-point support. And "b" in armv5b stands for Big Endian. Some people has build problems, because gcc generates little endian code by default. Maybe this is the problem of your software FP lib. Check <a href="http://www.google.com/search?q=armv5b" rel="nofollow">this search</a> for more info.</p>
| 8 | 2009-09-03T05:26:21Z | [
"python",
"floating-point",
"arm"
] |
Weird python behaviour on machine with ARM CPU | 1,371,228 | <p>What could possibly cause this weird python behaviour?</p>
<pre><code>Python 2.6.2 (r262:71600, May 31 2009, 03:55:41)
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> .1
1251938906.2350719
>>> .1
0.23507189750671387
>>> .1
0.0
>>> .1
-1073741823.0
>>> .1
-1073741823.0
>>> .1
-1073741823.0
>>>
</code></pre>
<p>It gives the same output for <code>0.1</code>, <code>0.5</code>, <code>5.1</code>, <code>0.0</code>, etc.. Integers are echoed back at me correctly, but anything with a decimal point gives me the crazy numbers.</p>
<p>This is a python binary compiled for ARM, installed via <a href="http://www.nslu2-linux.org/wiki/Optware/HomePage" rel="nofollow">Optware</a> on a Synology DiskStation 101j.</p>
<p>Has anyone seen anything like this before?</p>
| 10 | 2009-09-03T02:59:57Z | 1,374,437 | <p>As zxcat said, this sounds like you're running on an ARM with no hardware-floating point and a busted soft-float library. A quick search didn't turn up what ARM variant is in the DS101j; anyone know?</p>
| 0 | 2009-09-03T16:17:14Z | [
"python",
"floating-point",
"arm"
] |
query for values based on date w/ Django ORM | 1,371,280 | <p>I have a bunch of objects that have a value and a date field: </p>
<pre><code>obj1 = Obj(date='2009-8-20', value=10)
obj2 = Obj(date='2009-8-21', value=15)
obj3 = Obj(date='2009-8-23', value=8)
</code></pre>
<p>I want this returned:</p>
<pre><code>[10, 15, 0, 8]
</code></pre>
<p>or better yet, an aggregate of the total up to that point:</p>
<pre><code>[10, 25, 25, 33]
</code></pre>
<p>I would be best to get this data directly from the database, but otherwise I can do the totaling pretty easily with a forloop.</p>
<p>I'm using Django's ORM and also Postgres</p>
<p>edit:</p>
<p>Just to note, that my example only covers a few days, but in practice, I have hundreds of objects covering a couple decades... What I'm trying to do is create a line graph showing how the sum of all my objects has grown over time (a very long time)</p>
| 1 | 2009-09-03T03:20:05Z | 1,371,478 | <pre><code>result_list = []
for day in range(20,24):
result = Obj.objects.get(date=datetime(2009, 08, day))
if result:
result_list.append(result.value)
else:
result_list.append(0)
return result_list
</code></pre>
<p>If you have more than one Obj per date, you'll need to check len(obj) and iterate over them in case it's more than 1.</p>
| 0 | 2009-09-03T04:48:36Z | [
"python",
"django",
"django-orm"
] |
query for values based on date w/ Django ORM | 1,371,280 | <p>I have a bunch of objects that have a value and a date field: </p>
<pre><code>obj1 = Obj(date='2009-8-20', value=10)
obj2 = Obj(date='2009-8-21', value=15)
obj3 = Obj(date='2009-8-23', value=8)
</code></pre>
<p>I want this returned:</p>
<pre><code>[10, 15, 0, 8]
</code></pre>
<p>or better yet, an aggregate of the total up to that point:</p>
<pre><code>[10, 25, 25, 33]
</code></pre>
<p>I would be best to get this data directly from the database, but otherwise I can do the totaling pretty easily with a forloop.</p>
<p>I'm using Django's ORM and also Postgres</p>
<p>edit:</p>
<p>Just to note, that my example only covers a few days, but in practice, I have hundreds of objects covering a couple decades... What I'm trying to do is create a line graph showing how the sum of all my objects has grown over time (a very long time)</p>
| 1 | 2009-09-03T03:20:05Z | 1,371,550 | <p>This one isn't tested, since it's a bit too much of a pain to set up a Django table to test with:</p>
<pre><code>from datetime import date, timedelta
# http://www.ianlewis.org/en/python-date-range-iterator
def datetimeRange(from_date, to_date=None):
while to_date is None or from_date <= to_date:
yield from_date
from_date = from_date + timedelta(days = 1)
start = date(2009, 8, 20)
end = date(2009, 8, 23)
objects = Obj.objects.filter(date__gte=start)
objects = objects.filter(date__lte=end)
results = {}
for o in objects:
results[o.date] = o.value
return [results.get(day, 0) for day in datetimeRange(start, end)]
</code></pre>
<p>This avoids running a separate query for every day.</p>
| 3 | 2009-09-03T05:25:55Z | [
"python",
"django",
"django-orm"
] |
query for values based on date w/ Django ORM | 1,371,280 | <p>I have a bunch of objects that have a value and a date field: </p>
<pre><code>obj1 = Obj(date='2009-8-20', value=10)
obj2 = Obj(date='2009-8-21', value=15)
obj3 = Obj(date='2009-8-23', value=8)
</code></pre>
<p>I want this returned:</p>
<pre><code>[10, 15, 0, 8]
</code></pre>
<p>or better yet, an aggregate of the total up to that point:</p>
<pre><code>[10, 25, 25, 33]
</code></pre>
<p>I would be best to get this data directly from the database, but otherwise I can do the totaling pretty easily with a forloop.</p>
<p>I'm using Django's ORM and also Postgres</p>
<p>edit:</p>
<p>Just to note, that my example only covers a few days, but in practice, I have hundreds of objects covering a couple decades... What I'm trying to do is create a line graph showing how the sum of all my objects has grown over time (a very long time)</p>
| 1 | 2009-09-03T03:20:05Z | 1,372,222 | <p>If you loop through a Obj.objects.get 100 times, you're doing 100 SQL queries. Obj.objects.filter will return the results in one SQL query, but you also select all model fields. The right way to do this is to use Obj.objects.values_list, which will do this with a single query, and only select the 'values' field.</p>
<pre><code>start_date = date(2009, 8, 20)
end_date = date(2009, 8, 23)
objects = Obj.objects.filter(date__range=(start_date,end_date))
# values_list and 'value' aren't related. 'value' should be whatever field you're querying
val_list = objects.values_list('value',flat=True)
# val_list = [10, 15, 8]
</code></pre>
<p>To do a running aggregate of val_list, you can do this (not certain that this is the most pythonic way)</p>
<pre><code>for i in xrange(len(val_list)):
if i > 0:
val_list[i] = val_list[i] + val_list[i-1]
# val_list = [10,25,33]
</code></pre>
<p>EDIT: If you need to account for missing days, @Glenn Maynard's answer is actually pretty good, although I prefer the dict() syntax:</p>
<pre><code>objects = Obj.objects.filter(date__range=(start_date,end_date)).values('date','value')
val_dict = dict((obj['date'],obj['value']) for obj in objects)
# I'm stealing datetimeRange from @Glenn Maynard
val_list = [val_dict.get(day, 0) for day in datetimeRange(start_date, end_date)]
# val_list = [10,15,0,8]
</code></pre>
| 1 | 2009-09-03T08:51:19Z | [
"python",
"django",
"django-orm"
] |
REST / JSON / XML-RPC / SOAP | 1,371,312 | <p>Sorry for being the 100000th person to ask the same question. But I guess my case is slightly distinctive.</p>
<p>The application is that we'd like to have an Android phone client on 3g and a light python web service server.</p>
<p>The phone would do most of the work and do a lot of uploading, pictures, GPS, etc etc. The server just has to respond with an 'ok' per upload. </p>
<p>I want to use the lightest method, easiest on the battery. But reading about all these protocols is a bit confusing since they all sound the same. </p>
<p>Are they all on the same levels? Or can JSON be a RESTful thing etc?
So as described, the key here is uploading. Does all the input for a REST transaction have to be in a URI? i.e. <a href="http://www.server.com/upload/0x81d058f82ac13" rel="nofollow">http://www.server.com/upload/0x81d058f82ac13</a>.
XML-RPC and SOAP sound decently similar from Googling too.</p>
| 4 | 2009-09-03T03:35:22Z | 1,371,337 | <p>REST mandates the general semantics and concepts. The transport and encodings are up to you. They were originally formulated on XML, but JSON is totally applicable.</p>
<p>XML-RPC / SOAP are different mechanisms, but mostly the same ideas: how to map OO APIs on top of XML and HTTP. IMHO, they're disgusting from a design view. I was so relieved when found about REST. In your case, i'm sure that the lots of layers would mean a lot more CPU demand.</p>
<p>I'd say go REST, using JSON for encoding; but if your requirements are really that simple as just uploading, then you can use simply HTTP (which might be RESTful in design even without adding any specific library)</p>
| 7 | 2009-09-03T03:43:39Z | [
"python",
"android",
"service"
] |
Set Max Width for Frame with ScrolledWindow in wxPython | 1,371,510 | <p>I created a Frame object and I want to limit the width it can expand to. The only window in the frame is a ScrolledWindow object and that contains all other children. I have a lot of objects arranged with a BoxSizer oriented vertically so the ScrolledWindow object gets pretty tall. There is often a scrollbar to the right so you can scroll up and down.</p>
<p>The problem comes when I try to set a max size for the frame. I'm using the <code>scrolled_window.GetBestSize()</code> (or <code>scrolled_window.GetEffectiveMinSize()</code>) functions of ScrolledWindow, but they don't take into account the vertical scrollbar. I end up having a frame that's just a little too narrow and there's a horizontal scrollbar that will never go away.</p>
<p>Is there a method that will account compensate for the vertical scrollbar's width? If not, how would I get the scrollbar's width so I can manually add it to the my frame's max size?</p>
<p>Here's an example with a tall but narrow frame:</p>
<pre><code>class TallFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None, title='Tall Frame')
self.scroll = wx.ScrolledWindow(parent=self) # our scroll area where we'll put everything
scroll_sizer = wx.BoxSizer(wx.VERTICAL)
# Fill the scroll area with something...
for i in xrange(10):
textbox = wx.StaticText(self.scroll, -1, "%d) Some random text" % i, size=(400, 100))
scroll_sizer.Add(textbox, 0, wx.EXPAND)
self.scroll.SetSizer(scroll_sizer)
self.scroll.Fit()
width, height = self.scroll.GetBestSize()
self.SetMaxSize((width, -1)) # Trying to limit the width of our frame
self.scroll.SetScrollbars(1, 1, width, height) # throwing up some scrollbars
</code></pre>
<p>If you create this frame you'll see that <code>self.SetMaxSize</code> is set too narrow. There will always be a horizontal scrollbar since <code>self.scroll.GetBestSize()</code> didn't account for the width of scrollbar.</p>
| 0 | 2009-09-03T05:05:53Z | 1,670,856 | <p>This is a little ugly, but seems to work on Window and Linux. There is difference, though. The self.GetVirtualSize() seems to return different values on each platform. At any rate, I think this may help you.</p>
<pre><code>width, height = self.scroll.GetBestSize()
width_2, height_2 = self.GetVirtualSize()
print width
print width_2
dx = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
print dx
self.SetMaxSize((width + (width - width_2) + dx, -1)) # Trying to limit the width of our frame
self.scroll.SetScrollbars(1, 1, width, height) # throwing up some scrollbars
</code></pre>
| 1 | 2009-11-03T23:36:51Z | [
"python",
"user-interface",
"wxpython"
] |
Importing external module in IronPython | 1,371,994 | <p>I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with. </p>
<p>I want to import an external module into the script. How can I do that? Simple <code>import ext_lib</code> doesn't work. Should I add a path to the lib to <code>sys.path</code>?
Maybe it is possible to copy the lib's .py file into app directory and import from there?</p>
<p><strong>EDIT:</strong>
I finally chosen another solution - compiled my script with <code>py2exe</code> and I'm just running it from main C# app with <code>Process</code> (without using IronPython).</p>
<p>Anyway, thanks for help ;)</p>
| 11 | 2009-09-03T07:50:17Z | 1,372,777 | <p>Chances are that your path is set up incorrectly. From <a href="http://ironpython.codeplex.com/Wiki/View.aspx?title=FAQ">the IronPython FAQ</a>:</p>
<blockquote>
<h3>How do I use CPython standard libraries?</h3>
<p>To tell IronPython where the Python standard library is, you can add the "lib" directory of CPython to IronPython's path. To do this, put the following code into IronPython's "site.py" file (replace c:\python24\lib with your actual path to the CPython lib directory):</p>
<pre><code>import sys
sys.path.append(r"c:\python24\lib")
</code></pre>
</blockquote>
<p>Also, if you're getting import errors in CPython for a script that you <em>do</em> have on your computer, 99% of the time it's a path issue there too.</p>
| 7 | 2009-09-03T11:07:58Z | [
"python",
"import",
"ironpython"
] |
Importing external module in IronPython | 1,371,994 | <p>I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with. </p>
<p>I want to import an external module into the script. How can I do that? Simple <code>import ext_lib</code> doesn't work. Should I add a path to the lib to <code>sys.path</code>?
Maybe it is possible to copy the lib's .py file into app directory and import from there?</p>
<p><strong>EDIT:</strong>
I finally chosen another solution - compiled my script with <code>py2exe</code> and I'm just running it from main C# app with <code>Process</code> (without using IronPython).</p>
<p>Anyway, thanks for help ;)</p>
| 11 | 2009-09-03T07:50:17Z | 1,379,797 | <p>Before compiling a script with the PythonEngine, I add the script's directory to the engine's search path. This is what I do in the C# code:</p>
<pre><code>string dir = Path.GetDirectoryName(scriptPath);
ICollection<string> paths = engine.GetSearchPaths();
if (!String.IsNullOrWhitespace(dir))
{
paths.Add(dir);
}
else
{
paths.Add(Environment.CurrentDirectory);
}
engine.SetSearchPaths(paths);
</code></pre>
<p>Now if the libraries are in the directory where the scripts, which you are executing, reside they will be importable. </p>
| 18 | 2009-09-04T14:58:22Z | [
"python",
"import",
"ironpython"
] |
How to specify a configuration file for pylint under windows? | 1,372,295 | <p>I am evaluating pylint as source code checker and I would like to customize the maximum number of characters on a single line. </p>
<p>I would like to use a configuration file. I've generated a template thanks to the --generate-rcfile command and I've made my modification.</p>
<p>I am trying to run pylint --rcfile=myfile.rc but I can see that my changes are not taken into account by pylint. I've tried different location for my file : \Python26\Scripts\ and pylint.d in my user folder without any success.</p>
<p>Does anybody know what I am doing wrong?</p>
<p>Is it possible to use the configration file with pylint-gui? I can't do it too?</p>
| 13 | 2009-09-03T09:04:08Z | 1,372,445 | <p>Try setting PYLINTRC env variable.</p>
<p>I use batch:</p>
<pre><code>@echo off
set PYLINTHOME=c:\tools
set PYLINTRC=c:\etc\pylint.conf
rem c:\Python27\python.exe c:\Python27\Lib\site-packages\pylint\lint.py %1 %2 %3 %4 %5 %6 %7 %8 %9
c:\Python27\python.exe c:\Python27\Lib\site-packages\pylint\lint.py %*
</code></pre>
| 4 | 2009-09-03T09:40:21Z | [
"python",
"pylint"
] |
How to specify a configuration file for pylint under windows? | 1,372,295 | <p>I am evaluating pylint as source code checker and I would like to customize the maximum number of characters on a single line. </p>
<p>I would like to use a configuration file. I've generated a template thanks to the --generate-rcfile command and I've made my modification.</p>
<p>I am trying to run pylint --rcfile=myfile.rc but I can see that my changes are not taken into account by pylint. I've tried different location for my file : \Python26\Scripts\ and pylint.d in my user folder without any success.</p>
<p>Does anybody know what I am doing wrong?</p>
<p>Is it possible to use the configration file with pylint-gui? I can't do it too?</p>
| 13 | 2009-09-03T09:04:08Z | 15,837,092 | <p>On Windows 7, a .pylintrc file in your home directory (typically C:\Users\myusername) will be automatically recognized.</p>
<p>Since creating a file beginning with a dot is not allowed from Windows file explorer, you can create a template using:</p>
<pre><code>pylint --generate-rcfile > .pylintrc
</code></pre>
| 6 | 2013-04-05T14:54:32Z | [
"python",
"pylint"
] |
Python Changing module variables in another module | 1,372,486 | <p>Say I am importing the module 'foo' into the module 'bar'.
Is it possible for me to change a global variable in foo inside bar? </p>
<p>Let the global variable in foo be 'arbit'.
Change arbit so that if bar were to call a function of foo that uses this variable, the updated variable is used rather than the one before that.</p>
| 0 | 2009-09-03T09:54:13Z | 1,372,516 | <p>You should be able to do:</p>
<pre><code>import foo
foo.arbit = 'new value'
</code></pre>
| 5 | 2009-09-03T10:00:10Z | [
"python",
"module"
] |
How to insert a row with autoincrement id in a multi-primary-key table? | 1,372,525 | <p>I am writing a turbogears2 application. I have a table like this:</p>
<pre><code>class Order(DeclarativeBase):
__tablename__ = 'order'
# id of order
id = Column(Integer, autoincrement=True, primary_key=True)
# buyer's id
buyer_id = Column(Integer, ForeignKey('user.user_id',
onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)
</code></pre>
<p>I want to insert a new row into this table, but I got a "Field 'order_id' doesn't have a default value" error. It seems that I have to set the id of order manually, because I got two primary-key. My question is, how can I insert a row that generate new ID automatically?</p>
<p>If I generate id manually, I got some problem. For example:</p>
<pre><code>maxId = DBSession.query(func.max(Order)).one()[0]
newOrder = Order(id=maxId + 1, buyer_id=xxx)
DBSession.add(newOrder)
</code></pre>
<p>Add a new order in this way seems ok, but however, we got some problem if two request run these code in almost same time.</p>
<p>If there is request a and b run this code in following order:</p>
<pre><code>a.maxId = DBSession.query(func.max(Order)).one()[0]
b.maxId = DBSession.query(func.max(Order)).one()[0]
b.newOrder = Order(id=maxId + 1, buyer_id=xxx)
b.DBSession.add(newOrder)
a.newOrder = Order(id=maxId + 1, buyer_id=xxx)
a.DBSession.add(newOrder)
</code></pre>
<p>Then the request a might failed, because there is already an order with same id in table. I can catch the exception and try again. But I am wondering, is there any better way to do?</p>
<p>Sometimes, the id is not simple integer, we might need order id like this:</p>
<p>2009090133 standards for 33rd order at 2009-09-01</p>
<p>In these case, autoincrement is not usable. So I have no choice, manualy assign id for order. So my another question is, is there any better way than catch exception and retry to insert a row with id.</p>
| 0 | 2009-09-03T10:01:31Z | 1,372,787 | <p>If you want sequential numbers per buyer for your orders then you'll have to serialize the transactions inserting to one buyer. You can do that by acquiring exclusive lock on the buyer row:</p>
<pre><code>sess.query(Buyer.id).with_lockmode('update').get(xxx)
order_id = sess.query(func.max(Order.id)+1).filter_by(buyer_id=xxx).scalar() or 1
sess.add(Order(id=order_id, buyer_id=xxx))
</code></pre>
<p>Using this pattern when two transactions try to insert order for one buyer in parallel one of them will block on the first line until the other transaction completes or fails.</p>
| 1 | 2009-09-03T11:10:21Z | [
"python",
"sql",
"database",
"sqlalchemy"
] |
How to insert a row with autoincrement id in a multi-primary-key table? | 1,372,525 | <p>I am writing a turbogears2 application. I have a table like this:</p>
<pre><code>class Order(DeclarativeBase):
__tablename__ = 'order'
# id of order
id = Column(Integer, autoincrement=True, primary_key=True)
# buyer's id
buyer_id = Column(Integer, ForeignKey('user.user_id',
onupdate="CASCADE", ondelete="CASCADE"), primary_key=True)
</code></pre>
<p>I want to insert a new row into this table, but I got a "Field 'order_id' doesn't have a default value" error. It seems that I have to set the id of order manually, because I got two primary-key. My question is, how can I insert a row that generate new ID automatically?</p>
<p>If I generate id manually, I got some problem. For example:</p>
<pre><code>maxId = DBSession.query(func.max(Order)).one()[0]
newOrder = Order(id=maxId + 1, buyer_id=xxx)
DBSession.add(newOrder)
</code></pre>
<p>Add a new order in this way seems ok, but however, we got some problem if two request run these code in almost same time.</p>
<p>If there is request a and b run this code in following order:</p>
<pre><code>a.maxId = DBSession.query(func.max(Order)).one()[0]
b.maxId = DBSession.query(func.max(Order)).one()[0]
b.newOrder = Order(id=maxId + 1, buyer_id=xxx)
b.DBSession.add(newOrder)
a.newOrder = Order(id=maxId + 1, buyer_id=xxx)
a.DBSession.add(newOrder)
</code></pre>
<p>Then the request a might failed, because there is already an order with same id in table. I can catch the exception and try again. But I am wondering, is there any better way to do?</p>
<p>Sometimes, the id is not simple integer, we might need order id like this:</p>
<p>2009090133 standards for 33rd order at 2009-09-01</p>
<p>In these case, autoincrement is not usable. So I have no choice, manualy assign id for order. So my another question is, is there any better way than catch exception and retry to insert a row with id.</p>
| 0 | 2009-09-03T10:01:31Z | 1,372,794 | <p>You should be using a default on your column definitions</p>
<pre><code>id = Column(Integer, default = sqlexpression)
</code></pre>
<p>Where sqlexpression can be a sql expression. Here is the <a href="http://www.sqlalchemy.org/docs/05/metadata.html#pre-executed-and-inline-sql-expressions" rel="nofollow">documentation</a>. For autoincrement you should use the sql expression <code>coalesce(select max(order.id) from order,0) + 1</code>. For ease you could import sqlalchemy.sql.text so the id column could look something like</p>
<pre><code>id = Column(Integer, default = text("coalesce(select max(order.id) from order,0) + 1"))
</code></pre>
| 1 | 2009-09-03T11:13:27Z | [
"python",
"sql",
"database",
"sqlalchemy"
] |
Algorithm to filter a set of all phrases containing in other phrase | 1,372,531 | <p>Given a set of phrases, i would like to filter the set of all phrases that contain any of the other phrases. Contained here means that if a phrase contains all the words of another phrase it should be filtered out. Order of the words within the phrase does not matter.</p>
<p>What i have so far is this:</p>
<ol>
<li>Sort the set by the number of words in each phrase. </li>
<li>For each phrase X in the set:
<ol>
<li>For each phrase Y in the rest of the set:
<ol>
<li>If all the words in X are in Y then X is contained in Y, discard Y.</li>
</ol></li>
</ol></li>
</ol>
<p>This is slow given a list of about 10k phrases.
Any better options?</p>
| 1 | 2009-09-03T10:02:23Z | 1,372,585 | <p>sort phrases by their contents, i.e., 'Z A' -> 'A Z', then eliminating phrases is easy going from shortest to longer ones.</p>
| 0 | 2009-09-03T10:12:19Z | [
"c#",
"java",
"c++",
"python",
"algorithm"
] |
Algorithm to filter a set of all phrases containing in other phrase | 1,372,531 | <p>Given a set of phrases, i would like to filter the set of all phrases that contain any of the other phrases. Contained here means that if a phrase contains all the words of another phrase it should be filtered out. Order of the words within the phrase does not matter.</p>
<p>What i have so far is this:</p>
<ol>
<li>Sort the set by the number of words in each phrase. </li>
<li>For each phrase X in the set:
<ol>
<li>For each phrase Y in the rest of the set:
<ol>
<li>If all the words in X are in Y then X is contained in Y, discard Y.</li>
</ol></li>
</ol></li>
</ol>
<p>This is slow given a list of about 10k phrases.
Any better options?</p>
| 1 | 2009-09-03T10:02:23Z | 1,372,627 | <p>You could build an index which maps words to phrases and do something like:</p>
<pre>
let matched = set of all phrases
for each word in the searched phrase
let wordMatch = all phrases containing the current word
let matched = intersection of matched and wordMatch
</pre>
<p>After this, <code>matched</code> would contain all phrases matching all words in the target phrase. It could be pretty well optimized by initializing <code>matched</code> to the set of all phrases containing only <code>words[0]</code>, and then only iterating over <code>words[1..words.length]</code>. Filtering phrases which are too short to match the target phrase may improve performance, too.</p>
<p>Unless I'm mistaken, a simple implementation has a worst case complexity (when the search phrase matches all phrases) of <code>O(n·m)</code>, where <code>n</code> is the number of words in the search phrase, and <code>m</code> is the number of phrases.</p>
| 1 | 2009-09-03T10:24:14Z | [
"c#",
"java",
"c++",
"python",
"algorithm"
] |
Algorithm to filter a set of all phrases containing in other phrase | 1,372,531 | <p>Given a set of phrases, i would like to filter the set of all phrases that contain any of the other phrases. Contained here means that if a phrase contains all the words of another phrase it should be filtered out. Order of the words within the phrase does not matter.</p>
<p>What i have so far is this:</p>
<ol>
<li>Sort the set by the number of words in each phrase. </li>
<li>For each phrase X in the set:
<ol>
<li>For each phrase Y in the rest of the set:
<ol>
<li>If all the words in X are in Y then X is contained in Y, discard Y.</li>
</ol></li>
</ol></li>
</ol>
<p>This is slow given a list of about 10k phrases.
Any better options?</p>
| 1 | 2009-09-03T10:02:23Z | 1,372,711 | <p>Your algo is quadratic in the number of phrases, that's probably what's slowing it down. Here I index phrases by words to get below quadratic in the common case.</p>
<pre><code># build index
foreach phrase: foreach word: phrases[word] += phrase
# use index to filter out phrases that contain all the words
# from another phrase
foreach phrase:
foreach word:
if first word:
siblings = phrases[word]
else
siblings = siblings intersection phrases[word]
# siblings now contains any phrase that has at least all our words
remove each sibling from the output set of phrases
# done!
</code></pre>
| 1 | 2009-09-03T10:47:38Z | [
"c#",
"java",
"c++",
"python",
"algorithm"
] |
Algorithm to filter a set of all phrases containing in other phrase | 1,372,531 | <p>Given a set of phrases, i would like to filter the set of all phrases that contain any of the other phrases. Contained here means that if a phrase contains all the words of another phrase it should be filtered out. Order of the words within the phrase does not matter.</p>
<p>What i have so far is this:</p>
<ol>
<li>Sort the set by the number of words in each phrase. </li>
<li>For each phrase X in the set:
<ol>
<li>For each phrase Y in the rest of the set:
<ol>
<li>If all the words in X are in Y then X is contained in Y, discard Y.</li>
</ol></li>
</ol></li>
</ol>
<p>This is slow given a list of about 10k phrases.
Any better options?</p>
| 1 | 2009-09-03T10:02:23Z | 1,372,721 | <p>This is the problem of finding minimal values of a set of sets. The naive algorithm and problem definition looks like this:</p>
<pre><code>set(s for s in sets if not any(other < s for other in sets))
</code></pre>
<p>There are sub-quadratic algorithms to do this (such as <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.4283" rel="nofollow">this</a>), but given that N is 10000 the efficiency of the implementation probably matters more. The optimal approach depends heavily on the distribution of the input data. Given that the input sets are natural language phrases that mostly differ, the approach suggested by redtuna should work well. Here's a python implementation of that algorithm. </p>
<pre><code>from collections import defaultdict
def find_minimal_phrases(phrases):
# Make the phrases hashable
phrases = map(frozenset, phrases)
# Create a map to find all phrases containing a word
phrases_containing = defaultdict(set)
for phrase in phrases:
for word in phrase:
phrases_containing[word].add(phrase)
minimal_phrases = []
found_superphrases = set()
# in sorted by length order to find minimal sets first thanks to the
# fact that a.superset(b) implies len(a) > len(b)
for phrase in sorted(phrases, key=len):
if phrase not in found_superphrases:
connected_phrases = [phrases_containing[word] for word in phrase]
connected_phrases.sort(key=len)
superphrases = reduce(set.intersection, connected_phrases)
found_superphrases.update(superphrases)
minimal_phrases.append(phrase)
return minimal_phrases
</code></pre>
<p>This is still quadratic, but on my machine it runs in 350ms for a set of 10k phrases containing 50% of minimal values with words from an exponential distribution.</p>
| 1 | 2009-09-03T10:50:09Z | [
"c#",
"java",
"c++",
"python",
"algorithm"
] |
Is there a python library/module for creating a multi ssh connection? | 1,372,657 | <p>I've been searching for a library that can access multiple ssh connections at once, Ruby has a Net::SSH::Multi module that allows multiple ssh connections at once. However I rather prefer coding this in Python, are there any similar SSH module for python?</p>
| 1 | 2009-09-03T10:32:59Z | 1,372,742 | <p><a href="http://www.lag.net/paramiko/" rel="nofollow">Paramiko</a> is Python's SSH library.</p>
<p>I've never tried concurrent connections with Paramiko, but <a href="http://stackoverflow.com/questions/1185855/parallel-ssh-in-python/1188586#1188586">this answer</a> says it's possible, and <a href="http://www.packetstormsecurity.org/Crackers/mtsshbrute.py.txt" rel="nofollow">this little script</a> seems to make multiple connections in different threads.</p>
<p>The Paramiko mailing list also <a href="http://www.lag.net/pipermail/paramiko/2008-January/000599.html" rel="nofollow">confirms it's possible to make multiple connections by forking</a> -- there was a security issue regarding that, and it was patched in early 2008.</p>
| 2 | 2009-09-03T10:57:45Z | [
"python",
"ruby",
"ssh"
] |
Reading a Django model's field options | 1,372,706 | <p>Is it possible to read a Django model's fields' options? For example, with the model:</p>
<pre><code>class MyModel(models.Model):
source_url = models.URLField(max_length=500)
...
</code></pre>
<p>i.e. how would I programmatically read the 'max_length' option from, say, within a view or form.</p>
<p>My current workaround is to define a separate class attribute:</p>
<pre><code>class MyModel(models.Model):
SOURCE_URL_MAX_LENGTH=500
source_url = models.URLField(max_length=SOURCE_URL_MAX_LENGTH)
...
</code></pre>
<p>I can then access that from anywhere that imports models.MyModel, e.g.:</p>
<pre><code> from models import MyModel
max_length = MyModel.SOURCE_URL_MAX_LENGTH
</code></pre>
| 1 | 2009-09-03T10:46:27Z | 1,372,896 | <p>Do it this way.</p>
<pre><code>from models import MyModel
try:
max_length = MyModel._meta.get_field('source_url').max_length
except:
max_length = None
</code></pre>
| 5 | 2009-09-03T11:36:13Z | [
"python",
"django"
] |
Django: remove GROUP BY added with extra() method? | 1,372,890 | <p>Hi (excuse me for my bad english) !</p>
<p>When I make this:</p>
<pre><code>gallery_qs = Gallery.objects.all()\
.annotate(Count('photos'))\
.extra(select={'photo_id': 'photologue_photo.id'})
</code></pre>
<p>The sql query is :</p>
<pre><code>SELECT (photologue_photo.id) AS `photo`, `photologue_gallery`.*
FROM `photologue_gallery`
LEFT OUTER JOIN `photologue_gallery_photos`
ON (`photologue_gallery`.`id` = `photologue_gallery_photos`.`gallery_id`)
LEFT OUTER JOIN `photologue_photo`
ON (`photologue_gallery_photos`.`photo_id` = `photologue_photo`.`id`)
GROUP BY `photologue_gallery`.`id`, photologue_photo.id
ORDER BY `photologue_gallery`.`publication_date` DESC
</code></pre>
<p>The problem is that <code>extra</code> method automatically adds photologue_photo.id in GROUP BY clause. And I need remove it, because it duplicates galleries, for example :</p>
<pre><code>[<Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>]
</code></pre>
<p>Si I need to make this query with django, is it possible ?</p>
<pre><code>SELECT (photologue_photo.id) AS `photo`, `photologue_gallery`.*
FROM `photologue_gallery`
LEFT OUTER JOIN `photologue_gallery_photos`
ON (`photologue_gallery`.`id` = `photologue_gallery_photos`.`gallery_id`)
LEFT OUTER JOIN `photologue_photo`
ON (`photologue_gallery_photos`.`photo_id` = `photologue_photo`.`id`)
GROUP BY `photologue_gallery`
ORDER BY `photologue_gallery`.`publication_date` DESC
</code></pre>
<p>Thank you ! :)</p>
| 1 | 2009-09-03T11:34:36Z | 1,375,836 | <p>I don't think you really need the extra. From Django's concept, you don't need to cherry pick specific columns while running a Django QuerySet. That logic can be done in the template side.</p>
<p>I assume you know how to push <code>galley_qs</code> to your template from your view:</p>
<pre><code># views.py
gallery_qs = Gallery.objects.all()\
.annotate(Count('photos'))
</code></pre>
<p>In your template/html:</p>
<pre><code>{% for gallery in gallery_qs %}
{% for photo in gallery.photos %}
{% endfor %}
{% endfor %}
</code></pre>
<p><code>photos</code> is your ManyToManyField in your gallery model.</p>
| 1 | 2009-09-03T20:43:03Z | [
"python",
"sql",
"django",
"django-models",
"photologue"
] |
Django: remove GROUP BY added with extra() method? | 1,372,890 | <p>Hi (excuse me for my bad english) !</p>
<p>When I make this:</p>
<pre><code>gallery_qs = Gallery.objects.all()\
.annotate(Count('photos'))\
.extra(select={'photo_id': 'photologue_photo.id'})
</code></pre>
<p>The sql query is :</p>
<pre><code>SELECT (photologue_photo.id) AS `photo`, `photologue_gallery`.*
FROM `photologue_gallery`
LEFT OUTER JOIN `photologue_gallery_photos`
ON (`photologue_gallery`.`id` = `photologue_gallery_photos`.`gallery_id`)
LEFT OUTER JOIN `photologue_photo`
ON (`photologue_gallery_photos`.`photo_id` = `photologue_photo`.`id`)
GROUP BY `photologue_gallery`.`id`, photologue_photo.id
ORDER BY `photologue_gallery`.`publication_date` DESC
</code></pre>
<p>The problem is that <code>extra</code> method automatically adds photologue_photo.id in GROUP BY clause. And I need remove it, because it duplicates galleries, for example :</p>
<pre><code>[<Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>]
</code></pre>
<p>Si I need to make this query with django, is it possible ?</p>
<pre><code>SELECT (photologue_photo.id) AS `photo`, `photologue_gallery`.*
FROM `photologue_gallery`
LEFT OUTER JOIN `photologue_gallery_photos`
ON (`photologue_gallery`.`id` = `photologue_gallery_photos`.`gallery_id`)
LEFT OUTER JOIN `photologue_photo`
ON (`photologue_gallery_photos`.`photo_id` = `photologue_photo`.`id`)
GROUP BY `photologue_gallery`
ORDER BY `photologue_gallery`.`publication_date` DESC
</code></pre>
<p>Thank you ! :)</p>
| 1 | 2009-09-03T11:34:36Z | 1,376,682 | <p>Why are you trying to get distinct gallery records with a photo_id annotated on them when gallery to photo ids is a many to many relationship? From what I can tell, the query you are doing would only get a single photo id for each gallery.</p>
<p>If you really do need to do the above, I think you could use distinct() to get distinct gallery records (btw, you don't need the "all()" in there).</p>
<pre><code>Gallery.objects.distinct()\
.annotate(Count('photos'))\
.extra(select={'photo_id': 'photologue_photo.id'})
</code></pre>
<p>Or you could just simply access the photo id directly,</p>
<pre><code>g = Gallery.objects.annotate(Count('photos'))
# Get the photo
photo = g.photos[0]
</code></pre>
| 0 | 2009-09-04T00:30:47Z | [
"python",
"sql",
"django",
"django-models",
"photologue"
] |
Beginner graphics program in Python giving 'out of stack space' error | 1,372,949 | <p>I'm currently learning Python using Zelle's Introductory text, and I'm trying to recreate one of the example programs which uses an accompanying file graphics.py. Because I'm using Python 3.1 and the text was written for 2.x though, I'm using the GraphicsPy3.py file found at <a href="http://mcsp.wartburg.edu/zelle/python" rel="nofollow">http://mcsp.wartburg.edu/zelle/python</a> and renaming it graphics.py on my computer.</p>
<p>The file named futval_graph.py is as follows:</p>
<pre><code>from graphics import *
def main():
print("This program plots the growth of a 10-year investment.")
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annualized interest rate: "))
win = GraphWin("Investment Grown Chart", 320, 420)
win.setBackground("white")
Text(Point(20, 230), ' 0.0K').draw(win)
Text(Point(20, 180), ' 2.5K').draw(win)
Text(Point(20, 130), ' 5.0K').draw(win)
Text(Point(20, 80), ' 7.5K').draw(win)
Text(Point(20, 30), '10.0K').draw(win)
# Rest of code is here but I've commented it out to isolate the problem.
main()
</code></pre>
<p>When I run 'import futval_graph' on a fresh IDLE session the program simply runs and then hangs after inputing 'apr' without opening the new graphics window. When I run the program from the command line I get the following result:</p>
<blockquote>
<p>C:\Python31>futval_graph.py<br />
This program plots the growth of a 10-year investment.<br />
Enter the initial principal: error in background error handler:<br />
out of stack space (infinite loop?)<br />
while executing<br />
"::tcl::Bgerror {out of stack space (infinite loop?)} {-code 1 -level 0 -errorco de NONE -errorinfo {out of stack space (infinite loop?)<br />
while execu..." </p>
</blockquote>
<p>Especially frustrating is the fact that this series of commands works when entered into a fresh session of IDLE. And then when running 'import futval_graph' from IDLE after all of the commands have been run on their own, futval_graph works properly.</p>
<p>So my question is: how can I get futval_graph.py to run properly both from the command line and IDLE? Sorry if my explanation of the problem is a bit scattered. Let me know if any further info would help clarify.</p>
| 4 | 2009-09-03T11:49:33Z | 1,373,063 | <p>There appears to be a problem with the Python 3 version of graphics.py.</p>
<p>I downloaded the Python 3 version, renamed it to graphics.py, then ran the following.</p>
<pre><code>PS C:\Users\jaraco\Desktop> python
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from graphics import *
>>> dir()
['BAD_OPTION', 'Circle', 'DEAD_THREAD', 'DEFAULT_CONFIG', 'Entry', 'GraphWin', 'GraphicsError', 'GraphicsObject', 'Image', 'Line', 'OBJ_ALREADY_DRAWN', 'Oval',
'Pixmap', 'Point', 'Polygon', 'Queue', 'Rectangle', 'Text', 'Transform', 'UNSUPPORTED_METHOD', '\_\_builtins\_\_', '\_\_doc\_\_', '\_\_name\_\_', '\_\_package\_\_', 'atexit', 'color_rgb', 'copy', 'os', 'sys', 'test', 'time', 'tk']
>>> error in background error handler:
out of stack space (infinite loop?)
while executing
"::tcl::Bgerror {out of stack space (infinite loop?)} {-code 1 -level 0 -errorcode NONE -errorinfo {out of stack space (infinite loop?)
while execu..."
</code></pre>
<p>As you can see, I get the same error, and I haven't even executed anything in the module. There appears to be a problem with the library itself, and not something you're doing in your code.</p>
<p>I would report this to the author, as he suggests.</p>
<p>I did find that I did not get the error if I simply imported the graphics module.</p>
<pre><code>>>> import graphics
>>> dir(graphics)
</code></pre>
<p>I found that if I did this to your code, and then changed references GraphWin to graphics.GraphWin, Text to graphics.Text, and Point to graphics.Point, the problem seemed to go away, and I could run it from the command line.</p>
<pre><code>import graphics
def main():
print("This program plots the growth of a 10-year investment.")
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annualized interest rate: "))
win = graphics.GraphWin("Investment Grown Chart", 320, 420)
win.setBackground("white")
graphics.Text(graphics.Point(20, 230), ' 0.0K').draw(win)
graphics.Text(graphics.Point(20, 180), ' 2.5K').draw(win)
graphics.Text(graphics.Point(20, 130), ' 5.0K').draw(win)
graphics.Text(graphics.Point(20, 80), ' 7.5K').draw(win)
graphics.Text(graphics.Point(20, 30), '10.0K').draw(win)
# Rest of code is here but I've commented it out to isolate the problem.
main()
</code></pre>
<p>Why should this be? It shouldn't. It appears the graphics.py module has some side-effect that's not behaving properly.</p>
<p>I suspect you would not be running into these errors under the Python 2.x version.</p>
| 2 | 2009-09-03T12:17:36Z | [
"python"
] |
Beginner graphics program in Python giving 'out of stack space' error | 1,372,949 | <p>I'm currently learning Python using Zelle's Introductory text, and I'm trying to recreate one of the example programs which uses an accompanying file graphics.py. Because I'm using Python 3.1 and the text was written for 2.x though, I'm using the GraphicsPy3.py file found at <a href="http://mcsp.wartburg.edu/zelle/python" rel="nofollow">http://mcsp.wartburg.edu/zelle/python</a> and renaming it graphics.py on my computer.</p>
<p>The file named futval_graph.py is as follows:</p>
<pre><code>from graphics import *
def main():
print("This program plots the growth of a 10-year investment.")
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annualized interest rate: "))
win = GraphWin("Investment Grown Chart", 320, 420)
win.setBackground("white")
Text(Point(20, 230), ' 0.0K').draw(win)
Text(Point(20, 180), ' 2.5K').draw(win)
Text(Point(20, 130), ' 5.0K').draw(win)
Text(Point(20, 80), ' 7.5K').draw(win)
Text(Point(20, 30), '10.0K').draw(win)
# Rest of code is here but I've commented it out to isolate the problem.
main()
</code></pre>
<p>When I run 'import futval_graph' on a fresh IDLE session the program simply runs and then hangs after inputing 'apr' without opening the new graphics window. When I run the program from the command line I get the following result:</p>
<blockquote>
<p>C:\Python31>futval_graph.py<br />
This program plots the growth of a 10-year investment.<br />
Enter the initial principal: error in background error handler:<br />
out of stack space (infinite loop?)<br />
while executing<br />
"::tcl::Bgerror {out of stack space (infinite loop?)} {-code 1 -level 0 -errorco de NONE -errorinfo {out of stack space (infinite loop?)<br />
while execu..." </p>
</blockquote>
<p>Especially frustrating is the fact that this series of commands works when entered into a fresh session of IDLE. And then when running 'import futval_graph' from IDLE after all of the commands have been run on their own, futval_graph works properly.</p>
<p>So my question is: how can I get futval_graph.py to run properly both from the command line and IDLE? Sorry if my explanation of the problem is a bit scattered. Let me know if any further info would help clarify.</p>
| 4 | 2009-09-03T11:49:33Z | 1,373,069 | <p>your code has issues with buil-in <code>input</code>, when it's called with non-empty string as argument. I suspect it might have something to do with the thread setup that <code>graphics</code> does.</p>
<p>If you make Tkinter widgets to read these inputs, may be it'll solve your problem.</p>
<p>To be honest, when you download <code>graphicsPy3.py</code> it says:</p>
<blockquote>
<p>Graphics library ported to Python 3.x. Still experimental, please report any issues.</p>
</blockquote>
<p>so, I suppose, you better follow this recommendation.</p>
| 1 | 2009-09-03T12:18:22Z | [
"python"
] |
Beginner graphics program in Python giving 'out of stack space' error | 1,372,949 | <p>I'm currently learning Python using Zelle's Introductory text, and I'm trying to recreate one of the example programs which uses an accompanying file graphics.py. Because I'm using Python 3.1 and the text was written for 2.x though, I'm using the GraphicsPy3.py file found at <a href="http://mcsp.wartburg.edu/zelle/python" rel="nofollow">http://mcsp.wartburg.edu/zelle/python</a> and renaming it graphics.py on my computer.</p>
<p>The file named futval_graph.py is as follows:</p>
<pre><code>from graphics import *
def main():
print("This program plots the growth of a 10-year investment.")
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annualized interest rate: "))
win = GraphWin("Investment Grown Chart", 320, 420)
win.setBackground("white")
Text(Point(20, 230), ' 0.0K').draw(win)
Text(Point(20, 180), ' 2.5K').draw(win)
Text(Point(20, 130), ' 5.0K').draw(win)
Text(Point(20, 80), ' 7.5K').draw(win)
Text(Point(20, 30), '10.0K').draw(win)
# Rest of code is here but I've commented it out to isolate the problem.
main()
</code></pre>
<p>When I run 'import futval_graph' on a fresh IDLE session the program simply runs and then hangs after inputing 'apr' without opening the new graphics window. When I run the program from the command line I get the following result:</p>
<blockquote>
<p>C:\Python31>futval_graph.py<br />
This program plots the growth of a 10-year investment.<br />
Enter the initial principal: error in background error handler:<br />
out of stack space (infinite loop?)<br />
while executing<br />
"::tcl::Bgerror {out of stack space (infinite loop?)} {-code 1 -level 0 -errorco de NONE -errorinfo {out of stack space (infinite loop?)<br />
while execu..." </p>
</blockquote>
<p>Especially frustrating is the fact that this series of commands works when entered into a fresh session of IDLE. And then when running 'import futval_graph' from IDLE after all of the commands have been run on their own, futval_graph works properly.</p>
<p>So my question is: how can I get futval_graph.py to run properly both from the command line and IDLE? Sorry if my explanation of the problem is a bit scattered. Let me know if any further info would help clarify.</p>
| 4 | 2009-09-03T11:49:33Z | 1,383,262 | <p>After some additional research, it does appear that the call to input() does have some impact on triggering the unwanted behavior.</p>
<p>I re-wrote the program to not import the graphics module until after the input() calls were complete. In this case, I was unable to reproduce the error, and the code seemed to behave normally even when run from the command-line. I was able to get the parameters from the user, then it would begin to draw a graph (although with the sample code, only very little was drawn before the app closed). Perhaps this technique is a suitable workaround for your problem.</p>
<p>The underlying problem seems to have something to do with the way the tkinter module is initialized in a separate thread, and some undesirable interactions between threads. My guess is that the input() method, when run from a command-line, either locks a resource or otherwise triggers behavior that causes the Tk thread to go into an infinite loop.</p>
<p>Doing some searches around the Internet, I see that other users have gotten the same error, but for other reasons. Some were getting it when tkinter was built without thread support, but I don't think that applies here.</p>
| 0 | 2009-09-05T12:49:46Z | [
"python"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 1,373,185 | <p>Use dictionaries to accomplish this. Dictionaries are stores of keys and values. </p>
<pre><code>>>> dct = {'x': 1, 'y': 2, 'z': 3}
>>> dct
{'y': 2, 'x': 1, 'z': 3}
>>> dct["y"]
2
</code></pre>
<p>You can use variable key names to achieve the effect of variable variables without the security risk.</p>
<pre><code>>>> x = "spam"
>>> z = {x: "eggs"}
>>> z["spam"]
'eggs'
</code></pre>
<p>Make sense?</p>
| 92 | 2009-09-03T12:41:05Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 1,373,192 | <p>Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing</p>
<pre><code>$foo = "bar"
$$foo = "baz"
</code></pre>
<p>you write </p>
<pre><code>mydict = {}
foo = "bar"
mydict[foo] = "baz"
</code></pre>
<p>This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".</p>
| 21 | 2009-09-03T12:42:00Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 1,373,198 | <p>Use the built-in <a href="http://docs.python.org/library/functions.html#getattr"><code>getattr</code></a> function to get an attribute on an object by name. Modify the name as needed.</p>
<pre><code>obj.spam = 'eggs'
name = 'spam'
getattr(obj, name) # returns 'eggs'
</code></pre>
| 38 | 2009-09-03T12:43:26Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 1,373,201 | <p>It's not a good idea. If you are accessing a global variable you can use <a href="http://docs.python.org/library/functions.html#globals">globals()</a>.</p>
<pre><code>>>> a = 10
>>> globals()['a']
10
</code></pre>
<p>If you want to access a variable in the local scope you can use <a href="http://docs.python.org/library/functions.html#locals">locals()</a>, but you cannot assign values to the returned dict.</p>
<p><strong>A better solution</strong> is to use <code>getattr</code> or store your variables in a dictionary and then access them by name.</p>
| 33 | 2009-09-03T12:43:49Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 37,725,113 | <p>The consensus is to use a dictionary for this - see the other answers. This is a good idea for most cases, however, there are many aspects arising from this:</p>
<ul>
<li>you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc.</li>
<li>there's either no locality or globality for variable variables, it depends on the globality of the dictionary</li>
<li>if you want to rename a variable name, you'll have to do it manually</li>
<li>however, you are much more flexible, e.g.
<ul>
<li>you can decide to overwrite existing variables or ...</li>
<li>... choose to implement const variables</li>
<li>to raise an exception on overwriting for different types</li>
<li>etc.</li>
</ul></li>
</ul>
<p>That said, I've implemented a <a href="https://sourceforge.net/projects/python-vvm/" rel="nofollow">variable variables manager</a>-class which provides some of the above ideas. It works for python 2 and 3.</p>
<p>You'd use <a href="https://sourceforge.net/p/python-vvm/code/ci/master/tree/variableVariablesManager.py" rel="nofollow">the class</a> like this:</p>
<pre><code>from variableVariablesManager import VariableVariablesManager
myVars = VariableVariablesManager()
myVars['test'] = 25
print(myVars['test'])
# define a const variable
myVars.defineConstVariable('myconst', 13)
try:
myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
print("not allowed")
except AttributeError as e:
pass
# rename a variable
myVars.renameVariable('myconst', 'myconstOther')
# preserve locality
def testLocalVar():
myVars = VariableVariablesManager()
myVars['test'] = 13
print("inside function myVars['test']:", myVars['test'])
testLocalVar()
print("outside function myVars['test']:", myVars['test'])
# define a global variable
myVars.defineGlobalVariable('globalVar', 12)
def testGlobalVar():
myVars = VariableVariablesManager()
print("inside function myVars['globalVar']:", myVars['globalVar'])
myVars['globalVar'] = 13
print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
testGlobalVar()
print("outside function myVars['globalVar']:", myVars['globalVar'])
</code></pre>
<p>If you wish to allow overwriting of variables with the same type only:</p>
<pre><code>myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
myVars['test'] = 25
myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)
</code></pre>
| 0 | 2016-06-09T11:47:06Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 37,725,729 | <p>You have to use <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow">globals() built in method</a> to achieve that behaviour:</p>
<pre><code>def var_of_var(k, v):
globals()[k] = v
print variable_name # NameError: name 'variable_name' is not defined
some_name = 'variable_name'
globals()[some_name] = 123
print variable_name # 123
some_name = 'variable_name2'
var_of_var(some_name, 456)
print variable_name2 # 456
</code></pre>
| 1 | 2016-06-09T12:14:11Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 37,971,967 | <p>Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.</p>
<p>for example:</p>
<pre><code>#using dictionary
variables = {}
variables["first"] = 34
variables["second"] = 45
print variables["first"], variables["second"]
#using namedtuple
Variables = namedtuple('Variables', ['first', 'second'])
vars = Variables(34, 45)
print vars.first, vars.second
</code></pre>
| 3 | 2016-06-22T15:09:32Z | [
"python",
"variable-variables"
] |
How do I create a variable number of variables in Python? | 1,373,164 | <p>How do I accomplish variable variables in Python? </p>
<p>Here is an elaborative manual entry, for instance: <em><a href="http://us3.php.net/manual/en/language.variables.variable.php">Variable variables</a></em></p>
<p>I have heard this is a bad idea in general though, and it is a security hole in Python. Is that true?</p>
| 96 | 2009-09-03T12:37:48Z | 38,972,761 | <p>New coders sometimes write code like this:</p>
<pre><code>my_calculator.button_0 = tkinter.Button(root, text=0)
my_calculator.button_1 = tkinter.Button(root, text=1)
my_calculator.button_2 = tkinter.Button(root, text=2)
...
</code></pre>
<p>The coder is then left with a pile of named variables, with a coding effort of O(<em>m</em> * <em>n</em>), where <em>m</em> is the number of named variables and <em>n</em> is the number of times that group of variables needs to be accessed (including creation). The more astute beginner observes that the only difference in each of those lines is a number that changes based on a rule, and decides to use a loop. However, they get stuck on how to dynamically create those variable names, and may try something like this:</p>
<pre><code>for i in range(10):
my_calculator.('button_%d' % i) = tkinter.Button(root, text=i)
</code></pre>
<p>They soon find that this does not work.</p>
<p>If the program requires arbitrary variable "names," a dictionary is the best choice, as explained in other answers. However, if you're simply trying to create many variables and you don't mind referring to them with a sequence of integers, you're probably looking for a <code>list</code>. This is particularly true if your data are homogeneous, such as daily temperature readings, weekly quiz scores, or a grid of graphical widgets.</p>
<p>This can be assembled as follows:</p>
<pre><code>my_calculator.buttons = []
for i in range(10):
my_calculator.buttons.append(tkinter.Button(root, text=i))
</code></pre>
<p>This <code>list</code> can also be created in one line with a comprehension:</p>
<pre><code>my_calculator.buttons = [tkinter.Button(root, text=i) for i in range(10)]
</code></pre>
<p>The result in either case is a populated <code>list</code>, with the first element accessed with <code>my_calculator.buttons[0]</code>, the next with <code>my_calculator.buttons[1]</code>, and so on. The "base" variable name becomes the name of the <code>list</code> and the varying identifier is used to access it.</p>
<p>Finally, don't forget other data structures, such as the <code>set</code> - this is similar to a dictionary, except that each "name" doesn't have a value attached to it. If you simply need a "bag" of objects, this can be a great choice. Instead of something like this:</p>
<pre><code>keyword_1 = 'apple'
keyword_2 = 'banana'
if query == keyword_1 or query == keyword_2:
print('Match.')
</code></pre>
<p>You will have this:</p>
<pre><code>keywords = {'apple', 'banana'}
if query in keywords:
print('Match.')
</code></pre>
<p>Use a <code>list</code> for a sequence of similar objects, a <code>set</code> for an arbitrarily-ordered bag of objects, or a <code>dict</code> for a bag of names with associated values.</p>
| 0 | 2016-08-16T10:41:07Z | [
"python",
"variable-variables"
] |
making python 2.6 exception backward compatible | 1,373,255 | <p>I have the following python code:</p>
<pre><code> try:
pr.update()
except ConfigurationException as e:
returnString=e.line+' '+e.errormsg
</code></pre>
<p>This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you!</p>
| 7 | 2009-09-03T12:55:16Z | 1,373,261 | <p>This is backward compatible: </p>
<pre><code>try:
pr.update()
except ConfigurationException, e:
returnString=e.line+' '+e.errormsg
</code></pre>
| 9 | 2009-09-03T12:56:38Z | [
"python",
"exception",
"syntax",
"python-2.x"
] |
making python 2.6 exception backward compatible | 1,373,255 | <p>I have the following python code:</p>
<pre><code> try:
pr.update()
except ConfigurationException as e:
returnString=e.line+' '+e.errormsg
</code></pre>
<p>This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you!</p>
| 7 | 2009-09-03T12:55:16Z | 1,373,263 | <pre><code>try:
pr.update()
except ConfigurationException, e:
returnString = e.line + " " + e.errormsg
</code></pre>
| 1 | 2009-09-03T12:56:58Z | [
"python",
"exception",
"syntax",
"python-2.x"
] |
making python 2.6 exception backward compatible | 1,373,255 | <p>I have the following python code:</p>
<pre><code> try:
pr.update()
except ConfigurationException as e:
returnString=e.line+' '+e.errormsg
</code></pre>
<p>This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you!</p>
| 7 | 2009-09-03T12:55:16Z | 1,373,269 | <p>Read this: <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-try-statement">http://docs.python.org/reference/compound%5Fstmts.html#the-try-statement</a></p>
<p>and this: <a href="http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes">http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes</a></p>
<p>Don't use <code>as</code>, use a <code>,</code>.</p>
<p>The <code>as</code> syntax is specifically NOT backwards compatible because the <code>,</code> syntax is ambiguous and must go away in Python 3.</p>
| 5 | 2009-09-03T12:58:44Z | [
"python",
"exception",
"syntax",
"python-2.x"
] |
making python 2.6 exception backward compatible | 1,373,255 | <p>I have the following python code:</p>
<pre><code> try:
pr.update()
except ConfigurationException as e:
returnString=e.line+' '+e.errormsg
</code></pre>
<p>This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you!</p>
| 7 | 2009-09-03T12:55:16Z | 2,513,890 | <p>This is both backward AND forward compatible:</p>
<pre><code>import sys
try:
pr.update()
except (ConfigurationException,):
e = sys.exc_info()[1]
returnString = "%s %s" % (e.line, e.errormsg)
</code></pre>
<p>This gets rid of the ambiguity problem in python 2.5 and earlier, while still not losing any of the advantages of the python 2.6/3 variation i.e. can still unambiguously catch multiple exception types e.g. <code>except (ConfigurationException, AnotherExceptionType):</code> and, if per-type handling is needed, can still test for <code>exc_info()[0]==AnotherExceptionType</code>.</p>
| 12 | 2010-03-25T08:12:15Z | [
"python",
"exception",
"syntax",
"python-2.x"
] |
File open: Is this bad Python style? | 1,373,660 | <p>To read contents of a file:</p>
<pre><code>data = open(filename, "r").read()
</code></pre>
<p>The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.</p>
<p>EDIT: This has actually bitten me in a project I wrote - it prompted me to ask <a href="http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python/2023791#2023791">this</a> question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.</p>
| 10 | 2009-09-03T14:17:26Z | 1,373,672 | <p>No, it's perfectly reasonable Python style IMO, as per your reasoning.</p>
<p><strong>Update:</strong> There are a lot of comments here about whether file objects get tidied up straight away or not. Rather than speculate, I did some digging. Here's what I see:
<hr/>
From a comment in Python's <a href="http://svn.python.org/view/python/trunk/Include/object.h?revision=72461&view=markup" rel="nofollow"><code>object.h</code></a>:</p>
<blockquote>
<p>The macros Py_INCREF(op) and
Py_DECREF(op) are used to increment or
decrement reference counts. Py_DECREF
calls the object's deallocator
function when the refcount falls to 0</p>
</blockquote>
<p>Looking in Python's <a href="http://svn.python.org/view/python/trunk/Objects/fileobject.c?view=markup" rel="nofollow"><code>fileobject.c</code></a>:</p>
<p>The function table for file objects points to function <code>file_dealloc</code>. This function
calls <code>close_the_file</code>, which in turn closes the file.
<hr/>
So it seems reasonable to state that at the moment, on CPython, when there are no
more references to a file object, it's closed without any delay. If you think this interpretation is wrong, please post a comment indicating why you feel that way.</p>
| 3 | 2009-09-03T14:19:17Z | [
"python",
"file",
"file-io",
"coding-style"
] |
File open: Is this bad Python style? | 1,373,660 | <p>To read contents of a file:</p>
<pre><code>data = open(filename, "r").read()
</code></pre>
<p>The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.</p>
<p>EDIT: This has actually bitten me in a project I wrote - it prompted me to ask <a href="http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python/2023791#2023791">this</a> question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.</p>
| 10 | 2009-09-03T14:17:26Z | 1,373,677 | <p>looks fine to me.. I read files like that often.</p>
| 1 | 2009-09-03T14:20:12Z | [
"python",
"file",
"file-io",
"coding-style"
] |
File open: Is this bad Python style? | 1,373,660 | <p>To read contents of a file:</p>
<pre><code>data = open(filename, "r").read()
</code></pre>
<p>The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.</p>
<p>EDIT: This has actually bitten me in a project I wrote - it prompted me to ask <a href="http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python/2023791#2023791">this</a> question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.</p>
| 10 | 2009-09-03T14:17:26Z | 1,373,690 | <p>It is true that it will close eventually, but eventually might not be soon enough. Especially if you're using this inside a loop, the system might run out of file handles before the GC gets to the file objects.</p>
| 6 | 2009-09-03T14:21:38Z | [
"python",
"file",
"file-io",
"coding-style"
] |
File open: Is this bad Python style? | 1,373,660 | <p>To read contents of a file:</p>
<pre><code>data = open(filename, "r").read()
</code></pre>
<p>The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.</p>
<p>EDIT: This has actually bitten me in a project I wrote - it prompted me to ask <a href="http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python/2023791#2023791">this</a> question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.</p>
| 10 | 2009-09-03T14:17:26Z | 1,373,713 | <p>Just for the record:
This is only slightly longer, and closes the file immediately:</p>
<pre><code>from __future__ import with_statement
with open(filename, "r") as f:
data = f.read()
</code></pre>
| 29 | 2009-09-03T14:24:50Z | [
"python",
"file",
"file-io",
"coding-style"
] |
File open: Is this bad Python style? | 1,373,660 | <p>To read contents of a file:</p>
<pre><code>data = open(filename, "r").read()
</code></pre>
<p>The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.</p>
<p>EDIT: This has actually bitten me in a project I wrote - it prompted me to ask <a href="http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python/2023791#2023791">this</a> question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.</p>
| 10 | 2009-09-03T14:17:26Z | 1,373,828 | <p>The code works exactly as you say it does, but it's bad style nevertheless. Your code relies on assumptions which may be true now, but won't always be true. It's not impossible that your code will be run in a situation where the file being opened and not close <em>does</em> matter. Is it really worth that risk just to save 1 or 2 lines of code? I don't think so.</p>
| 4 | 2009-09-03T14:40:49Z | [
"python",
"file",
"file-io",
"coding-style"
] |
File open: Is this bad Python style? | 1,373,660 | <p>To read contents of a file:</p>
<pre><code>data = open(filename, "r").read()
</code></pre>
<p>The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.</p>
<p>EDIT: This has actually bitten me in a project I wrote - it prompted me to ask <a href="http://stackoverflow.com/questions/2023608/check-what-files-are-open-in-python/2023791#2023791">this</a> question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.</p>
| 10 | 2009-09-03T14:17:26Z | 2,047,151 | <p>Even though it works as expected, I think it fails in two counts:</p>
<ol>
<li>Your code will not scale up seamlessly, because you are reading the entire file into memory, and this may or may not be necessarily what you want.</li>
<li>According to the Zen of Python (try <code>import this</code> in the Python prompt to retrieve it) "explicit is better than implicit" and, by failing to explicitly close the file, you could confuse someone who, down the road, will be left with your code for maintenance.</li>
</ol>
<p>It really helps being explicit! Python encourages explicit style.</p>
<p>Other than that, for a throwaway script, your style makes sense.</p>
<p>Maybe you will benefit from <a href="http://stackoverflow.com/questions/1885868/pythonic-way-to-read-a-set-number-of-lines-from-a-file/1885999#1885999">this answer</a>.</p>
| 2 | 2010-01-12T06:30:14Z | [
"python",
"file",
"file-io",
"coding-style"
] |
using soaplib to connect to remote SOAP server lacking definition | 1,373,738 | <p>I am looking at the soaplib python module (it comes with standard ubuntu 9.04). I have used xmlrpclib extensively in the last years but now I am curious about soap. writing servers with soaplib is acceptably easy, I assume writing clients should be even easier.</p>
<p>in my impatience I can't find a way to make use of introspection. do I really need to describe each and every method in the server in order to define the client ( <a href="http://trac.optio.webfactional.com/wiki/Client" rel="nofollow">http://trac.optio.webfactional.com/wiki/Client</a> )? </p>
<p>I find this difficult to believe, but I can't find any significant web page holding my three search terms: python soap introspect...</p>
<p>so the question sounds: can I use Python soaplib to access just any remote web service of which I only know the URL? and how do I do that?</p>
<p>am I or is the library missing something? </p>
| 2 | 2009-09-03T14:28:23Z | 1,394,011 | <p>If I understand your question correctly, you would like to generate client code for a given webservice without defining what methods etc are availible on that service in your own code directly? IE: you would like to introspect the service and generate client automatically.</p>
<p>If this is the case then the answer is that you need to use the <a href="http://github.com/jkp/soaplib/tree/master" rel="nofollow">soaplib trunk</a>. Specifically you will be interested in a <a href="http://github.com/jkp/soaplib/blob/f61ddf293c67d6e3a95fa9d75c6e354e38969b52/soaplib/ext/wsdl2py.py" rel="nofollow">recently contributed script</a> that allows the generation of Python classes to act as a client to a given service as described in a <a href="http://en.wikipedia.org/wiki/Web%5FServices%5FDescription%5FLanguage" rel="nofollow">WSDL</a> file. There are scripts in soaplib to allow the generation of classes both in a static manner (where a .py module is generated and written to disk) and in a dynamic manner where the classes exist only at runtime in your program.</p>
<p>Hope that helps.</p>
| 1 | 2009-09-08T13:22:39Z | [
"python",
"soap",
"introspection"
] |
Benefit cost analysis libraries | 1,373,902 | <p>I was wondering if there are any opensource libraries that are geared towards transportation ben/cost analysis. </p>
<p>I currently use <a href="http://www.dot.ca.gov/hq/tpp/offices/ote/benefit%5Fcost/models/microbencost.html" rel="nofollow">microBENCOST</a> and would like to build my own solution. I'm most comfortable with C/c++ and Python. </p>
<p>cheers</p>
| 2 | 2009-09-03T14:53:00Z | 1,410,655 | <p>microBENCOST is purchased by the californian department of transport and really it seems a suitable tool. What is missing? If you need something particular that is not yet implemented, maybe you should consider to write your own. It's really difficult to find something better </p>
| 1 | 2009-09-11T12:48:12Z | [
"c++",
"python",
"transport",
"economics"
] |
Benefit cost analysis libraries | 1,373,902 | <p>I was wondering if there are any opensource libraries that are geared towards transportation ben/cost analysis. </p>
<p>I currently use <a href="http://www.dot.ca.gov/hq/tpp/offices/ote/benefit%5Fcost/models/microbencost.html" rel="nofollow">microBENCOST</a> and would like to build my own solution. I'm most comfortable with C/c++ and Python. </p>
<p>cheers</p>
| 2 | 2009-09-03T14:53:00Z | 1,425,624 | <p>I don't think there are any alternatives, considering MicroBENCOST appears to be a special project developed for the state of California, and transportation analysis is about as niche as it gets.</p>
<p>If you are going to build your own solution, you will probably want to look into the various math libraries available to Python - particularly <a href="http://numpy.scipy.og" rel="nofollow">numpy</a> and/or <a href="http://scipy.org" rel="nofollow">scipy</a>.</p>
| 2 | 2009-09-15T07:16:21Z | [
"c++",
"python",
"transport",
"economics"
] |
Benefit cost analysis libraries | 1,373,902 | <p>I was wondering if there are any opensource libraries that are geared towards transportation ben/cost analysis. </p>
<p>I currently use <a href="http://www.dot.ca.gov/hq/tpp/offices/ote/benefit%5Fcost/models/microbencost.html" rel="nofollow">microBENCOST</a> and would like to build my own solution. I'm most comfortable with C/c++ and Python. </p>
<p>cheers</p>
| 2 | 2009-09-03T14:53:00Z | 1,430,169 | <p>My girlfriend works for a transportation planning firm, and they use a variety of models developed in SPSS, with a lot of data munging in Excel and visualization in ArcGIS. As far as turnkey solutions go, though, I think you're going to be more or less on your own.</p>
<p>Assuming you want to move on to something a bit newer/more maintainable than a DOS application like MicroBENCOST, though, I would second the recommendation to become comfortable with <a href="http://scipy.org/" rel="nofollow">Scipy</a>, and then start building up a toolbox of statistical models based on the original application. For other types of modeling, you may also find <a href="http://simpy.sourceforge.net/" rel="nofollow">SimPy</a> useful; it doesn't do the simplified cost/benefit analysis that MicroBENCOST does, but it may be applicable for more open-ended design problems where original discrete simulation models are called for. </p>
| 4 | 2009-09-15T23:34:19Z | [
"c++",
"python",
"transport",
"economics"
] |
On a Mac w/ Python2.6 and trying to install psycopg2 | 1,374,187 | <p>I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:</p>
<p><a href="http://py-psycopg.darwinports.com/" rel="nofollow">http://py-psycopg.darwinports.com/</a></p>
<p>I get something like...</p>
<pre><code>sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
</code></pre>
<p>I am running MacOS X 10.4.</p>
<p>How do i make this work? </p>
<p>Any reply would be greatly appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>After running the code below I get the errors below:</p>
<pre><code>$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
</code></pre>
<p>FYI, the python i installed was the dmg file from the pythong site.</p>
<p>Thanks,
Wenbert</p>
| 1 | 2009-09-03T15:34:31Z | 1,374,304 | <p>If you're using Python 2.6, you actually want to build <code>py26-psycopg2</code>:</p>
<pre><code>$ sudo port install py26-psycopg2
</code></pre>
<p>In MacPorts, <code>py-*</code> packages build using Python 2.4, <code>py25-*</code> using Python 2.5, and <code>py26-*</code> use Python 2.6.</p>
| 10 | 2009-09-03T15:54:39Z | [
"python",
"osx"
] |
On a Mac w/ Python2.6 and trying to install psycopg2 | 1,374,187 | <p>I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:</p>
<p><a href="http://py-psycopg.darwinports.com/" rel="nofollow">http://py-psycopg.darwinports.com/</a></p>
<p>I get something like...</p>
<pre><code>sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
</code></pre>
<p>I am running MacOS X 10.4.</p>
<p>How do i make this work? </p>
<p>Any reply would be greatly appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>After running the code below I get the errors below:</p>
<pre><code>$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
</code></pre>
<p>FYI, the python i installed was the dmg file from the pythong site.</p>
<p>Thanks,
Wenbert</p>
| 1 | 2009-09-03T15:34:31Z | 1,374,308 | <p>Maybe you need to look at the <a href="http://py26-psycopg2.darwinports.com/" rel="nofollow">version for Python 2.6</a>? </p>
| 3 | 2009-09-03T15:54:49Z | [
"python",
"osx"
] |
On a Mac w/ Python2.6 and trying to install psycopg2 | 1,374,187 | <p>I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:</p>
<p><a href="http://py-psycopg.darwinports.com/" rel="nofollow">http://py-psycopg.darwinports.com/</a></p>
<p>I get something like...</p>
<pre><code>sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
</code></pre>
<p>I am running MacOS X 10.4.</p>
<p>How do i make this work? </p>
<p>Any reply would be greatly appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>After running the code below I get the errors below:</p>
<pre><code>$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
</code></pre>
<p>FYI, the python i installed was the dmg file from the pythong site.</p>
<p>Thanks,
Wenbert</p>
| 1 | 2009-09-03T15:34:31Z | 1,374,645 | <p>I installed psycopg2 on my Mac with setuptools and easy_install. First get the Python 2.6 egg from the <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools downloads page</a>, then install it with the instructions on that page. Then you can run the following to install it:</p>
<pre><code>sudo easy_install psycopg2
</code></pre>
<p>You may have different luck, but that's what did it for me.</p>
| 0 | 2009-09-03T16:51:13Z | [
"python",
"osx"
] |
On a Mac w/ Python2.6 and trying to install psycopg2 | 1,374,187 | <p>I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:</p>
<p><a href="http://py-psycopg.darwinports.com/" rel="nofollow">http://py-psycopg.darwinports.com/</a></p>
<p>I get something like...</p>
<pre><code>sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
</code></pre>
<p>I am running MacOS X 10.4.</p>
<p>How do i make this work? </p>
<p>Any reply would be greatly appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>After running the code below I get the errors below:</p>
<pre><code>$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
</code></pre>
<p>FYI, the python i installed was the dmg file from the pythong site.</p>
<p>Thanks,
Wenbert</p>
| 1 | 2009-09-03T15:34:31Z | 1,382,924 | <p>I had problems installing <code>psycopg2</code> on my 10.4 Mac too. I installed both Python and Postgres from dmg files, and <code>sudo easy_install psycopg2</code> was giving an error I can't remember now. What worked for me was an easy solution:</p>
<pre><code>PATH=$PATH:/Library/PostgreSQL/8.3/bin/ sudo easy_install psycopg2
</code></pre>
<p>which I've found at <a href="http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/" rel="nofollow">http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/</a></p>
| 1 | 2009-09-05T09:58:58Z | [
"python",
"osx"
] |
On a Mac w/ Python2.6 and trying to install psycopg2 | 1,374,187 | <p>I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:</p>
<p><a href="http://py-psycopg.darwinports.com/" rel="nofollow">http://py-psycopg.darwinports.com/</a></p>
<p>I get something like...</p>
<pre><code>sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
</code></pre>
<p>I am running MacOS X 10.4.</p>
<p>How do i make this work? </p>
<p>Any reply would be greatly appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>After running the code below I get the errors below:</p>
<pre><code>$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
</code></pre>
<p>FYI, the python i installed was the dmg file from the pythong site.</p>
<p>Thanks,
Wenbert</p>
| 1 | 2009-09-03T15:34:31Z | 1,622,533 | <p>I did this:</p>
<p><a href="http://tonylandis.com/python/installing-psycopg2-on-osx-105/" rel="nofollow">http://tonylandis.com/python/installing-psycopg2-on-osx-105/</a></p>
| 0 | 2009-10-25T23:54:27Z | [
"python",
"osx"
] |
On a Mac w/ Python2.6 and trying to install psycopg2 | 1,374,187 | <p>I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here:</p>
<p><a href="http://py-psycopg.darwinports.com/" rel="nofollow">http://py-psycopg.darwinports.com/</a></p>
<p>I get something like...</p>
<pre><code>sudo port install py-psycopg
... bunch of errors here...
Error: The following dependencies failed to build: py-mx python24
</code></pre>
<p>I am running MacOS X 10.4.</p>
<p>How do i make this work? </p>
<p>Any reply would be greatly appreciated.</p>
<p><strong>UPDATE:</strong></p>
<p>After running the code below I get the errors below:</p>
<pre><code>$ sudo port install py26-psycopg2
Warning: Skipping upgrade since openssl 0.9.8k_0 >= openssl 0.9.8k_0, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
Warning: Skipping upgrade since readline 6.0.000_1 >= readline 6.0.000_1, even though installed variants "" do not match "+darwin". Use 'upgrade --enforce-variants' to switch to the requested variants.
---> Computing dependencies for py26-psycopg2
---> Building python26
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_lang_python26/work/Python-2.6.2" && /usr/bin/make all MAKE="/usr/bin/make CC=/usr/bin/gcc-4.0" " returned error 2
Command output: /usr/bin/install -c -d -m 755 Python.framework/Versions/2.6
if test ""; then \
/usr/bin/gcc-4.0 -o Python.framework/Versions/2.6/Python -dynamiclib \
-isysroot "" \
-all_load libpython2.6.a -Wl,-single_module \
-install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python \
-compatibility_version 2.6 \
-current_version 2.6; \
else \
/usr/bin/libtool -o Python.framework/Versions/2.6/Python -dynamic libpython2.6.a \
-lSystem -lSystemStubs -install_name /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python -compatibility_version 2.6 -current_version 2.6 ;\
fi
ld64 failed: in libpython2.6.a(__.SYMDEF), not a valid ppc64 mach-o file
/usr/bin/libtool: internal link edit command failed
make: *** [Python.framework/Versions/2.6/Python] Error 1
Error: The following dependencies failed to build: python26
Error: Status 1 encountered during processing.
</code></pre>
<p>FYI, the python i installed was the dmg file from the pythong site.</p>
<p>Thanks,
Wenbert</p>
| 1 | 2009-09-03T15:34:31Z | 2,806,807 | <p>I tried everything and nothing works. At least this post:
<a href="http://benkreeger.com/post/312303245/conquering-symbol-not-found-pqbackendpid" rel="nofollow">http://benkreeger.com/post/312303245/conquering-symbol-not-found-pqbackendpid</a></p>
<p>led me to homebrew which made it perfectly.</p>
| 0 | 2010-05-10T22:10:36Z | [
"python",
"osx"
] |
How to add a namespace to an attribute in lxml | 1,374,443 | <p>I'm trying to create an xml entry that looks like this using python and lxml:</p>
<pre><code><resource href="Unit 4.html" adlcp:scormtype="sco">
</code></pre>
<p>I'm using python and lxml. I'm having trouble with the <code>adlcp:scormtype</code> attribute. I'm new to xml so please correct me if I'm wrong. <code>adlcp</code> is a namespace and <code>scormtype</code> is an attribute that is defined in the adlcp namespace, right?<br />
I'm not even sure if this is the right question but... My question is, how do I add an attribute to an element from a non-default namespace using lxml? I apologize in advance if this is a trivial question.</p>
| 7 | 2009-09-03T16:17:51Z | 1,374,757 | <p>This is not a full reply but just a few pointers.</p>
<p>adlcp is not the namespace it is a namespace prefix. The namespace is defined in the document by an attribute like <code>xmlns:adlcp="http://xxx/yy/zzz"</code></p>
<p>In lxml you always set an element/attribute name including the namespace e.g.
<code>{http://xxx/yy/zzz}scormtype</code> instead of just scormtype. lxml will then put in a namespace prefix automatically.
However lxml will set the prefix to ns0 or similar unless you do more fiddling but that should be sufficient as the prefix does not mean anything. (However some people prefer controlling the prefix name; see the nsmap argument on the Element and SubElement functions, and the register_namespace function).</p>
<p>I would look at the <a href="http://lxml.de/tutorial.html#namespaces" rel="nofollow">lxml tutorial on namespace</a> and also <a href="http://www.diveintopython.net/xml_processing/index.html" rel="nofollow">Dive into Python - XML chapter</a></p>
| 14 | 2009-09-03T17:13:08Z | [
"python",
"xml",
"lxml",
"scorm"
] |
How to add a namespace to an attribute in lxml | 1,374,443 | <p>I'm trying to create an xml entry that looks like this using python and lxml:</p>
<pre><code><resource href="Unit 4.html" adlcp:scormtype="sco">
</code></pre>
<p>I'm using python and lxml. I'm having trouble with the <code>adlcp:scormtype</code> attribute. I'm new to xml so please correct me if I'm wrong. <code>adlcp</code> is a namespace and <code>scormtype</code> is an attribute that is defined in the adlcp namespace, right?<br />
I'm not even sure if this is the right question but... My question is, how do I add an attribute to an element from a non-default namespace using lxml? I apologize in advance if this is a trivial question.</p>
| 7 | 2009-09-03T16:17:51Z | 27,957,145 | <p>Try this:</p>
<pre><code>builder = ElementMaker(namespace="http://a.different.url/blah/v.10",
nsmap={
'adlcp': "http://a.namespace.url/blah/v.10",
'anotherns': "http://a.different.url/blah/v.10"
})
builder.resource()
builder.attrib['href'] = "Unit 4.html"
builder.attrib['{http://a.namespace.url/blah/v.10}scormtype'] = 'sco'
print(etree.tostring(builder, pretty_print=True))
</code></pre>
| 2 | 2015-01-15T05:07:50Z | [
"python",
"xml",
"lxml",
"scorm"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 1,374,469 | <p>Have you tried this?</p>
<pre><code> len( pattern.findall(source) )
</code></pre>
| 5 | 2009-09-03T16:22:10Z | [
"python",
"regex"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 1,374,471 | <pre><code>import re
len(re.findall(pattern, string_to_search))
</code></pre>
| 22 | 2009-09-03T16:22:47Z | [
"python",
"regex"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 1,374,488 | <pre><code>import re
print len(re.findall(r'ab',u'ababababa'))
</code></pre>
| 1 | 2009-09-03T16:26:10Z | [
"python",
"regex"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 1,374,516 | <p>I know this is a question about regex. I just thought I'd mention the <a href="http://docs.python.org/library/stdtypes.html#str.count">count</a> method for future reference if someone wants a non-regex solution.</p>
<pre><code>>>> s = "It actually happened when it acted out of turn."
>>> s.count('t a')
2
</code></pre>
<p>Which return the number of non-overlapping occurrences of the substring</p>
| 7 | 2009-09-03T16:29:57Z | [
"python",
"regex"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 1,374,893 | <p>The existing solutions based on <code>findall</code> are fine for non-overlapping matches (and no doubt optimal except maybe for HUGE number of matches), although alternatives such as <code>sum(1 for m in re.finditer(thepattern, thestring))</code> (to avoid ever materializing the list when all you care about is the count) are also quite possible. Somewhat idiosyncratic would be using <code>subn</code> and ignoring the resulting string...:</p>
<pre><code>def countnonoverlappingrematches(pattern, thestring):
return re.subn(pattern, '', thestring)[1]
</code></pre>
<p>the only real advantage of this latter idea would come if you only cared to count (say) up to 100 matches; then, <code>re.subn(pattern, '', thestring, 100)[1]</code> might be practical (returning 100 whether there are 100 matches, or 1000, or even larger numbers).</p>
<p>Counting <strong>overlapping</strong> matches requires you to write more code, because the built-in functions in question are all focused on NON-overlapping matches. There's also a problem of definition, e.g, with pattern being <code>'a+'</code> and thestring being <code>'aa'</code>, would you consider this to be just one match, or three (the first <code>a</code>, the second one, both of them), or...?</p>
<p>Assuming for example that you want possibly-overlapping matches <em>starting at distinct spots in the string</em> (which then would give TWO matches for the example in the previous paragraph):</p>
<pre><code>def countoverlappingdistinct(pattern, thestring):
total = 0
start = 0
there = re.compile(pattern)
while True:
mo = there.search(thestring, start)
if mo is None: return total
total += 1
start = 1 + mo.start()
</code></pre>
<p>Note that you do have to compile the pattern into a RE object in this case: function <code>re.search</code> does not accept a <code>start</code> argument (starting position for the search) the way <em>method</em> <code>search</code> does, so you'd have to be slicing thestring as you go -- definitely more effort than just having the next search start at the next possible distinct starting point, which is what I'm doing in this function.</p>
| 8 | 2009-09-03T17:43:59Z | [
"python",
"regex"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 1,375,160 | <p>You can find overlapping matches by using a noncapturing subpattern:</p>
<pre><code>def count_overlapping(pattern, string):
return len(re.findall("(?=%s)" % pattern, string))
</code></pre>
| 3 | 2009-09-03T18:32:48Z | [
"python",
"regex"
] |
Find out how many times a regex matches in a string in Python | 1,374,457 | <p>Is there a way that I can find out how many matches of a regex are in a string in Python? For example, if I have the string <code>"It actually happened when it acted out of turn."</code></p>
<p>I want to know how many times <code>"t a"</code> appears in the string. In that string, <code>"t a"</code> appears twice. I want my function to tell me it appeared twice. Is this possible?</p>
| 15 | 2009-09-03T16:20:44Z | 5,634,958 | <p>To avoid creating a list of matches one may also use <a href="http://docs.python.org/library/re#re.sub" rel="nofollow">re.sub</a> with a callable as replacement. It will be called on each match, incrementing internal counter.</p>
<pre><code>class Counter(object):
def __init__(self):
self.matched = 0
def __call__(self, matchobj):
self.matched += 1
counter = Counter()
re.sub(some_pattern, counter, text)
print counter.matched
</code></pre>
| 0 | 2011-04-12T12:10:33Z | [
"python",
"regex"
] |
save python output to log | 1,375,283 | <p>I have a python script the runs this code:</p>
<pre><code>strpath = "sudo svnadmin create /svn/repos/" + short_name
os.popen (strpath, 'w')
</code></pre>
<p>How can I get the output of that command stored in a variable or written to a log file in the current directory?</p>
<p>I know, there may not be an output, but if there is, I need to know.</p>
| 0 | 2009-09-03T18:56:56Z | 1,375,290 | <p>you can do it in your bash-part:</p>
<pre><code>strpath = "sudo svnadmin create /svn/repos/" + short_name + ' > log.txt'
</code></pre>
| 0 | 2009-09-03T18:58:59Z | [
"python",
"logging",
"variables"
] |
save python output to log | 1,375,283 | <p>I have a python script the runs this code:</p>
<pre><code>strpath = "sudo svnadmin create /svn/repos/" + short_name
os.popen (strpath, 'w')
</code></pre>
<p>How can I get the output of that command stored in a variable or written to a log file in the current directory?</p>
<p>I know, there may not be an output, but if there is, I need to know.</p>
| 0 | 2009-09-03T18:56:56Z | 1,375,292 | <p>If you don't need to write to the command, then just change the 'w' to 'r':</p>
<pre><code>strpath = "sudo svnadmin create /svn/repos/" + short_name
output = os.popen (strpath, 'r')
for line in output.readlines():
# do stuff
</code></pre>
<p>Alternatively if you don't want to process line-by-line:</p>
<pre><code>strpath = "sudo svnadmin create /svn/repos/" + short_name
output = os.popen (strpath, 'r')
outtext = output.read()
</code></pre>
<p>However, I'd echo Greg's suggestion of looking at the subprocess module instead.</p>
| 1 | 2009-09-03T18:59:10Z | [
"python",
"logging",
"variables"
] |
save python output to log | 1,375,283 | <p>I have a python script the runs this code:</p>
<pre><code>strpath = "sudo svnadmin create /svn/repos/" + short_name
os.popen (strpath, 'w')
</code></pre>
<p>How can I get the output of that command stored in a variable or written to a log file in the current directory?</p>
<p>I know, there may not be an output, but if there is, I need to know.</p>
| 0 | 2009-09-03T18:56:56Z | 1,375,295 | <p>Use the <code>'r'</code> mode to open the pipe instead:</p>
<pre><code>f = os.popen (strpath, 'r')
for line in f:
print line
f.close()
</code></pre>
<p>See the documentation for <a href="http://docs.python.org/library/os.html#os.popen" rel="nofollow"><code>os.popen()</code></a> for more information.</p>
<p>The <a href="http://docs.python.org/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> module is a better way to execute external commands like this, because it allows much more control over the process execution, as well as providing access to both input and output streams simultaneously.</p>
| 3 | 2009-09-03T19:00:56Z | [
"python",
"logging",
"variables"
] |
Wrapping Mutually Dependent Structs in Pyrex | 1,375,293 | <p>I am attempting to wrap some C code in Python using Pyrex. I've run into an issue with defining two structs. In this case, the structures have been defined in terms of one another, and Pyrex cannot seem to handle the conflict. The structures look something like so:</p>
<pre><code>typedef struct a {
b * b_pointer;
} a;
typedef struct b {
a a_obj;
} b;
</code></pre>
<p>They are placed in different files. The code I am using to wrap the structures looks like this:</p>
<pre><code>def extern from "file.c":
ctypdef struct a:
b * b_pointer
ctypedef struct b:
a a_obj
</code></pre>
<p><code>File.c</code> is a separate file containing function definitions, as opposed to the structure definitions, but it includes the source files that define these structures. Is there some way I can wrap both of these structures?</p>
| 2 | 2009-09-03T19:00:20Z | 1,376,307 | <p>You can use an <a href="http://ldots.org/pyrex-guide/4-functions.html#incomplete%5Ftypes" rel="nofollow">incomplete type</a> (you do need the corresponding C typedefs in to be in a <code>.h</code> file, not just a <code>.c</code> file):</p>
<pre><code>cdef extern from "some.h":
ctypedef struct b
ctypedef struct a:
b * b_pointer
ctypedef struct b:
a a_obj
</code></pre>
| 3 | 2009-09-03T22:28:19Z | [
"python",
"c",
"struct",
"wrapper"
] |
Error importing a python module in Django | 1,375,382 | <p>In my Django project, the following line throws an ImportError: "No module named elementtree".</p>
<pre><code> from elementtree import ElementTree
</code></pre>
<p>However, the module is installed (ie, I can run an interactive python shell, and type that exact line without any ImportError), and the directory containing the module is on the PYTHONPATH. But when I access any page in a browser, it somehow can't find the module, and throws the ImportError. What could be causing this?</p>
| 2 | 2009-09-03T19:17:47Z | 1,375,418 | <p>Go into your installation directory</p>
<p>Example: </p>
<blockquote>
<p>C:\Python26\Lib\site-packages</p>
</blockquote>
<p>And check if both elementtree and django are in there. </p>
<p>If they are both not there, then you probably have multiple installation directories for different versions of Python. </p>
<p><hr /></p>
<p>In any case, you can solve your problem by running this command:</p>
<blockquote>
<p>python setup.py install</p>
</blockquote>
<p>Run it twice, once inside the download for django and once inside the download for elementtree. It will install both of the downloads into whatever your current default python is. </p>
<p>References: </p>
<ul>
<li><a href="http://effbot.org/zone/element-index.htm" rel="nofollow">Installation documentation for ElementTree</a></li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/install/#installing-official-release" rel="nofollow">Installation documentation for Django</a></li>
</ul>
| 0 | 2009-09-03T19:25:18Z | [
"python",
"django",
"elementtree",
"python-module"
] |
Error importing a python module in Django | 1,375,382 | <p>In my Django project, the following line throws an ImportError: "No module named elementtree".</p>
<pre><code> from elementtree import ElementTree
</code></pre>
<p>However, the module is installed (ie, I can run an interactive python shell, and type that exact line without any ImportError), and the directory containing the module is on the PYTHONPATH. But when I access any page in a browser, it somehow can't find the module, and throws the ImportError. What could be causing this?</p>
| 2 | 2009-09-03T19:17:47Z | 1,375,562 | <p>I've also run into cross-platform issues where ElementTree was available from different modules on different systems... this ended up working for me:</p>
<pre><code>try:
import elementtree.ElementTree as ET
except:
import xml.etree.ElementTree as ET
</code></pre>
<p>May or may not help for you...</p>
| 1 | 2009-09-03T19:49:40Z | [
"python",
"django",
"elementtree",
"python-module"
] |
Error importing a python module in Django | 1,375,382 | <p>In my Django project, the following line throws an ImportError: "No module named elementtree".</p>
<pre><code> from elementtree import ElementTree
</code></pre>
<p>However, the module is installed (ie, I can run an interactive python shell, and type that exact line without any ImportError), and the directory containing the module is on the PYTHONPATH. But when I access any page in a browser, it somehow can't find the module, and throws the ImportError. What could be causing this?</p>
| 2 | 2009-09-03T19:17:47Z | 1,375,595 | <p>Can you import <code>elementtree</code> within the django shell:</p>
<pre><code>python manage.py shell
</code></pre>
<p>Assuming you have multiple python versions and do not know which one is being used to run your site, add the following to your view and push <code>python_ver</code> to your template, it will show you the Python version you are using:</p>
<pre><code>import sys
python_ver = sys.version
</code></pre>
<p>You can also explicitly add the path to elementtree programatically in your <code>settings.py</code>:</p>
<pre><code>import sys
sys.path.append('path to where elementtree resides')
</code></pre>
| 4 | 2009-09-03T19:53:33Z | [
"python",
"django",
"elementtree",
"python-module"
] |
Problem with polling sockets in python | 1,375,772 | <p>After I begin the polling loop, all messages printed after the first iteration require me to press enter in the terminal for it to be displayed.</p>
<pre><code>#!/usr/bin/python
import socket, select, os, pty, sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 5007))
s.listen(5)
mypoll = select.poll()
mypoll.register(s.fileno() )
while True:
print "poll time"
subr = mypoll.poll()
for x in subr[0]:
if x == s.fileno():
conn, addr = s.accept()
pid, fd = pty.fork()
if pid != 0:
mypoll.register(fd)
print "done. go back to poll now"
else:
print "forked"
#handles new connection
else:
data = os.read(x,1024)
print data
</code></pre>
| 0 | 2009-09-03T20:31:38Z | 1,375,888 | <p>After the first iteration, haven't you registered the pty fd, and are then polling it? And its fd will never be equal to the socket fd, so you will then os.read the pty fd. And isn't that now reading from your terminal? And so won't typing a return cause it to "print data"?</p>
| 1 | 2009-09-03T20:52:30Z | [
"python",
"sockets",
"fork",
"polling"
] |
How do create a python module for MySQL Workbench? | 1,375,881 | <p>I am trying to create a simple Python module for MySQL Workbench 5.1.17 SE however I cannot seem to register the module, that is, it is not displaying under the Plugins->Catalog menu. </p>
<p>The documentation appears to be rather weak at this time, the best I have found is <a href="http://mysqlworkbench.org/?p=197" rel="nofollow">Python Scripting in Workbench</a>. There isn't much in the way of instructions here. </p>
<p>How do I create and install a python module with MySQL Workbench?</p>
| 0 | 2009-09-03T20:50:57Z | 1,376,968 | <p>I chatted with one of the developers of MySQL Workbench via IRC and it turns out there were two problems:</p>
<ol>
<li>I had to make sure my python script ended with *_grt.py so that it was recognized as a module.</li>
<li><p>There is a bug at least in version 5.1.17+ that prevents more than one python script module from being loaded. This has been fixed in a branch but has not yet made it into the stable release. The current workaround is to remove / delete any *.py modules you have in the following folders:</p>
<ul>
<li><em>\modules</em></li>
<li><em>C:\Documents and Settings\\Application Data\MySQL\Workbench\modules</em></li>
</ul></li>
</ol>
| 1 | 2009-09-04T02:37:36Z | [
"python",
"plugins",
"mysql-workbench"
] |
How to get the signed integer value of a long in python? | 1,375,897 | <p>If lv stores a long value, and the machine is 32 bits, the following code: </p>
<pre><code>iv = int(lv & 0xffffffff)
</code></pre>
<p>results an iv of type long, instead of the machine's int. </p>
<p>How can I get the (signed) int value in this case?</p>
| 12 | 2009-09-03T20:54:38Z | 1,375,939 | <p>You're working in a high-level scripting language; by nature, the native data types of the system you're running on aren't visible. You can't cast to a native signed int with code like this.</p>
<p>If you know that you want the value converted to a 32-bit signed integer--regardless of the platform--you can just do the conversion with the simple math:</p>
<pre><code>iv = 0xDEADBEEF
if(iv & 0x80000000):
iv = -0x100000000 + iv
</code></pre>
| 12 | 2009-09-03T21:03:04Z | [
"python",
"unsigned",
"signed"
] |
How to get the signed integer value of a long in python? | 1,375,897 | <p>If lv stores a long value, and the machine is 32 bits, the following code: </p>
<pre><code>iv = int(lv & 0xffffffff)
</code></pre>
<p>results an iv of type long, instead of the machine's int. </p>
<p>How can I get the (signed) int value in this case?</p>
| 12 | 2009-09-03T20:54:38Z | 1,390,179 | <p>You may use <strong>struct</strong> library to convert values like that. It's ugly, but works:</p>
<pre><code>from struct import pack, unpack
signed = unpack('l', pack('L', lv & 0xffffffff))[0]
</code></pre>
| 6 | 2009-09-07T16:53:49Z | [
"python",
"unsigned",
"signed"
] |
How to get the signed integer value of a long in python? | 1,375,897 | <p>If lv stores a long value, and the machine is 32 bits, the following code: </p>
<pre><code>iv = int(lv & 0xffffffff)
</code></pre>
<p>results an iv of type long, instead of the machine's int. </p>
<p>How can I get the (signed) int value in this case?</p>
| 12 | 2009-09-03T20:54:38Z | 9,351,268 | <pre><code>import ctypes
number = lv & 0xFFFFFFFF
signed_number = ctypes.c_long(number).value
</code></pre>
| 13 | 2012-02-19T17:13:34Z | [
"python",
"unsigned",
"signed"
] |
How to get the signed integer value of a long in python? | 1,375,897 | <p>If lv stores a long value, and the machine is 32 bits, the following code: </p>
<pre><code>iv = int(lv & 0xffffffff)
</code></pre>
<p>results an iv of type long, instead of the machine's int. </p>
<p>How can I get the (signed) int value in this case?</p>
| 12 | 2009-09-03T20:54:38Z | 11,612,456 | <p>Can I suggest this:</p>
<pre><code>def getSignedNumber(number, bitLength):
mask = (2 ** bitLength) - 1
if number & (1 << (bitLength - 1)):
return number | ~mask
else:
return number & mask
print iv, '->', getSignedNumber(iv, 32)
</code></pre>
| 4 | 2012-07-23T12:22:44Z | [
"python",
"unsigned",
"signed"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.