title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to get 280slides.com functionality? | 1,385,722 | <p>I have seen 280slides.com and it is really impresive. But its developers had to create their own language.</p>
<p>Which platform or language would you use to have an as similar as possible functionality?
Is it possible to do something similar in python?
Could you give any working examples?</p>
| 3 | 2009-09-06T13:51:26Z | 1,385,753 | <p>From memory, that language (Objective-J) compiles into javascript, so it's just the old HTML + CSS + Javascript + <code><</code><em>insert server-side language here</em><code>></code>. Python could easily be the server-side language. If you want examples of python web frameworks, look at <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> and <a href="http://plone.org/" rel="nofollow">Plone</a>.</p>
| 0 | 2009-09-06T14:01:30Z | [
"python",
"rich-internet-application"
] |
How to get 280slides.com functionality? | 1,385,722 | <p>I have seen 280slides.com and it is really impresive. But its developers had to create their own language.</p>
<p>Which platform or language would you use to have an as similar as possible functionality?
Is it possible to do something similar in python?
Could you give any working examples?</p>
| 3 | 2009-09-06T13:51:26Z | 1,385,927 | <p>Inventing our own language was a miniscule part of the problem. What was important was developing the right framework, which is now available as Cappuccino (cappuccino.org). </p>
<p>You ask what platform/language you could use to develop something similar? I assume you already know that the answer to what platform is the web. 280 Slides is web based, and that is an integral part of the experience. </p>
<p>And when it comes to the web, you realistically have one development choice: JavaScript. Fortunately, once you accept that, there are a lot of things you can do, including targeting JavaScript with other languages (like Java with GWT). </p>
<p>Objective-J is a pretty thin layer on top of JavaScript, so if it's the only thing keeping you from trying Cappuccino, I strongly recommend giving it a shot. As far as the server is concerned, there's nothing remarkable going on. Almost all the magic is happening in the browser.</p>
| 8 | 2009-09-06T15:29:29Z | [
"python",
"rich-internet-application"
] |
SQLCODE -1829 on connect using informixdb | 1,385,731 | <p>While trying to connect to the database I get a strange error:</p>
<pre><code>DatabaseError: SQLCODE -1829 in CONNECT:
ìæà : Cannot open file 'os.iem'
ìæà : Cannot open file 'os.iem'
</code></pre>
<p>I can confirm that the file is present in $INFORMIXDIR/msg/en_us/0333/ directory. The environment variables INFORMIXDIR, INFORMIXSERVER and ONCONFIG are set correctly and as expected by my instance. Any clues on what I might be doing wrong?</p>
<p>Am connecting using informixdb (version 2.5) and am connecting to Informix version 11.5. The user who is connecting has the requisite permissions.</p>
| 1 | 2009-09-06T13:54:07Z | 1,386,274 | <p>ok figured this one out! It appears only the env values set before the import of the informixdb module affect the way the module works. So the following does not work:</p>
<pre><code>import informixdb
os.environ["INFORMIXDIR"] = "/opt/informix"
...
def conn(db):
informixdb.connect(db, self.username, self.passwd)
...
conn('local')
</code></pre>
<p>whereas the following does:</p>
<pre><code>os.environ["INFORMIXDIR"] = "/opt/informix"
import informixdb
...
def conn(db):
informixdb.connect(db, self.username, self.passwd)
...
conn('local')
</code></pre>
| 1 | 2009-09-06T18:03:57Z | [
"python",
"informix"
] |
Should __init__() call the parent class's __init__()? | 1,385,759 | <p>I'm used that in Objective-C I've got this construct:</p>
<pre><code>- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
</code></pre>
<p>Should Python also call the parent class's implementation for <code>__init__</code>?</p>
<pre><code>class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
</code></pre>
<p>Is this also true/false for <code>__new__()</code> and <code>__del__()</code>?</p>
<p><strong>Edit:</strong> There's a very similar question: <a href="http://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python">Inheritance and Overriding <code>__init__</code> in Python</a></p>
| 61 | 2009-09-06T14:04:23Z | 1,385,767 | <p><strong>Edit</strong>: (after the code change)<br />
There is no way for us to tell you whether you need or not to call your parent's <code>__init__</code> (or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your <code>__init__</code> is done in parent class, you can just skip child-class <code>__init__</code> altogether.</p>
<p>consider the following example:</p>
<pre><code>>>> class A:
def __init__(self, val):
self.a = val
>>> class B(A):
pass
>>> class C(A):
def __init__(self, val):
A.__init__(self, val)
self.a += val
>>> A(4).a
4
>>> B(5).a
5
>>> C(6).a
12
</code></pre>
| 14 | 2009-09-06T14:11:23Z | [
"python"
] |
Should __init__() call the parent class's __init__()? | 1,385,759 | <p>I'm used that in Objective-C I've got this construct:</p>
<pre><code>- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
</code></pre>
<p>Should Python also call the parent class's implementation for <code>__init__</code>?</p>
<pre><code>class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
</code></pre>
<p>Is this also true/false for <code>__new__()</code> and <code>__del__()</code>?</p>
<p><strong>Edit:</strong> There's a very similar question: <a href="http://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python">Inheritance and Overriding <code>__init__</code> in Python</a></p>
| 61 | 2009-09-06T14:04:23Z | 1,385,768 | <p>There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.</p>
<p><strong>Update:</strong> The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the <code>render()</code> method of a widget.</p>
<p><strong>Further update:</strong> What's the OPP? Do you mean OOP? No - a subclass often needs to know <em>something</em> about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why <code>protected</code> is a valid concept in OOP in general (though not, of course, in Python).</p>
| 4 | 2009-09-06T14:13:22Z | [
"python"
] |
Should __init__() call the parent class's __init__()? | 1,385,759 | <p>I'm used that in Objective-C I've got this construct:</p>
<pre><code>- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
</code></pre>
<p>Should Python also call the parent class's implementation for <code>__init__</code>?</p>
<pre><code>class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
</code></pre>
<p>Is this also true/false for <code>__new__()</code> and <code>__del__()</code>?</p>
<p><strong>Edit:</strong> There's a very similar question: <a href="http://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python">Inheritance and Overriding <code>__init__</code> in Python</a></p>
| 61 | 2009-09-06T14:04:23Z | 1,385,778 | <p>In Python, calling the super-class' <code>__init__</code> is optional. If you call it, it is then also optional whether to use the <code>super</code> identifier, or whether to explicitly name the super class:</p>
<pre><code>object.__init__(self)
</code></pre>
<p>In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for <code>__del__</code>.</p>
<p>OTOH, for <code>__new__</code>, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.</p>
| 32 | 2009-09-06T14:18:07Z | [
"python"
] |
Should __init__() call the parent class's __init__()? | 1,385,759 | <p>I'm used that in Objective-C I've got this construct:</p>
<pre><code>- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
</code></pre>
<p>Should Python also call the parent class's implementation for <code>__init__</code>?</p>
<pre><code>class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
</code></pre>
<p>Is this also true/false for <code>__new__()</code> and <code>__del__()</code>?</p>
<p><strong>Edit:</strong> There's a very similar question: <a href="http://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python">Inheritance and Overriding <code>__init__</code> in Python</a></p>
| 61 | 2009-09-06T14:04:23Z | 1,385,826 | <p>IMO, you should call it. If your superclass is <code>object</code>, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override <code>__init__</code> itself, for example when it has no (additional) internal state to initialize.</p>
| 3 | 2009-09-06T14:47:43Z | [
"python"
] |
Should __init__() call the parent class's __init__()? | 1,385,759 | <p>I'm used that in Objective-C I've got this construct:</p>
<pre><code>- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
</code></pre>
<p>Should Python also call the parent class's implementation for <code>__init__</code>?</p>
<pre><code>class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
</code></pre>
<p>Is this also true/false for <code>__new__()</code> and <code>__del__()</code>?</p>
<p><strong>Edit:</strong> There's a very similar question: <a href="http://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python">Inheritance and Overriding <code>__init__</code> in Python</a></p>
| 61 | 2009-09-06T14:04:23Z | 1,385,836 | <p>If you need something from super's <code>__init__</code> to be done in addition to what is being done in the current class's <code>__init__,</code> you must call it yourself, since that will not happen automatically. But if you don't need anything from super's <code>__init__,</code> no need to call it. Example:</p>
<pre><code>>>> class C(object):
def __init__(self):
self.b = 1
>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1
>>> class E(C):
def __init__(self):
self.a = 1
>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'
</code></pre>
<p><code>__del__</code> is the same way, (but be wary of relying on <code>__del__</code> for finalization - consider doing it via the with statement instead).</p>
<p>I rarely use <code>__new__.</code> I do all the initialization in <code>__init__.</code></p>
| 71 | 2009-09-06T14:51:06Z | [
"python"
] |
Should __init__() call the parent class's __init__()? | 1,385,759 | <p>I'm used that in Objective-C I've got this construct:</p>
<pre><code>- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
</code></pre>
<p>Should Python also call the parent class's implementation for <code>__init__</code>?</p>
<pre><code>class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
</code></pre>
<p>Is this also true/false for <code>__new__()</code> and <code>__del__()</code>?</p>
<p><strong>Edit:</strong> There's a very similar question: <a href="http://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python">Inheritance and Overriding <code>__init__</code> in Python</a></p>
| 61 | 2009-09-06T14:04:23Z | 7,059,529 | <p>In Anon's answer:<br>
<em>"If you need something from super's <code>__init__</code> to be done in addition to what is being done in the current class's <code>__init__</code> , you must call it yourself, since that will not happen automatically"</em> </p>
<p>It's incredible: he is wording exactly the contrary of the principle of inheritance.</p>
<p>. </p>
<p>It is not that <em>"something from super's <code>__init__</code> (...) will not happen automatically"</em> , it is that it WOULD happen automatically, but it doesn't happen because the base-class' <code>__init__</code> is overriden by the definition of the derived-clas <code>__init__</code> </p>
<p>So then, WHY defining a derived_class' <code>__init__</code> , since it overrides what is aimed at when someone resorts to inheritance ?? </p>
<p>It's because one needs to define something that is NOT done in the base-class' <code>__init__</code> , and the only possibility to obtain that is to put its execution in a derived-class' <code>__init__</code> function.<br>
In other words, <strong>one needs something in base-class' <code>__init__</code> in addition</strong> to what would be automatically done in the base-classe' <code>__init__</code> if this latter wasn't overriden.<br>
NOT the contrary. </p>
<p>.</p>
<p>Then, the problem is that the desired instructions present in the base-class' <code>__init__</code> are no more activated at the moment of instanciation. In order to offset this inactivation, something special is required: calling explicitly the base-class' <code>__init__</code> , in order to <strong>KEEP</strong> , NOT TO ADD, the initialization performed by the base-class' <code>__init__</code> .
That's exactly what is said in the official doc:</p>
<blockquote>
<p>An overriding method in a derived class may in fact want to <strong>extend
rather than simply replace the base class method</strong> of the same name.
There is a simple way to call the base class method directly: just
call BaseClassName.methodname(self, arguments).<br>
<a href="http://docs.python.org/tutorial/classes.html#inheritance">http://docs.python.org/tutorial/classes.html#inheritance</a></p>
</blockquote>
<p>That's all the story:</p>
<ul>
<li><p>when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an <code>__init__</code> function in the derived class</p></li>
<li><p>when the aim is to REPLACE the initialization performed by the base-class, <code>__init__</code> must be defined in the derived-class</p></li>
<li><p>when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' <code>__init__</code> must be defined , comprising an explicit call to the base-class <code>__init__</code> </p></li>
</ul>
<p>.</p>
<p>What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.</p>
| 28 | 2011-08-14T20:31:39Z | [
"python"
] |
Group Input in Forms | 1,385,766 | <p>I've this django form</p>
<pre><code>class CustomerForm(forms.Form):
first_name = forms.CharField(label=_('Nome'), max_length=30)
last_name = forms.CharField(label=_('Cognome'), max_length=30)
business_name = forms.CharField(label=_('Ragione Sociale'),
max_length=100)
vat_number = forms.CharField(label=_('Partita iva'),
max_length=11, required=False)
</code></pre>
<p>and I want to group the inputs (first_name and last_name, business_name and vat_number) so that when I display the form I get <strong>first_name and last_name</strong> in a div and <strong>business_name and vat_number</strong> in a another div</p>
<p>is this possible?</p>
<p>Thanks :)</p>
| 2 | 2009-09-06T14:10:23Z | 1,385,773 | <p>There's nothing to stop you doing this in your template. Remember, as the documentation says, the <code>{{ form.as_p }}</code> etc are just shortcuts. As soon as you need to do something different, you can just fall back to iterating through the fields in your template, or even listing them individually.</p>
| 0 | 2009-09-06T14:15:45Z | [
"python",
"django",
"django-forms",
"input"
] |
Group Input in Forms | 1,385,766 | <p>I've this django form</p>
<pre><code>class CustomerForm(forms.Form):
first_name = forms.CharField(label=_('Nome'), max_length=30)
last_name = forms.CharField(label=_('Cognome'), max_length=30)
business_name = forms.CharField(label=_('Ragione Sociale'),
max_length=100)
vat_number = forms.CharField(label=_('Partita iva'),
max_length=11, required=False)
</code></pre>
<p>and I want to group the inputs (first_name and last_name, business_name and vat_number) so that when I display the form I get <strong>first_name and last_name</strong> in a div and <strong>business_name and vat_number</strong> in a another div</p>
<p>is this possible?</p>
<p>Thanks :)</p>
| 2 | 2009-09-06T14:10:23Z | 3,394,174 | <p>have a look at the <a href="http://djangosnippets.org/snippets/1783/" rel="nofollow">Stacked/Grouped Forms</a> snippet, where you can define "Stacks" (Groups) of fields in your Form.</p>
| 1 | 2010-08-03T06:47:20Z | [
"python",
"django",
"django-forms",
"input"
] |
How do you check if a widget has focus in Tkinter? | 1,385,921 | <pre><code>from Tkinter import *
app = Tk()
text_field = Entry(app)
text_field.pack()
app.mainloop()
</code></pre>
<p>I want to be able to check if <code>text_field</code> is currently selected or focused, so that I know whether or not to do something with its contents when the user presses enter.</p>
| 7 | 2009-09-06T15:25:17Z | 1,385,933 | <p>If you want to do something when the user presses enter only if the focus is on the entry widget, simply add a binding to the entry widget. It will only fire if that widget has focus. For example:</p>
<pre><code>>>> from Tkinter import *
>>> root=Tk()
>>> e1=Entry(root)
>>> e1.pack()
>>> e2=Entry(root)
>>> e2.pack()
>>> def handleReturn(event):
... print "return: event.widget is",event.widget
... print "focus is:", root.focus_get()
...
>>> e1.bind("<Return>", handleReturn)
</code></pre>
<p>Notice that the handler is only called if the first entry has focus when you press return.</p>
<p>If you really want a global binding and need to know which widget has focus, use the focus_get() method on the root object. In the following example a binding is put on "." (the main toplevel) so that it fires no matter what has focus:</p>
<pre><code>>>> from Tkinter import *
>>> root=Tk()
>>> e1=Entry(root)
>>> e1.pack()
>>> e2=Entry(root)
>>> e2.pack()
>>> def handleReturn(event):
... print "return: event.widget is",event.widget
... print "focus is:",root.focus_get()
...
>>> root.bind("<Return>",handleReturn)
</code></pre>
<p>Notice the difference between the two: in the first example the handler will only be called when you press return in the first entry widget. There is no need to check which widget has focus. In the second example the handler will be called no matter which widget has focus.</p>
<p>Both solutions are good depending on what you really need to have happen. If your main goal is to only do something when the user presses return in a specific widget, use the former. If you want a global binding, but in that binding do something different based on what has or doesn't have focus, do the latter example.</p>
| 11 | 2009-09-06T15:32:23Z | [
"python",
"focus",
"tkinter",
"entry"
] |
maximum number combinations | 1,385,929 | <p>I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9.</p>
<p>I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999. </p>
<p>Any clues as to why the following code is dropping certain combinations?</p>
<pre>
def permgen(items, n):
if n==0: yield []
else:
for i in range(len(items)):
for cc in permgen(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
if __name__=="__main__":
for c in permgen(['0','1','2','3','4','5','6','7','8','9'],4): print ''.join(c)
</pre>
| 3 | 2009-09-06T15:30:45Z | 1,385,935 | <p>If you have python 2.6, why not use <a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a>?</p>
<pre><code>from itertools import combinations
combinations(range(10), 4)
</code></pre>
| 12 | 2009-09-06T15:34:42Z | [
"python",
"combinations"
] |
maximum number combinations | 1,385,929 | <p>I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9.</p>
<p>I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999. </p>
<p>Any clues as to why the following code is dropping certain combinations?</p>
<pre>
def permgen(items, n):
if n==0: yield []
else:
for i in range(len(items)):
for cc in permgen(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
if __name__=="__main__":
for c in permgen(['0','1','2','3','4','5','6','7','8','9'],4): print ''.join(c)
</pre>
| 3 | 2009-09-06T15:30:45Z | 1,385,943 | <pre><code>int ra;
for(ra=0,ra<10000;ra++) printf("%04u\n",ra);
</code></pre>
| 0 | 2009-09-06T15:37:13Z | [
"python",
"combinations"
] |
maximum number combinations | 1,385,929 | <p>I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9.</p>
<p>I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999. </p>
<p>Any clues as to why the following code is dropping certain combinations?</p>
<pre>
def permgen(items, n):
if n==0: yield []
else:
for i in range(len(items)):
for cc in permgen(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
if __name__=="__main__":
for c in permgen(['0','1','2','3','4','5','6','7','8','9'],4): print ''.join(c)
</pre>
| 3 | 2009-09-06T15:30:45Z | 1,385,955 | <p>This line:</p>
<pre><code>for cc in permgen(items[:i]+items[i+1:],n-1):
</code></pre>
<p>You're basically saying "get a number, than add another one <em>different</em> from ir, repeat n times, then return a list of these digits. That's going to give you numbers where no digit appears more than once. If you change that line to:</p>
<pre><code>for cc in permgen(items,n-1):
</code></pre>
<p>then you get all combinations.</p>
| 4 | 2009-09-06T15:40:47Z | [
"python",
"combinations"
] |
maximum number combinations | 1,385,929 | <p>I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9.</p>
<p>I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999. </p>
<p>Any clues as to why the following code is dropping certain combinations?</p>
<pre>
def permgen(items, n):
if n==0: yield []
else:
for i in range(len(items)):
for cc in permgen(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
if __name__=="__main__":
for c in permgen(['0','1','2','3','4','5','6','7','8','9'],4): print ''.join(c)
</pre>
| 3 | 2009-09-06T15:30:45Z | 1,386,207 | <p>Take a look at <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools' combinatoric generators</a>:</p>
<pre><code>>>> from itertools import combinations, permutations, product
>>> def pp(chunks):
... print(' '.join(map(''.join, chunks)))
...
>>> pp(combinations('012', 2))
01 02 12
>>> pp(permutations('012', 2))
01 02 10 12 20 21
>>> pp(product('012', repeat=2))
00 01 02 10 11 12 20 21 22
>>> from itertools import combinations_with_replacement
>>> pp(combinations_with_replacement('012', 2))
00 01 02 11 12 22
</code></pre>
<p><a href="http://docs.python.org/dev/library/itertools.html#itertools.combinations%5Fwith%5Freplacement" rel="nofollow"><code>combinations_with_replacement</code></a> is available in Python 3.1 (or 2.7).</p>
<p>It seems that <a href="http://docs.python.org/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a> is the most suitable for your task.</p>
| 4 | 2009-09-06T17:34:13Z | [
"python",
"combinations"
] |
Add Preprocessor to HTML (Probably in Apache) | 1,385,965 | <p>I would like to add a preprocessor to HTML pages. Basically, I have a program that takes the name of an HTML file containing preprocessor instructions and outputs the contents of the file after preprocessing to stdout. This mechanism could change if it makes things easier. All I want to do is hook this into Apache so that all the files that my website serves get put through the preprocessor before going out to the browser. A solution that works with other HTTP servers than Apache would be preferred, but is not required.</p>
<p>If my understanding is correct, this is roughly what PHP does.</p>
<p>If it makes any difference, the preprocessor is written in Python.</p>
| 0 | 2009-09-06T15:46:38Z | 1,385,987 | <p>If you have Apache and a "preprocessor" written in python, why not go for <a href="http://www.modpython.org/" rel="nofollow">mod_python</a>?</p>
| 4 | 2009-09-06T15:55:13Z | [
"php",
"python",
"html",
"apache",
"preprocessor"
] |
Shall I bother with storing DateTime data as julianday in SQLite? | 1,386,093 | <p>SQLite docs specifies that the preferred format for storing datetime values in the DB is to use Julian Day (using built-in functions).</p>
<p>However, all frameworks I saw in python (pysqlite, SQLAlchemy) store the <code>datetime.datetime</code> values as ISO formatted strings. Why are they doing so?</p>
<p>I'm usually trying to adapt the frameworks to storing datetime as julianday, and it's quite painful. I started to doubt that is worth the efforts.</p>
<p>Please share your experience in this field with me. Does sticking with julianday make sense?</p>
| 8 | 2009-09-06T16:43:23Z | 1,386,154 | <p>Julian Day is handy for all sorts of date calculations, but it can's store the <em>time</em> part decently (with precise hours, minutes, and seconds). In the past I've used both Julian Day fields (for dates), and seconds-from-the-Epoch (for <code>datetime</code> instances), but only when I had specific needs for computation (of dates and respectively of times). The simplicity of ISO formatted dates and datetimes, I think, should make them the preferred choice, say about 97% of the time.</p>
| 6 | 2009-09-06T17:10:49Z | [
"python",
"datetime",
"sqlite",
"sqlalchemy",
"pysqlite"
] |
Shall I bother with storing DateTime data as julianday in SQLite? | 1,386,093 | <p>SQLite docs specifies that the preferred format for storing datetime values in the DB is to use Julian Day (using built-in functions).</p>
<p>However, all frameworks I saw in python (pysqlite, SQLAlchemy) store the <code>datetime.datetime</code> values as ISO formatted strings. Why are they doing so?</p>
<p>I'm usually trying to adapt the frameworks to storing datetime as julianday, and it's quite painful. I started to doubt that is worth the efforts.</p>
<p>Please share your experience in this field with me. Does sticking with julianday make sense?</p>
| 8 | 2009-09-06T16:43:23Z | 1,399,537 | <p>Store it both ways. Frameworks can be set in their ways and if yours is expecting to find a raw column with an ISO formatted string then that is probably more of a pain to get around than it's worth.</p>
<p>The concern in having two columns is data consistency but sqlite should have everything you need to make it work. Version 3.3 has support for check constraints and triggers. Read up on <a href="http://www.sqlite.org/lang%5Fdatefunc.html">date and time functions</a>. You should be able to do what you need entirely in the database.</p>
<pre><code>CREATE TABLE Table1 (jd, isotime);
CREATE TRIGGER trigger_name_1 AFTER INSERT ON Table1
BEGIN
UPDATE Table1 SET jd = julianday(isotime) WHERE rowid = last_insert_rowid();
END;
CREATE TRIGGER trigger_name_2 AFTER UPDATE OF isotime ON Table1
BEGIN
UPDATE Table1 SET jd = julianday(isotime) WHERE rowid = old.rowid;
END;
</code></pre>
<p>And if you cant do what you need within the DB you can write a C extension to perform the functionality you need. That way you wont need to touch the framework other than to load your extension.</p>
| 5 | 2009-09-09T12:57:15Z | [
"python",
"datetime",
"sqlite",
"sqlalchemy",
"pysqlite"
] |
Shall I bother with storing DateTime data as julianday in SQLite? | 1,386,093 | <p>SQLite docs specifies that the preferred format for storing datetime values in the DB is to use Julian Day (using built-in functions).</p>
<p>However, all frameworks I saw in python (pysqlite, SQLAlchemy) store the <code>datetime.datetime</code> values as ISO formatted strings. Why are they doing so?</p>
<p>I'm usually trying to adapt the frameworks to storing datetime as julianday, and it's quite painful. I started to doubt that is worth the efforts.</p>
<p>Please share your experience in this field with me. Does sticking with julianday make sense?</p>
| 8 | 2009-09-06T16:43:23Z | 3,089,486 | <p>Because <code>2010-06-22 00:45:56</code> is far easier for a human to read than <code>2455369.5318981484</code>. Text dates are great for doing ad-hoc queries in SQLiteSpy or SQLite Manager.</p>
<p>The main drawback, of course, is that text dates require 19 bytes instead of 8.</p>
| 0 | 2010-06-22T00:50:37Z | [
"python",
"datetime",
"sqlite",
"sqlalchemy",
"pysqlite"
] |
Shall I bother with storing DateTime data as julianday in SQLite? | 1,386,093 | <p>SQLite docs specifies that the preferred format for storing datetime values in the DB is to use Julian Day (using built-in functions).</p>
<p>However, all frameworks I saw in python (pysqlite, SQLAlchemy) store the <code>datetime.datetime</code> values as ISO formatted strings. Why are they doing so?</p>
<p>I'm usually trying to adapt the frameworks to storing datetime as julianday, and it's quite painful. I started to doubt that is worth the efforts.</p>
<p>Please share your experience in this field with me. Does sticking with julianday make sense?</p>
| 8 | 2009-09-06T16:43:23Z | 4,634,359 | <p>But typically, the Human doesn't read directly from the database. Fractional time on a Julian Day is easily converted to human readible by (for example)</p>
<pre><code>void hour_time(GenericDate *ConvertObject)
{
double frac_time = ConvertObject->jd;
double hour = (24.0*(frac_time - (int)frac_time));
double minute = 60.0*(hour - (int)hour);
double second = 60.0*(minute - (int)minute);
double microsecond = 1000000.0*(second - (int)second);
ConvertObject->hour = hour;
ConvertObject->minute = minute;
ConvertObject->second = second;
ConvertObject->microsecond = microsecond;
};
</code></pre>
| 1 | 2011-01-08T14:36:32Z | [
"python",
"datetime",
"sqlite",
"sqlalchemy",
"pysqlite"
] |
'Query' object has no attribute 'kind' when using appcfg.py download_data | 1,386,191 | <p>I'm having problems with bulk downloads -- all of my data is not being pulled down.</p>
<p>I'm still debugging, but I see in my console:</p>
<pre><code>Traceback (most recent call last):
File "/Users/matthew/local/opt/google_appengine/google/appengine/tools/adaptive_thread_pool.py", line 150, in WorkOnItems
status, instruction = item.PerformWork(self.__thread_pool)
File "/Users/matthew/local/opt/google_appengine/google/appengine/tools/bulkloader.py", line 675, in PerformWork
transfer_time = self._TransferItem(thread_pool)
File "/Users/matthew/local/opt/google_appengine/google/appengine/tools/bulkloader.py", line 1054, in _TransferItem
download_result = self.request_manager.GetEntities(self)
File "/Users/matthew/local/opt/google_appengine/google/appengine/tools/bulkloader.py", line 1274, in GetEntities
query = key_range_item.key_range.make_directed_datastore_query(self.kind)
File "/Users/matthew/local/opt/google_appengine/google/appengine/ext/key_range/__init__.py", line 246, in make_directed_datastore_query
query = self.filter_datastore_query(query)
File "/Users/matthew/local/opt/google_appengine/google/appengine/ext/key_range/__init__.py", line 175, in filter_datastore_query
return EmptyDatastoreQuery(query.kind)
AttributeError: 'Query' object has no attribute 'kind'
[INFO ] An error occurred. Shutting down...
.....[ERROR ] Error in Thread-7: 'Query' object has no attribute 'kind'
[INFO ] Have 83 entities, 0 previously transferred
[INFO ] 83 entities (0 bytes) transferred in 2.5 seconds
</code></pre>
<p>Any ideas? For this test, I'm only exporting data for a single Model, but each record does have 2 references to another Model.</p>
| 0 | 2009-09-06T17:28:04Z | 1,386,519 | <p>It looks like you've encountered a bug in the bulk downloader, unfortunately. Can you please file a bug report <a href="http://code.google.com/p/googleappengine/issues/entry" rel="nofollow">here</a>? It'd help if you can supply the model definition and bulk loader exporter subclass definition.</p>
| 1 | 2009-09-06T19:40:40Z | [
"python",
"google-app-engine"
] |
Should properties do nontrivial initialization? | 1,386,210 | <p>I have an object that is basically a Python implementation of an Oracle sequence. For a variety of reasons, we have to get the nextval of an Oracle sequence, count up manually when determining primary keys, then update the sequence once the records have been inserted.</p>
<p>So here's the steps my object does:</p>
<ol>
<li>Construct an object, with a <code>key_generator</code> attribute initially set to None.</li>
<li>Get the first value from the database, passing it to an itertools.count.</li>
<li>Return keys from that generator using a property <code>next_key</code>.</li>
</ol>
<p>I'm a little bit unsure about where to do step 2. I can think of three possibilities:</p>
<ol>
<li>Skip step 1 and do step 2 in the constructor. I find this evil because I tend to dislike doing this kind of initialization in a constructor.</li>
<li>Make <code>next_key</code> get the starting key from the database the first time it is called. I find this evil because properties are typically assumed to be trivial.</li>
<li>Make <code>next_key</code> into a <code>get_next_key</code> method. I dislike this because properties just seem more natural here.</li>
</ol>
<p>Which is the lesser of 3 evils? I'm leaning towards #2, because only the first call to this property will result in a database query.</p>
| 2 | 2009-09-06T17:35:26Z | 1,386,258 | <p>I agree that attribute access and everything that looks like it (i.e. properties in the Python context) should be fairly trivial. If a property is going to perform a potentially costly operation, use a method to make this explicit. I recommend a name like "fetch_XYZ" or "retrieve_XYZ", since "get_XYZ" is used in some languages (e.g. Java) as a convention for simple attribute access, is quite generic, and does not sound "costly" either.</p>
<p>A good guideline is: If your property could throw an exception that is not due to a programming error, it should be a method. For example, throwing a (hypothetical) DatabaseConnectionError from a property is bad, while throwing an ObjectStateError would be okay.</p>
<p>Also, when I understood you correctly, you want to return the next key, whenever the next_key property is accessed. I recommend strongly against having side-effects (apart from caching, cheap lazy initialization, etc.) in your properties. Properties (and attributes for that matter) should be idempotent.</p>
| 2 | 2009-09-06T17:57:43Z | [
"python",
"properties",
"initialization"
] |
Should properties do nontrivial initialization? | 1,386,210 | <p>I have an object that is basically a Python implementation of an Oracle sequence. For a variety of reasons, we have to get the nextval of an Oracle sequence, count up manually when determining primary keys, then update the sequence once the records have been inserted.</p>
<p>So here's the steps my object does:</p>
<ol>
<li>Construct an object, with a <code>key_generator</code> attribute initially set to None.</li>
<li>Get the first value from the database, passing it to an itertools.count.</li>
<li>Return keys from that generator using a property <code>next_key</code>.</li>
</ol>
<p>I'm a little bit unsure about where to do step 2. I can think of three possibilities:</p>
<ol>
<li>Skip step 1 and do step 2 in the constructor. I find this evil because I tend to dislike doing this kind of initialization in a constructor.</li>
<li>Make <code>next_key</code> get the starting key from the database the first time it is called. I find this evil because properties are typically assumed to be trivial.</li>
<li>Make <code>next_key</code> into a <code>get_next_key</code> method. I dislike this because properties just seem more natural here.</li>
</ol>
<p>Which is the lesser of 3 evils? I'm leaning towards #2, because only the first call to this property will result in a database query.</p>
| 2 | 2009-09-06T17:35:26Z | 1,386,269 | <p>I think your doubts come from <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP-8</a>:</p>
<blockquote>
<pre><code> Note 3: Avoid using properties for computationally expensive
operations; the attribute notation makes the caller believe
that access is (relatively) cheap.
</code></pre>
</blockquote>
<p>Adherence to a standard behavior is usually quite a good idea; and this would be a reason to scrap away solution #2.</p>
<p>However, if you <em>feel</em> the interface is better with property than a method, then I would simply document that the first call is more expensive, and go with that (solution #2).<br />
In the end, recommendations are meant to be interpreted.</p>
| 4 | 2009-09-06T18:01:29Z | [
"python",
"properties",
"initialization"
] |
Should properties do nontrivial initialization? | 1,386,210 | <p>I have an object that is basically a Python implementation of an Oracle sequence. For a variety of reasons, we have to get the nextval of an Oracle sequence, count up manually when determining primary keys, then update the sequence once the records have been inserted.</p>
<p>So here's the steps my object does:</p>
<ol>
<li>Construct an object, with a <code>key_generator</code> attribute initially set to None.</li>
<li>Get the first value from the database, passing it to an itertools.count.</li>
<li>Return keys from that generator using a property <code>next_key</code>.</li>
</ol>
<p>I'm a little bit unsure about where to do step 2. I can think of three possibilities:</p>
<ol>
<li>Skip step 1 and do step 2 in the constructor. I find this evil because I tend to dislike doing this kind of initialization in a constructor.</li>
<li>Make <code>next_key</code> get the starting key from the database the first time it is called. I find this evil because properties are typically assumed to be trivial.</li>
<li>Make <code>next_key</code> into a <code>get_next_key</code> method. I dislike this because properties just seem more natural here.</li>
</ol>
<p>Which is the lesser of 3 evils? I'm leaning towards #2, because only the first call to this property will result in a database query.</p>
| 2 | 2009-09-06T17:35:26Z | 1,389,673 | <p>I've decided that the key smell in the solution I'm proposing is that the property I was creating contained the word "next" in it. Thus, instead of making a <code>next_key</code> property, I've decided to turn my DatabaseIntrospector class into a KeyCounter class and implemented the iterator protocol (ie making a plain old next method that returns the next key).</p>
| 0 | 2009-09-07T14:29:54Z | [
"python",
"properties",
"initialization"
] |
PIL: Thumbnail and end up with a square image | 1,386,352 | <p>Calling</p>
<pre><code>image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)
</code></pre>
<p>will maintain the aspect ratio. But I need to end up displaying the image like this:</p>
<pre><code><img src="/media/image.png" style="height:36px; width:36px" />
</code></pre>
<p>Can I have a letterbox style with either transparent or white around the image?</p>
| 41 | 2009-09-06T18:33:59Z | 1,386,382 | <p>Paste the image into a transparent image with the right size as a background</p>
<pre><code>from PIL import Image
size = (36, 36)
image = Image.open(data)
image.thumbnail(size, Image.ANTIALIAS)
background = Image.new('RGBA', size, (255, 255, 255, 0))
background.paste(
image,
((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
</code></pre>
<p>EDIT: fixed syntax error</p>
| 56 | 2009-09-06T18:45:01Z | [
"python",
"png",
"thumbnails",
"python-imaging-library",
"alpha"
] |
PIL: Thumbnail and end up with a square image | 1,386,352 | <p>Calling</p>
<pre><code>image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)
</code></pre>
<p>will maintain the aspect ratio. But I need to end up displaying the image like this:</p>
<pre><code><img src="/media/image.png" style="height:36px; width:36px" />
</code></pre>
<p>Can I have a letterbox style with either transparent or white around the image?</p>
| 41 | 2009-09-06T18:33:59Z | 8,469,920 | <p>PIL already already has a function to do exactly that</p>
<pre><code>from PIL import Image, ImageOps
thumb = ImageOps.fit(image, size, Image.ANTIALIAS)
</code></pre>
| 96 | 2011-12-12T04:25:06Z | [
"python",
"png",
"thumbnails",
"python-imaging-library",
"alpha"
] |
PIL: Thumbnail and end up with a square image | 1,386,352 | <p>Calling</p>
<pre><code>image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)
</code></pre>
<p>will maintain the aspect ratio. But I need to end up displaying the image like this:</p>
<pre><code><img src="/media/image.png" style="height:36px; width:36px" />
</code></pre>
<p>Can I have a letterbox style with either transparent or white around the image?</p>
| 41 | 2009-09-06T18:33:59Z | 28,247,523 | <p>Or this, maybe... (forgive spaghetti)</p>
<pre><code>from PIL import Image
def process_image(image, size):
if image.size[0] > size[0] or image.size[1] > size[1]:
#preserve original
thumb = img.copy()
thumb.thumbnail(size,Image.ANTIALIAS)
img = thumb.copy()
img_padded = Image.new("RGBA",size)
img_padded.paste(img,((size[0]-img.size[0])/2,(size[1]-img.size[1])/2))
#do something with image here
</code></pre>
| 0 | 2015-01-31T02:26:01Z | [
"python",
"png",
"thumbnails",
"python-imaging-library",
"alpha"
] |
PIL: Thumbnail and end up with a square image | 1,386,352 | <p>Calling</p>
<pre><code>image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)
</code></pre>
<p>will maintain the aspect ratio. But I need to end up displaying the image like this:</p>
<pre><code><img src="/media/image.png" style="height:36px; width:36px" />
</code></pre>
<p>Can I have a letterbox style with either transparent or white around the image?</p>
| 41 | 2009-09-06T18:33:59Z | 38,631,007 | <pre><code>from PIL import Image
import StringIO
def thumbnail_image():
image = Image.open("image.png")
image.thumbnail((300, 200))
thumb_buffer = StringIO.StringIO()
image.save(thumb_buffer, format=image.format)
fp = open("thumbnail.png", "w")
fp.write(thumb_buffer.getvalue())
fp.close()
</code></pre>
| 2 | 2016-07-28T08:30:28Z | [
"python",
"png",
"thumbnails",
"python-imaging-library",
"alpha"
] |
PIL: Image resizing : Algorithm similar to firefox's | 1,386,400 | <p>I'm getting about the same <em>bad looking</em> resizing from all the 4 algorithms of PIL</p>
<pre><code>>>> data = utils.fetch("http://wavestock.com/images/beta-icon.gif")
>>> image = Image.open(StringIO.StringIO(data)); image.save("/home/ptarjan/www/tmp/metaward/original.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.ANTIALIAS); image.save("/home/ptarjan/www/tmp/metaward/antialias-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BILINEAR); image.save("/home/ptarjan/www/tmp/metaward/bilinear-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BICUBIC); image.save("/home/ptarjan/www/tmp/metaward/bicubic-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.NEAREST); image.save("/home/ptarjan/www/tmp/metaward/nearest-thumb.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest-rgb.png")
</code></pre>
<p>But the results look much worse that just resizing in firefox.</p>
<p><a href="http://paulisageek.com/tmp/metaward/images.html" rel="nofollow">http://paulisageek.com/tmp/metaward/images.html</a></p>
<p>How can I get a similar effect to the firefox result using PIL (or another python image library)?</p>
<p><strong>EDIT</strong> : Hover your mouse to see what each image is</p>
<p><img src="http://paulisageek.com/tmp/metaward/original.png" height="36" title="original">
<img src="http://paulisageek.com/tmp/metaward/antialias.png" title="antialias">
<img src="http://paulisageek.com/tmp/metaward/bicubic.png" title="bicubic">
<img src="http://paulisageek.com/tmp/metaward/bilinear.png" title="bilinear">
<img src="http://paulisageek.com/tmp/metaward/nearest.png" title="nearest">
<img src="http://paulisageek.com/tmp/metaward/antialias-thumb.png" title="antialias-thumb">
<img src="http://paulisageek.com/tmp/metaward/bicubic-thumb.png" title="bicubic-thumb">
<img src="http://paulisageek.com/tmp/metaward/bilinear-thumb.png" title="bilinear-thumb">
<img src="http://paulisageek.com/tmp/metaward/nearest-thumb.png" title="nearest-thumb">
<img src="http://paulisageek.com/tmp/metaward/antialias-rgb.png" title="antialias-rgb">
<img src="http://paulisageek.com/tmp/metaward/bicubic-rgb.png" title="bicubic-rgb">
<img src="http://paulisageek.com/tmp/metaward/bilinear-rgb.png" title="bilinear-rgb">
<img src="http://paulisageek.com/tmp/metaward/nearest-rgb.png" title="nearest-rgb"></p>
<p>It looks like the RGB and then ANTIALIS looks the best. Any other recommendations?</p>
<p>For reference, this is the one that looked the best :</p>
<pre><code>>>> image = Image.open(StringIO.StringIO(data));
>>> image.convert("RGB").resize((36,36), Image.ANTIALIAS)
</code></pre>
| 8 | 2009-09-06T18:58:37Z | 1,386,414 | <p>Try using the <code>resize()</code> method instead of <code>thumbnail()</code>. In my experience, they behave very differently.</p>
<p>Also, your code shows reading a .gif, but your original is .png. Make sure you really have all the original data before you start reducing it.</p>
| 0 | 2009-09-06T19:01:48Z | [
"python",
"image",
"thumbnails",
"python-imaging-library"
] |
PIL: Image resizing : Algorithm similar to firefox's | 1,386,400 | <p>I'm getting about the same <em>bad looking</em> resizing from all the 4 algorithms of PIL</p>
<pre><code>>>> data = utils.fetch("http://wavestock.com/images/beta-icon.gif")
>>> image = Image.open(StringIO.StringIO(data)); image.save("/home/ptarjan/www/tmp/metaward/original.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.ANTIALIAS); image.save("/home/ptarjan/www/tmp/metaward/antialias-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BILINEAR); image.save("/home/ptarjan/www/tmp/metaward/bilinear-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BICUBIC); image.save("/home/ptarjan/www/tmp/metaward/bicubic-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.NEAREST); image.save("/home/ptarjan/www/tmp/metaward/nearest-thumb.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest-rgb.png")
</code></pre>
<p>But the results look much worse that just resizing in firefox.</p>
<p><a href="http://paulisageek.com/tmp/metaward/images.html" rel="nofollow">http://paulisageek.com/tmp/metaward/images.html</a></p>
<p>How can I get a similar effect to the firefox result using PIL (or another python image library)?</p>
<p><strong>EDIT</strong> : Hover your mouse to see what each image is</p>
<p><img src="http://paulisageek.com/tmp/metaward/original.png" height="36" title="original">
<img src="http://paulisageek.com/tmp/metaward/antialias.png" title="antialias">
<img src="http://paulisageek.com/tmp/metaward/bicubic.png" title="bicubic">
<img src="http://paulisageek.com/tmp/metaward/bilinear.png" title="bilinear">
<img src="http://paulisageek.com/tmp/metaward/nearest.png" title="nearest">
<img src="http://paulisageek.com/tmp/metaward/antialias-thumb.png" title="antialias-thumb">
<img src="http://paulisageek.com/tmp/metaward/bicubic-thumb.png" title="bicubic-thumb">
<img src="http://paulisageek.com/tmp/metaward/bilinear-thumb.png" title="bilinear-thumb">
<img src="http://paulisageek.com/tmp/metaward/nearest-thumb.png" title="nearest-thumb">
<img src="http://paulisageek.com/tmp/metaward/antialias-rgb.png" title="antialias-rgb">
<img src="http://paulisageek.com/tmp/metaward/bicubic-rgb.png" title="bicubic-rgb">
<img src="http://paulisageek.com/tmp/metaward/bilinear-rgb.png" title="bilinear-rgb">
<img src="http://paulisageek.com/tmp/metaward/nearest-rgb.png" title="nearest-rgb"></p>
<p>It looks like the RGB and then ANTIALIS looks the best. Any other recommendations?</p>
<p>For reference, this is the one that looked the best :</p>
<pre><code>>>> image = Image.open(StringIO.StringIO(data));
>>> image.convert("RGB").resize((36,36), Image.ANTIALIAS)
</code></pre>
| 8 | 2009-09-06T18:58:37Z | 1,386,756 | <p>I resized the "original" with Python and found the same results as you did. I also resized the "original" with GIMP and I got the same (if not inferior) quality. This made me suspect that Firefox cheats. Possibly it converts to RGB ("original" mode is indexed color). Thus the following code:</p>
<pre><code>import Image
im=Image.open("beta-icon.gif")
im = im.convert("RGB")
im=im.resize((36,36), Image.ANTIALIAS)
im.save("q5.png")
</code></pre>
<p>The result is almost as good as that of Firefox.</p>
| 8 | 2009-09-06T21:21:59Z | [
"python",
"image",
"thumbnails",
"python-imaging-library"
] |
PIL: Image resizing : Algorithm similar to firefox's | 1,386,400 | <p>I'm getting about the same <em>bad looking</em> resizing from all the 4 algorithms of PIL</p>
<pre><code>>>> data = utils.fetch("http://wavestock.com/images/beta-icon.gif")
>>> image = Image.open(StringIO.StringIO(data)); image.save("/home/ptarjan/www/tmp/metaward/original.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic.png")
>>> image = Image.open(StringIO.StringIO(data)); image.resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.ANTIALIAS); image.save("/home/ptarjan/www/tmp/metaward/antialias-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BILINEAR); image.save("/home/ptarjan/www/tmp/metaward/bilinear-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.BICUBIC); image.save("/home/ptarjan/www/tmp/metaward/bicubic-thumb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.thumbnail((36,36), Image.NEAREST); image.save("/home/ptarjan/www/tmp/metaward/nearest-thumb.png")
>>>
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.ANTIALIAS).save("/home/ptarjan/www/tmp/metaward/antialias-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BILINEAR).save("/home/ptarjan/www/tmp/metaward/bilinear-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.BICUBIC).save("/home/ptarjan/www/tmp/metaward/bicubic-rgb.png")
>>> image = Image.open(StringIO.StringIO(data)); image.convert("RGB").resize((36,36), Image.NEAREST).save("/home/ptarjan/www/tmp/metaward/nearest-rgb.png")
</code></pre>
<p>But the results look much worse that just resizing in firefox.</p>
<p><a href="http://paulisageek.com/tmp/metaward/images.html" rel="nofollow">http://paulisageek.com/tmp/metaward/images.html</a></p>
<p>How can I get a similar effect to the firefox result using PIL (or another python image library)?</p>
<p><strong>EDIT</strong> : Hover your mouse to see what each image is</p>
<p><img src="http://paulisageek.com/tmp/metaward/original.png" height="36" title="original">
<img src="http://paulisageek.com/tmp/metaward/antialias.png" title="antialias">
<img src="http://paulisageek.com/tmp/metaward/bicubic.png" title="bicubic">
<img src="http://paulisageek.com/tmp/metaward/bilinear.png" title="bilinear">
<img src="http://paulisageek.com/tmp/metaward/nearest.png" title="nearest">
<img src="http://paulisageek.com/tmp/metaward/antialias-thumb.png" title="antialias-thumb">
<img src="http://paulisageek.com/tmp/metaward/bicubic-thumb.png" title="bicubic-thumb">
<img src="http://paulisageek.com/tmp/metaward/bilinear-thumb.png" title="bilinear-thumb">
<img src="http://paulisageek.com/tmp/metaward/nearest-thumb.png" title="nearest-thumb">
<img src="http://paulisageek.com/tmp/metaward/antialias-rgb.png" title="antialias-rgb">
<img src="http://paulisageek.com/tmp/metaward/bicubic-rgb.png" title="bicubic-rgb">
<img src="http://paulisageek.com/tmp/metaward/bilinear-rgb.png" title="bilinear-rgb">
<img src="http://paulisageek.com/tmp/metaward/nearest-rgb.png" title="nearest-rgb"></p>
<p>It looks like the RGB and then ANTIALIS looks the best. Any other recommendations?</p>
<p>For reference, this is the one that looked the best :</p>
<pre><code>>>> image = Image.open(StringIO.StringIO(data));
>>> image.convert("RGB").resize((36,36), Image.ANTIALIAS)
</code></pre>
| 8 | 2009-09-06T18:58:37Z | 1,391,502 | <blockquote>
<p>It looks like the RGB and then ANTIALIS looks the best. Any other recommendations?</p>
</blockquote>
<p>No, that is indeed the expected result. Any resizing done in the original limited palette mode is likely to produce jaggy rubbish because of the lack of available in-between colours in the palette; and ANTIALIAS is the <em>only</em> resize filter that is intended to be used for downscaling: BILINEAR and BICUBIC really do only take two pixels per axis and blend between them, which is fine for upscaling but doesn't work at all when one or both axes are downscaled.</p>
<p>Unfortunately thumbnail() has never really worked properly so you have to do it yourself.</p>
| 1 | 2009-09-08T01:07:27Z | [
"python",
"image",
"thumbnails",
"python-imaging-library"
] |
python Invalid literal for float | 1,386,420 | <p>I am running a code to select chunks from a big file. I am getting some strange error that is</p>
<pre><code>"Invalid literal for float(): E-135"
</code></pre>
<p>Does anybody know how to fix this? Thanks in advance.</p>
<p>Actually this is the statement that is giving me error</p>
<pre><code>float (line_temp[line(line_temp)-1])
</code></pre>
<p>This statement produces error
line_temp is a string
'line' is any line in an open and file also a string. </p>
| 2 | 2009-09-06T19:04:34Z | 1,386,431 | <p>You need a number in front of the E to make it a valid string representation of a float number</p>
<pre><code>>>> float('1E-135')
1e-135
>>> float('E-135')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): E-135
</code></pre>
<p>In fact, which number is E-135 supposed to represent? <code>1x10^-135</code>? </p>
<p>Valid literal forms for floats are <a href="http://python.org/doc/2.5.2/ref/floating.html">here</a>.</p>
| 6 | 2009-09-06T19:09:49Z | [
"python"
] |
python Invalid literal for float | 1,386,420 | <p>I am running a code to select chunks from a big file. I am getting some strange error that is</p>
<pre><code>"Invalid literal for float(): E-135"
</code></pre>
<p>Does anybody know how to fix this? Thanks in advance.</p>
<p>Actually this is the statement that is giving me error</p>
<pre><code>float (line_temp[line(line_temp)-1])
</code></pre>
<p>This statement produces error
line_temp is a string
'line' is any line in an open and file also a string. </p>
| 2 | 2009-09-06T19:04:34Z | 1,386,432 | <p>Looks like you are trying to convert a string to a float. If the string is <code>E-135</code>, then it is indeed an invalid value to be converted to a float. Perhaps you are chopping off a digit in the beginning of the string and it really ought to be something like <code>1E-135</code>? That would be a valid float.</p>
| 3 | 2009-09-06T19:10:10Z | [
"python"
] |
python Invalid literal for float | 1,386,420 | <p>I am running a code to select chunks from a big file. I am getting some strange error that is</p>
<pre><code>"Invalid literal for float(): E-135"
</code></pre>
<p>Does anybody know how to fix this? Thanks in advance.</p>
<p>Actually this is the statement that is giving me error</p>
<pre><code>float (line_temp[line(line_temp)-1])
</code></pre>
<p>This statement produces error
line_temp is a string
'line' is any line in an open and file also a string. </p>
| 2 | 2009-09-06T19:04:34Z | 1,386,508 | <p>May I suggest you replace</p>
<pre><code>float(x-y)
</code></pre>
<p>with</p>
<pre><code>float(x) - float(y)
</code></pre>
| 1 | 2009-09-06T19:37:24Z | [
"python"
] |
python Invalid literal for float | 1,386,420 | <p>I am running a code to select chunks from a big file. I am getting some strange error that is</p>
<pre><code>"Invalid literal for float(): E-135"
</code></pre>
<p>Does anybody know how to fix this? Thanks in advance.</p>
<p>Actually this is the statement that is giving me error</p>
<pre><code>float (line_temp[line(line_temp)-1])
</code></pre>
<p>This statement produces error
line_temp is a string
'line' is any line in an open and file also a string. </p>
| 2 | 2009-09-06T19:04:34Z | 1,386,830 | <p>Ronald, kindly check the answers again. They are right.
What you are doing is: float(EXPRESSION), where the result of EXPRESSION is E-135. E-135 is not valid input into the float() function. I have no idea what the "line_temp[line(line_temp)-1]" does, but it returns incorrect data for the float() function.</p>
| 1 | 2009-09-06T21:53:05Z | [
"python"
] |
Python: manipulating sub trees | 1,386,493 | <p>I'm a nooby. I'd like to acknowledge Allen Downey, Jeffrey Elkner and Chris Meyers
and 'How to think like a computer scientist' for what I know.</p>
<p>I'm building a genetics inspired program to generate equations that match some provided problem.</p>
<p>The node class looks like this:</p>
<pre><code>class Node(object):
'''
'''
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
self.parent = None
self.branch = None
self.seq = 0
def __str__(self):
return str(self.cargo)
def copy(self):
return copy.deepcopy(self)
</code></pre>
<p>I have a <code>Tree</code> class that contains an attribute: <code>self.data</code> which is a linked series of nodes forming a tree which I can traverse to produce an equation.</p>
<p>To perform crossover, I'd like to be able to swap subtrees chosen at random from two instances of <code>Tree</code>.</p>
<p>As <code>self.data</code> is being constructed, it builds a dictionary with a sequential key holding each node as a value. One such record looks like this:</p>
<pre><code> 3: <__main__.Node object at 0x0167B6B0>}
</code></pre>
<p>I thought I'd be clever and simply choose a node each from two tree instances and exchange their respective parents <code>node.left</code> or <code>node.right</code> values. Each node records if it is a left or right in its <code>node.branch</code> attribute.</p>
<p>I don't know how to reference <code>self.data(subnode)</code> to change it.</p>
<p>And both tree instances would have to have access to each other's nodes by the address saved in the dictionary.</p>
<p>I fear I shall have to copy and replace each subtree.</p>
<p>Any comments would be appreciated.</p>
<p>Thanks,</p>
<p>Peter Stewart</p>
<p>Nanaimo, Canada</p>
| 0 | 2009-09-06T19:33:38Z | 1,386,777 | <p>If I understand correctly, you are looking for something like this...</p>
<p>(I have not tested this.)</p>
<pre><code>def swap_nodes(dict_1, key_1, dict_2, key_2):
node_1 = dict_1[key_1]
node_2 = dict_2[key_2]
# Update dicts and seq fields for the two nodes...
dict_1[key_1] = node_2
node_2.seq = key_1
dict_2[key_2] = node_1
node_1.seq = key_2
# Update the parents...
if node_1.branch == "left":
node_1.parent.left = node_2
else:
node_1.parent.right = node_2
if node_2.branch == "left":
node_2.parent.left = node_1
else:
node_2.parent.right = node_1
# Now update the branch and parent fields of the nodes...
node_1.branch, node_2.branch = node_2.branch, node_1.branch
node_1.parent, node_2.parent = node_2.parent, node_1.parent
</code></pre>
| 0 | 2009-09-06T21:31:34Z | [
"python",
"data-structures",
"tree"
] |
Python: manipulating sub trees | 1,386,493 | <p>I'm a nooby. I'd like to acknowledge Allen Downey, Jeffrey Elkner and Chris Meyers
and 'How to think like a computer scientist' for what I know.</p>
<p>I'm building a genetics inspired program to generate equations that match some provided problem.</p>
<p>The node class looks like this:</p>
<pre><code>class Node(object):
'''
'''
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
self.parent = None
self.branch = None
self.seq = 0
def __str__(self):
return str(self.cargo)
def copy(self):
return copy.deepcopy(self)
</code></pre>
<p>I have a <code>Tree</code> class that contains an attribute: <code>self.data</code> which is a linked series of nodes forming a tree which I can traverse to produce an equation.</p>
<p>To perform crossover, I'd like to be able to swap subtrees chosen at random from two instances of <code>Tree</code>.</p>
<p>As <code>self.data</code> is being constructed, it builds a dictionary with a sequential key holding each node as a value. One such record looks like this:</p>
<pre><code> 3: <__main__.Node object at 0x0167B6B0>}
</code></pre>
<p>I thought I'd be clever and simply choose a node each from two tree instances and exchange their respective parents <code>node.left</code> or <code>node.right</code> values. Each node records if it is a left or right in its <code>node.branch</code> attribute.</p>
<p>I don't know how to reference <code>self.data(subnode)</code> to change it.</p>
<p>And both tree instances would have to have access to each other's nodes by the address saved in the dictionary.</p>
<p>I fear I shall have to copy and replace each subtree.</p>
<p>Any comments would be appreciated.</p>
<p>Thanks,</p>
<p>Peter Stewart</p>
<p>Nanaimo, Canada</p>
| 0 | 2009-09-06T19:33:38Z | 1,386,787 | <p>Unfortunately you don't provide us with the <code>Tree</code> class, but let's assume it's something like:</p>
<pre><code>class Tree(object):
def __init__(self):
self.data = None
self.nextkey = 0
self.thedict = {}
</code></pre>
<p>with the various attributes being updated accurately when new nodes are inserted. Now, while you talk about "the address saved in the dictionary", it's clear that the dict's value is NOT "an address" -- rather, it's a Node object (if you define a special method <code>__repr__</code> in your node you may be able to see that in a clearer way; what you're seeing is the default representation, used for all Python objects whose type don't define or inherit <code>__repr__</code>).</p>
<p>So, swapping random subtree between two different trees only requires care in updating all of the many redundant pieces of information that you're keeping (and that must ALL be in sync). By the way, it would be simpler if such updates were methods of Tree and/or Node and so usable for any of various kinds of "edit" (insertion, removal, etc), rather than buried deep in a function that performs the updates as part of a random swap -- that's good OO practice. But, that's somewhat of a side issue.</p>
<p>You also don't tell us exactly how the <code>branch</code> attribute works, I'll assume it's a string, 'left' or 'right' as appropriate (or None if there's no parent, i.e., a root node).</p>
<p>To remove a subtree, you need to update: the parent node, setting to None its appropriate attribute; the root of the subtree, setting to None its parent and branch attributes; AND the Tree, removing that entry from the Tree's <code>thedict</code> attribute. You will also need to remember what the parent and branch were in order to be able to insert some other subtree at that spot. Therefore...:</p>
<pre><code>def removeSubtreeFromTree(tree, keyindict):
subtreenode = tree.thedict.pop(keyindict)
parent, branch = subtreenode.parent, subtreenode.branch
# a sanity chech can't hurt...;-)
assert getattr(parent, branch) is subtreenode
subtreenode.parent, subtreenode.branch = None, None
setattr(parent, branch, None)
return subtreenode, parent, branch
</code></pre>
<p>Now to ADD a new subtree to a given parent and branch in a Tree is simpler:</p>
<pre><code>def addNewSubtree(tree, subtreenode, parent, branch):
# sanity checks R us
assert getattr(parent, branch) is None
assert subtreenode.parent is None
assert subtreenode.branch is None
setattr(parent, branch, subtreenode)
subtreenode.parent = parent
subtreenode.branch = branch
tree.thedict[tree.nextkey] = subtreenode
tree.nextkey += 1
</code></pre>
<p>Note you can't just reuse the previous keys: there might be a "conflict" (assuming keys are unique only within a single given Tree... if you made them globally unique instead, then you could indeed reuse them).</p>
<p>Finally, putting these two operations and a little more together can be done. If you never need to "swap" a tree's very root, it's simpler (no special case needed to deal with a parentless subtree...) so I'm temporarily going to assume that (if you want more generality you WILL have to code the finicky special cases -- ideally after refactoring things to be methods as I previously suggested;-)...:</p>
<pre><code> def randomNonrootSubtree(tree):
# we're in trouble if the tree ONLY has a root w/no really SUB trees;-)
assert len(tree.thedict) > 1
while True:
thekey = random.choice(tree.thedict.keys())
subtree = tree.thedict[thekey]
if subtree.parent: return thekey
</code></pre>
<p>and at last...:</p>
<pre><code> def theSwapper(t1, t2):
k1 = randomNonrootSubtree(t1)
k2 = randomNonrootSubtree(t2)
st1, p1, b1 = removeSubtreeFromTree(t1, k1)
st2, p2, b2 = removeSubtreeFromTree(t2, k2)
addNewSubtree(t1, st2, p1, b1)
addNewSubtree(t2, st1, p2, b2)
</code></pre>
| 1 | 2009-09-06T21:39:34Z | [
"python",
"data-structures",
"tree"
] |
Handling big numbers in code | 1,386,604 | <p>I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?</p>
| 7 | 2009-09-06T20:13:19Z | 1,386,615 | <p>Sure it can:</p>
<pre><code>>>> s = 10 ** 100000
</code></pre>
| 3 | 2009-09-06T20:17:25Z | [
"python",
"algorithm"
] |
Handling big numbers in code | 1,386,604 | <p>I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?</p>
| 7 | 2009-09-06T20:13:19Z | 1,386,618 | <p>It seems to work fine:</p>
<pre><code>>>> x = 10**100000
>>> x
10000000000000000000000000000000000000000000000000000000000000000000000000000000
[snip]
00000000L
</code></pre>
<p>According to <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">http://docs.python.org/library/stdtypes.html</a>, "Long integers have unlimited precision", which probably means that their size is not limited.</p>
| 3 | 2009-09-06T20:19:34Z | [
"python",
"algorithm"
] |
Handling big numbers in code | 1,386,604 | <p>I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?</p>
| 7 | 2009-09-06T20:13:19Z | 1,386,629 | <p>Yes; Python 2.x has two types of integers, <strong>int</strong> of limited size and <strong>long</strong> of <strong>unlimited size</strong>. However all calculations will automatically convert to long if needed. Handling big numbers works fine, but one of the slower things will be if you try to print the 100000 digits to output, or even try to create a string from it.</p>
<p>If you need arbitrary decimal fixed-point precision as well, there is the decimal module.</p>
| 7 | 2009-09-06T20:22:55Z | [
"python",
"algorithm"
] |
Handling big numbers in code | 1,386,604 | <p>I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?</p>
| 7 | 2009-09-06T20:13:19Z | 1,386,735 | <p>As other answers indicated, Python does support integer numbers bounded only by the amount of memory available. If you want even faster support for them, try <a href="http://code.google.com/p/gmpy/">gmpy</a> (as gmpy's author and current co-maintainer I'm of course a little biased here;-):</p>
<pre><code>$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'x+1'
10000 loops, best of 3: 114 usec per loop
$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y+1'
10000 loops, best of 3: 65.4 usec per loop
</code></pre>
<p>Typically, arithmetic is not the bottleneck for working with such numbers (although <code>gmpy</code>'s direct support for some combinatorial and number-theoretical functions can help if that's what you're doing with such numbers). Turning the numbers into decimal strings is probably the common operation that will feel slowest...:</p>
<pre><code>$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'str(x)'
10 loops, best of 3: 3.11 sec per loop
$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'str(y)'
10 loops, best of 3: 27.3 msec per loop
</code></pre>
<p>As you see, even in <code>gmpy</code> stringification of huge numbers can be hundreds of times slower than a simple addition (alas, it's an intrinsically complicated operation!); but in native Python code the ratio of times can go to stringification being <strong>tens of thousands</strong> times slower than a simple addition, so you really want to watch out for that, especially if you decide not to download and install <code>gmpy</code> (for example because you can't: e.g., gmpy is not currently supported on Google App Engine).</p>
<p>Finally, an intermediate case:</p>
<pre><code>$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'x*x'
10 loops, best of 3: 90 msec per loop
$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y*y'
100 loops, best of 3: 5.63 msec per loop
$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y*x'
100 loops, best of 3: 8.4 msec per loop
</code></pre>
<p>As you see, multiplying two huge numbers in native Python code can be almost 1000 times slower than the simple addition, while with <code>gmpy</code> the slowdown is less than 100 times (and it's not too bad even if only one if the numbers is already in <code>gmpy</code>'s own format so that there's the overhead of converting the other).</p>
| 22 | 2009-09-06T21:12:35Z | [
"python",
"algorithm"
] |
Handling big numbers in code | 1,386,604 | <p>I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?</p>
| 7 | 2009-09-06T20:13:19Z | 1,398,808 | <p>As already pointed out, Python can handle numbers as big as your memory will allow. I would just like to add that as the numbers grow bigger, the cost of all operations on them increases. This is not just for printing/converting to string (although that's the slowest), adding two large numbers (larger that what your hardware can natively handle) is no longer O(1). </p>
<p>I'm just mentioning this to point out that although Python neatly hides the details of working with big numbers, you still have to keep in mind that these big numbers operations are not always like those on ordinary ints.</p>
| 3 | 2009-09-09T10:25:48Z | [
"python",
"algorithm"
] |
Convert binary string to list of integers using Python | 1,386,811 | <p>I am new to Python. Here's what I am trying to do: </p>
<ol>
<li>Slice a long binary string into 3 digit-long chunks. </li>
<li>Store each "chunk" into a list called row. </li>
<li>Convert each binary chunk into a number (0-7).</li>
<li>Store the converted list of numbers into a new list called numbers. </li>
</ol>
<p>Here is what I have so far:</p>
<pre><code>def traverse(R):
x = 0
while x < (len(R) - 3):
row = R[x] + R[x+1] + R[x+2]
???
</code></pre>
<p>Thanks for your help! It is greatly appreciated. </p>
| 5 | 2009-09-06T21:46:52Z | 1,386,828 | <p>Something like this should do it:</p>
<pre><code>s = "110101001"
numbers = [int(s[i:i+3], 2) for i in range(0, len(s), 3)]
print numbers
</code></pre>
<p>The output is:</p>
<pre><code>[6, 5, 1]
</code></pre>
<p>Breaking this down step by step, first:</p>
<pre><code>>>> range(0, len(s), 3)
[0, 3, 6]
</code></pre>
<p>The <a href="http://docs.python.org/library/functions.html#range" rel="nofollow"><code>range()</code></a> function produces a list of integers from 0, less than the max <code>len(s)</code>, by step 3.</p>
<pre><code>>>> [s[i:i+3] for i in range(0, len(s), 3)]
["110", "101", "001"]
</code></pre>
<p>This is a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow"><em>list comprehension</em></a> that evaluates <code>s[i:i+3]</code> for each <code>i</code> in the above range. The <code>s[i:i+3]</code> is a <a href="http://docs.python.org/tutorial/introduction.html#lists" rel="nofollow"><em>slice</em></a> that selects a substring. Finally:</p>
<pre><code>>>> [int(s[i:i+3], 2) for i in range(0, len(s), 3)]
[6, 5, 1]
</code></pre>
<p>The <a href="http://docs.python.org/library/functions.html#int" rel="nofollow"><code>int(..., 2)</code></a> function converts from binary (base 2, second argument) to integers.</p>
<p>Note that the above code may not properly handle error conditions like an input string that is not a multiple of 3 characters in length.</p>
| 11 | 2009-09-06T21:51:21Z | [
"python"
] |
Convert binary string to list of integers using Python | 1,386,811 | <p>I am new to Python. Here's what I am trying to do: </p>
<ol>
<li>Slice a long binary string into 3 digit-long chunks. </li>
<li>Store each "chunk" into a list called row. </li>
<li>Convert each binary chunk into a number (0-7).</li>
<li>Store the converted list of numbers into a new list called numbers. </li>
</ol>
<p>Here is what I have so far:</p>
<pre><code>def traverse(R):
x = 0
while x < (len(R) - 3):
row = R[x] + R[x+1] + R[x+2]
???
</code></pre>
<p>Thanks for your help! It is greatly appreciated. </p>
| 5 | 2009-09-06T21:46:52Z | 1,386,836 | <p>I'll assume that by "binary string" you actually mean a normal string (i.e. text) whose items are all '0' or '1'.</p>
<p>So for points 1 and 2,</p>
<pre><code>row = [thestring[i:i+3] for i in xrange(0, len(thestring), 3)]
</code></pre>
<p>of course the last item will be only 1 or 2 characters long if <code>len(thestring)</code> is not an exact multiple of 3, that's inevitable;-).</p>
<p>For points 3 and 4, I'd suggest building an auxiliary temp dictionary and storing it:</p>
<pre><code>aux = {}
for x in range(8):
s = format(x, 'b')
aux[s] = x
aux[('00'+s)[-3:]] = x
</code></pre>
<p>so that points 3 and 4 just become:</p>
<pre><code>numbers = [aux[x] for x in row]
</code></pre>
<p>this dict lookup should be much faster than converting each entry on the fly.</p>
<p><strong>Edit</strong>: it's been suggested I explain why am I making two entries into <code>aux</code> for each value of <code>x</code>. The point is that <code>s</code> may be of any length from 1 to 3 characters, and for the short lengths I do want two entries -- one with <code>s</code> as it it (because as I mentioned the last item in <code>row</code> may well be shorter than 3...), and one with it left-padded to a length of 3 with <code>0</code>s.</p>
<p>The sub-expression <code>('00'+s)[-3:]</code> computes "s left-padded with '0's to a length of 3" by taking the last 3 characters (that's the <code>[-3:]</code> slicing part) of the string obtained by placing zeros to the left of <code>s</code> (that's the <code>'00'+s</code> part). If <code>s</code> is already 3 characters long, the whole subexpression will equal <code>s</code> so the assignment to that entry of <code>aux</code> is useless but harmless, so I find it simpler to not even bother checking (prepending an <code>if len(s)<3:</code> would be fine too, matter of taste;-).</p>
<p>There are other approaches (e.g. formatting <code>x</code> again if needed) but this is hardly the crux of the code (it executes just 8 times to build up the auxiliary "lookup table", after all;-), so I didn't pay it enough attention.</p>
<p>...nor did I unit-test it, so it has a bug in one obscure corner case. Can you see it...?</p>
<p>Suppose <code>row</code> has <code>'01'</code> as the last entry: THAT key, after my code's above has built <code>aux</code>, will not be present in <code>aux</code> (both <code>1</code> and <code>001</code> WILL be, but that's scanty consolation;-). In the code above I use the original <code>s</code>, <code>'1'</code>, and the length-three padded version, <code>'001'</code>, but the intermediate length-two padded version, oops, got overlooked;-).</p>
<p>So, here's a RIGHT way to do it...:</p>
<pre><code>aux = {}
for x in range(8):
s = format(x, 'b')
aux[s] = x
while len(s) < 3:
s = '0' + s
aux[s] = x
</code></pre>
<p>...no doubt simpler and more obvious, but, even more importantly, CORRECT;-).</p>
| 7 | 2009-09-06T21:55:15Z | [
"python"
] |
Convert binary string to list of integers using Python | 1,386,811 | <p>I am new to Python. Here's what I am trying to do: </p>
<ol>
<li>Slice a long binary string into 3 digit-long chunks. </li>
<li>Store each "chunk" into a list called row. </li>
<li>Convert each binary chunk into a number (0-7).</li>
<li>Store the converted list of numbers into a new list called numbers. </li>
</ol>
<p>Here is what I have so far:</p>
<pre><code>def traverse(R):
x = 0
while x < (len(R) - 3):
row = R[x] + R[x+1] + R[x+2]
???
</code></pre>
<p>Thanks for your help! It is greatly appreciated. </p>
| 5 | 2009-09-06T21:46:52Z | 1,386,897 | <p>Great answers from Greg and Alex! List comprehensions and slicing are so pythonic!
For short input strings I wouldn't bother with the dictionary lookup trick, but if the input string were longer, I would, as well as using gen-exps rather than list-comps, i.e.:</p>
<p>row = list(thestring[i:i+3] for i in xrange(0, len(thestring), 3))</p>
<p>and</p>
<p>numbers = list(aux[x] for x in row)</p>
<p>since gen-exp perform better.</p>
| 0 | 2009-09-06T22:30:15Z | [
"python"
] |
Convert binary string to list of integers using Python | 1,386,811 | <p>I am new to Python. Here's what I am trying to do: </p>
<ol>
<li>Slice a long binary string into 3 digit-long chunks. </li>
<li>Store each "chunk" into a list called row. </li>
<li>Convert each binary chunk into a number (0-7).</li>
<li>Store the converted list of numbers into a new list called numbers. </li>
</ol>
<p>Here is what I have so far:</p>
<pre><code>def traverse(R):
x = 0
while x < (len(R) - 3):
row = R[x] + R[x+1] + R[x+2]
???
</code></pre>
<p>Thanks for your help! It is greatly appreciated. </p>
| 5 | 2009-09-06T21:46:52Z | 21,275,178 | <p>Wouldn't this be easier:</p>
<p>(I wanted an array of the upper 3 bits of a variable that contained the integer 29)</p>
<p>format your variables and arrays first</p>
<p>a = ''</p>
<p>b = []</p>
<p>I stole this from a really good example in this forum, it formats the integer 29 into 5 bits, bits zero through four and puts the string of bits into the string variable "a". [edited] Needed to change the format from 0:5b to 0:05b, in order to pad zeros when the integer is < 7.</p>
<p>a = '{0:05b}'.format(29)</p>
<p>look at your string variable</p>
<p>a</p>
<p>'11101'</p>
<p>split your string into an array</p>
<p>b[0:3] = a[0:3]</p>
<p>this is exactly what I wanted.</p>
<p>b</p>
<p>['1', '1', '1']</p>
| 0 | 2014-01-22T05:48:19Z | [
"python"
] |
Convert binary string to list of integers using Python | 1,386,811 | <p>I am new to Python. Here's what I am trying to do: </p>
<ol>
<li>Slice a long binary string into 3 digit-long chunks. </li>
<li>Store each "chunk" into a list called row. </li>
<li>Convert each binary chunk into a number (0-7).</li>
<li>Store the converted list of numbers into a new list called numbers. </li>
</ol>
<p>Here is what I have so far:</p>
<pre><code>def traverse(R):
x = 0
while x < (len(R) - 3):
row = R[x] + R[x+1] + R[x+2]
???
</code></pre>
<p>Thanks for your help! It is greatly appreciated. </p>
| 5 | 2009-09-06T21:46:52Z | 21,275,703 | <p>If you're dealing with processing raw data of any kind, I'd like to recommend the excellent <a href="https://pypi.python.org/pypi/bitstring" rel="nofollow">bitstring</a> module:</p>
<pre><code>>>> import bitstring
>>> bits = bitstring.Bits('0b110101001')
>>> [b.uint for b in bits.cut(3)]
[6, 5, 1]
</code></pre>
<p>Description from the <a href="https://code.google.com/p/python-bitstring/" rel="nofollow">home page</a>:</p>
<blockquote>
<p>A Python module that makes the creation, manipulation and analysis of
binary data as simple and natural as possible.</p>
<p>Bitstrings can be constructed from integers, floats, hex, octal,
binary, bytes or files. They can also be created and interpreted using
flexible format strings.</p>
<p>Bitstrings can be sliced, joined, reversed, inserted into,
overwritten, etc. with simple methods or using slice notation. They
can also be read from, searched and replaced, and navigated in,
similar to a file or stream.</p>
<p>Internally the bit data is efficiently stored in byte arrays, the
module has been optimized for speed, and excellent code coverage is
given by over 400 unit tests.</p>
</blockquote>
| 1 | 2014-01-22T06:24:37Z | [
"python"
] |
Django : select_related with ManyToManyField | 1,387,044 | <p>I have :</p>
<pre><code>class Award(models.Model) :
name = models.CharField(max_length=100, db_index=True)
class Alias(models.Model) :
awards = models.ManyToManyField('Award', through='Achiever')
class Achiever(models.Model):
award = models.ForeignKey(Award)
alias = models.ForeignKey(Alias)
count = models.IntegerField(default=1)
</code></pre>
<p>How can I have an <code>Alias</code> which has all its <code>achiever_set</code> and <code>awards</code> prepopulated?</p>
<pre><code>>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("achiever_set__award").get().achiever_set.all()[0].award.name
u'Perma-Peddle'
>>> len(db.connection.queries)
3
>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("awards").get().awards.all()[0].name
u'Dwarfageddon (10 player)'
>>> len(db.connection.queries)
2
</code></pre>
<p>I'm going to need a lot of access to the award that an alias has already gotten (both the intermediate table and the awards themselves). How can I batch all of these?</p>
| 13 | 2009-09-06T23:52:55Z | 1,391,125 | <p>Can you try to write more detailed about needed effect? Do you want to make simply three table join, or do you need to get correct paris from the Achiever table?</p>
<p>You can use additional methods based on ManyToMany and ForeignsKey relations.</p>
| -1 | 2009-09-07T22:10:00Z | [
"python",
"django",
"django-models",
"django-select-related"
] |
Django : select_related with ManyToManyField | 1,387,044 | <p>I have :</p>
<pre><code>class Award(models.Model) :
name = models.CharField(max_length=100, db_index=True)
class Alias(models.Model) :
awards = models.ManyToManyField('Award', through='Achiever')
class Achiever(models.Model):
award = models.ForeignKey(Award)
alias = models.ForeignKey(Alias)
count = models.IntegerField(default=1)
</code></pre>
<p>How can I have an <code>Alias</code> which has all its <code>achiever_set</code> and <code>awards</code> prepopulated?</p>
<pre><code>>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("achiever_set__award").get().achiever_set.all()[0].award.name
u'Perma-Peddle'
>>> len(db.connection.queries)
3
>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("awards").get().awards.all()[0].name
u'Dwarfageddon (10 player)'
>>> len(db.connection.queries)
2
</code></pre>
<p>I'm going to need a lot of access to the award that an alias has already gotten (both the intermediate table and the awards themselves). How can I batch all of these?</p>
| 13 | 2009-09-06T23:52:55Z | 9,431,210 | <p>Django versions 1.4 and above have <a href="https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related"><code>prefetch_related</code></a> for this purpose.</p>
<p>The <a href="https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related"><code>prefetch_related</code></a> method is similar to <a href="https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-related"><code>select_related</code></a>, but does not do a database join. Instead, it executes additional database queries and does the joining in Python.</p>
| 18 | 2012-02-24T13:00:05Z | [
"python",
"django",
"django-models",
"django-select-related"
] |
Django : select_related with ManyToManyField | 1,387,044 | <p>I have :</p>
<pre><code>class Award(models.Model) :
name = models.CharField(max_length=100, db_index=True)
class Alias(models.Model) :
awards = models.ManyToManyField('Award', through='Achiever')
class Achiever(models.Model):
award = models.ForeignKey(Award)
alias = models.ForeignKey(Alias)
count = models.IntegerField(default=1)
</code></pre>
<p>How can I have an <code>Alias</code> which has all its <code>achiever_set</code> and <code>awards</code> prepopulated?</p>
<pre><code>>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("achiever_set__award").get().achiever_set.all()[0].award.name
u'Perma-Peddle'
>>> len(db.connection.queries)
3
>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("awards").get().awards.all()[0].name
u'Dwarfageddon (10 player)'
>>> len(db.connection.queries)
2
</code></pre>
<p>I'm going to need a lot of access to the award that an alias has already gotten (both the intermediate table and the awards themselves). How can I batch all of these?</p>
| 13 | 2009-09-06T23:52:55Z | 10,133,687 | <p>If you're not on Django 1.4, there's also the <a href="https://github.com/lilspikey/django-batch-select" rel="nofollow">django-batch-select</a> library, which works basically the same way as prefetch_related.</p>
| 3 | 2012-04-13T00:23:20Z | [
"python",
"django",
"django-models",
"django-select-related"
] |
Reliably detect Windows in Python | 1,387,222 | <p>I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The <code>platform.platform</code> function comes close but only returns a string.</p>
<p>Unfortunately I don't know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I'm missing here?</p>
| 30 | 2009-09-07T01:29:16Z | 1,387,224 | <p>Try this:</p>
<pre><code>import platform
if platform.system() == "Darwin":
# Don't have Windows handy, but I'd expect "Win32" or "Windows" for it
</code></pre>
<p><strong>Edit:</strong> Just saw that you tried <code>platform.platform()</code>...<code>platform.system()</code> will work better for this case. Trust me, use it. Dark corners lie in platform detection.</p>
<p><code>distutils</code> will do this too, if you ask it nicely.</p>
<p>You could always do something bad like <code>os.path.exists()</code> on a Windows file...but <code>platform</code> is as reliable as it gets in the Python standard library.</p>
<p><strong>Edit 2:</strong> Another helpful answerer pointed out <code>platform.system()</code> is exactly equal to "Windows" on his Windows machine.</p>
| 8 | 2009-09-07T01:31:03Z | [
"python",
"windows",
"platform-detection"
] |
Reliably detect Windows in Python | 1,387,222 | <p>I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The <code>platform.platform</code> function comes close but only returns a string.</p>
<p>Unfortunately I don't know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I'm missing here?</p>
| 30 | 2009-09-07T01:29:16Z | 1,387,226 | <p>On my Windows box, <code>platform.system()</code> returns <code>'Windows'</code>.</p>
<p>However, I'm not sure why you'd bother. If you want to limit the platform it runs on technologically, I'd use a white-list rather than a black-list.</p>
<p>In fact, I wouldn't do it technologically at all since perhaps the next release of Python may have <code>Win32/Win64</code> instead of <code>Windows</code> (for black-listing) and <code>*nix</code> instead of <code>Linux</code> (for white-listing).</p>
<p>My advice is to simply state what the requirements are and, if the user chooses to ignore that, that's their problem. If they ring up saying they got an error message stating "Cannot find FHS" and they admit they're running on Windows, gently point out to them that it's not a supported configuration.</p>
<p>Maybe your customers are smart enough to get FHS running under Windows so that your code will work. They're unlikely to appreciate what they would then consider an arbitrary limitation of your software.</p>
<p>This is a problem faced by software developers every day. Even huge organizations can't support <em>every</em> single platform and configuration out there.</p>
| 17 | 2009-09-07T01:32:49Z | [
"python",
"windows",
"platform-detection"
] |
Reliably detect Windows in Python | 1,387,222 | <p>I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The <code>platform.platform</code> function comes close but only returns a string.</p>
<p>Unfortunately I don't know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I'm missing here?</p>
| 30 | 2009-09-07T01:29:16Z | 1,387,228 | <pre><code>>>> import platform
>>> platform.system()
'Windows'
</code></pre>
| 47 | 2009-09-07T01:33:31Z | [
"python",
"windows",
"platform-detection"
] |
Reliably detect Windows in Python | 1,387,222 | <p>I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The <code>platform.platform</code> function comes close but only returns a string.</p>
<p>Unfortunately I don't know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I'm missing here?</p>
| 30 | 2009-09-07T01:29:16Z | 3,469,295 | <p>From help(platform)</p>
<pre><code>system()
Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
</code></pre>
| 2 | 2010-08-12T15:24:22Z | [
"python",
"windows",
"platform-detection"
] |
Reliably detect Windows in Python | 1,387,222 | <p>I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The <code>platform.platform</code> function comes close but only returns a string.</p>
<p>Unfortunately I don't know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I'm missing here?</p>
| 30 | 2009-09-07T01:29:16Z | 4,865,804 | <pre><code>>>> import os
>>> os.name
'nt'
</code></pre>
<p>"The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'mac', 'os2', 'ce', 'java', 'riscos'." (c) <a href="http://docs.python.org/library/os.html#os.name" rel="nofollow">http://docs.python.org/library/os.html#os.name</a></p>
<pre><code>import os
if os.name == 'nt':
#yourcodehere
</code></pre>
| 4 | 2011-02-01T17:23:47Z | [
"python",
"windows",
"platform-detection"
] |
Reliably detect Windows in Python | 1,387,222 | <p>I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The <code>platform.platform</code> function comes close but only returns a string.</p>
<p>Unfortunately I don't know what to search for in that string for it to yield a reliable result. Does anyone know what to search for or does anyone know of another function that I'm missing here?</p>
| 30 | 2009-09-07T01:29:16Z | 7,637,706 | <p>For those that came here looking for a way to detect Cygwin from Python (as opposed to just detecting Windows), here are some example return values from <code>os.name</code> and <code>platform.system</code> on different platforms</p>
<pre><code>OS/build | os.name | platform.system()
-------------+---------+-----------------------
Win32 native | nt | Windows
Win32 cygwin | posix | CYGWIN_NT-5.1*
Win64 native | nt | Windows
Win64 cygwin | posix | CYGWIN_NT-6.1-WOW64*
Linux | posix | Linux
</code></pre>
<p>From this point, how to distinguish between Windows native and Cygwin should be obvious although I'm not convinced this is future proof.</p>
<p>* version numbers are for XP and Win7 respectively, do not rely on them</p>
| 36 | 2011-10-03T16:18:44Z | [
"python",
"windows",
"platform-detection"
] |
Globbing the processing of an object's attributes in Python? | 1,387,315 | <p>Here is a Django model I'm using.</p>
<pre><code>class Person(models.Model):
surname = models.CharField(max_length=255, null=True, blank=True)
first_name = models.CharField(max_length=255, null=True, blank=True)
middle_names = models.CharField(max_length=255, null=True, blank=True)
birth_year = WideYear(null=True, blank=True)
birth_year_uncertain = models.BooleanField()
death_year = WideYear(null=True, blank=True)
death_year_uncertain = models.BooleanField()
flourit_year = WideYear(null=True, blank=True)
flourit_year_uncertain = models.BooleanField()
FLOURIT_CHOICES = (
(u'D', u'Birth and death dates'),
(u'F', u'Flourit date'),
)
use_flourit = models.CharField('Date(s) to use', max_length=2, choices=FLOURIT_CHOICES)
def __unicode__(self):
if str(self.birth_year) == 'None':
self.birth_year = ''
if str(self.death_year) == 'None':
self.death_year = ''
if str(self.flourit_year) == 'None':
self.flourit_year = ''
if self.use_flourit == u'D':
return '%s, %s %s (%s - %s)' % (self.surname, self.first_name, self.middle_names, self.birth_year, self.death_year)
else:
return '%s, %s %s (fl. %s)' % (self.surname, self.first_name, self.middle_names, self.flourit_year)
</code></pre>
<p>This bit of code from the model's __unicode__ method seems rather verbose:</p>
<pre><code>if str(self.birth_year) == 'None':
self.birth_year = ''
if str(self.death_year) == 'None':
self.death_year = ''
if str(self.flourit_year) == 'None':
self.flourit_year = ''
</code></pre>
<p>Its aim is to stop the __unicode__ method from returning something like</p>
<blockquote>
<p>Murdoch, Rupert (1931 - None)</p>
</blockquote>
<p>and to ensure the method instead returns something like</p>
<blockquote>
<p>Murdoch, Rupert (1931 - )</p>
</blockquote>
<p>Is there a way to "glob" that bit of code somehow, e.g. using a wildcard so that all attributes of the <strong>self</strong> object are processed?</p>
<p>Something like this:</p>
<pre><code>if str(self.(*)) == 'None':
self.$1 = ''
</code></pre>
<p>Here, I've just used regular expression syntax to illustrate what I mean; obviously, it's not working python code. Essentially the idea is to loop through each of the attributes, checking if their str() representations are equal to 'None' and if so, setting them to ''. But it would be nice if this could be done more concisely than by setting up a for loop.</p>
| 1 | 2009-09-07T02:18:55Z | 1,387,326 | <pre><code>for n in dir(self):
if getattr(self, n) is None:
setattr(self, n, '')
</code></pre>
<p>I'm using the normal <code>is None</code> idiom, assuming there's no hypersubtle motivation for that weird alternative you're using, but that's a separate issue;-)</p>
<p><strong>Edit</strong>: if you're using a framework laden with VERY deep black-magic, like Django, perfectly normal Python approaches suddenly may become fraught -- as the OP seems to have indicated with a similarly-murky edit. Well, if the dark deep metaclasses of Django don't let this work (though I can't reproduce the issue as the OP reports it), there are always alternatives. In particular, since this is taking place inside a special method that SHOULDN'T alter the object (<code>__unicode__</code>, specifically), I recommend a simple auxiliary function (a plain good old stand-alone module-level function!):</p>
<pre><code>def b(atr): return atr or u''
</code></pre>
<p>to be used as follows:</p>
<pre><code>def __unicode__(self):
if self.use_flourit == u'D':
return '%s, %s %s (%s - %s)' % (
b(self.surname), b(self.first_name), b(self.middle_names),
b(self.birth_year), b(self.death_year)
)
else:
return '%s, %s %s (fl. %s)' % (
b(self.surname), b(self.first_name), b(self.middle_names),
b(self.flourit_year)
)
</code></pre>
<p>Note that my original answer is perfectly fine when (A) you WANT to alter <code>self</code> as needed (in converters such as <code>__unicode__</code>, <code>__str__</code>, <code>__repr__</code>, ..., you shouldn't!), AND (B) you're in a class that doesn't use REALLY deep, dark, soot-black magic (apparently Django's models superclass is breaking something absolutely fundamental such as <code>dir</code>, <code>setattr</code>, and/or <code>getattr</code> -- though even with that hypothesis I just can't reproduce the specific symptoms somewhat-reported by the OP).</p>
| 5 | 2009-09-07T02:21:59Z | [
"python",
"oop",
"django-models"
] |
MySQL INSERT data does not get stored in proper db, only temporary? | 1,387,573 | <p>I'm having trouble with MySQL or Python and can't seem to isolate the problem. <code>INSERT</code>s only seem to last the run of the script and are not stored in the database.</p>
<p>I have this script:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="example")
dbcursor = db.cursor()
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'before: '+str(temp)
dbcursor.execute('INSERT INTO tablename (data1, data2, data3) VALUES ("1", "a", "b")')
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'after: '+str(temp)
</code></pre>
<p>The first time I run it I get the expected output:</p>
<pre><code>>>>
before: ()
after: ((1L, 'a', 'b'),)
</code></pre>
<p>The problem is that if I run it again, the <code>before</code> comes out empty when it should already have the entry in it and the after doesn't break (data 1 is primary key).</p>
<pre><code>>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
</code></pre>
<p>If I try running the insert command twice in the same script it will break ("Duplicate entry for PRIMARY KEY")</p>
<p>Any idea what might be happening here?</p>
| 2 | 2009-09-07T04:37:21Z | 1,387,579 | <p>You are not committing the transaction. </p>
<pre><code>conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor()
cursor.execute(...)
conn.commit()
</code></pre>
<p><a href="http://www.kitebird.com/articles/pydbapi.html" rel="nofollow">Reference</a></p>
| 8 | 2009-09-07T04:40:32Z | [
"python",
"mysql"
] |
MySQL INSERT data does not get stored in proper db, only temporary? | 1,387,573 | <p>I'm having trouble with MySQL or Python and can't seem to isolate the problem. <code>INSERT</code>s only seem to last the run of the script and are not stored in the database.</p>
<p>I have this script:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="example")
dbcursor = db.cursor()
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'before: '+str(temp)
dbcursor.execute('INSERT INTO tablename (data1, data2, data3) VALUES ("1", "a", "b")')
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'after: '+str(temp)
</code></pre>
<p>The first time I run it I get the expected output:</p>
<pre><code>>>>
before: ()
after: ((1L, 'a', 'b'),)
</code></pre>
<p>The problem is that if I run it again, the <code>before</code> comes out empty when it should already have the entry in it and the after doesn't break (data 1 is primary key).</p>
<pre><code>>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
</code></pre>
<p>If I try running the insert command twice in the same script it will break ("Duplicate entry for PRIMARY KEY")</p>
<p>Any idea what might be happening here?</p>
| 2 | 2009-09-07T04:37:21Z | 1,387,589 | <p>I think you need to call</p>
<p>db.commit()</p>
| 3 | 2009-09-07T04:46:49Z | [
"python",
"mysql"
] |
MySQL INSERT data does not get stored in proper db, only temporary? | 1,387,573 | <p>I'm having trouble with MySQL or Python and can't seem to isolate the problem. <code>INSERT</code>s only seem to last the run of the script and are not stored in the database.</p>
<p>I have this script:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="example")
dbcursor = db.cursor()
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'before: '+str(temp)
dbcursor.execute('INSERT INTO tablename (data1, data2, data3) VALUES ("1", "a", "b")')
dbcursor.execute("select * from tablename")
temp = dbcursor.fetchall()
print 'after: '+str(temp)
</code></pre>
<p>The first time I run it I get the expected output:</p>
<pre><code>>>>
before: ()
after: ((1L, 'a', 'b'),)
</code></pre>
<p>The problem is that if I run it again, the <code>before</code> comes out empty when it should already have the entry in it and the after doesn't break (data 1 is primary key).</p>
<pre><code>>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
>>>
before: ()
after: ((1L, 'a', 'b'),)
</code></pre>
<p>If I try running the insert command twice in the same script it will break ("Duplicate entry for PRIMARY KEY")</p>
<p>Any idea what might be happening here?</p>
| 2 | 2009-09-07T04:37:21Z | 13,190,127 | <p>The problem is you are not committing the changes. it can be done by
conn.commit()</p>
<p>read more on this <a href="http://sahanlm.blogspot.com/2012/10/mysqldb-does-not-commit-then-read-this.html" rel="nofollow">here</a></p>
| 2 | 2012-11-02T06:02:19Z | [
"python",
"mysql"
] |
Verify CSV against given format | 1,387,644 | <p>I am expecting users to upload a CSV file of max size 1MB to a web form that should fit a given format similar to:</p>
<pre><code>"<String>","<String>",<Int>,<Float>
</code></pre>
<p>That will be processed later. I would like to verify the file fits a specified format so that the program that shall later use the file doesnt receive unexpected input and that there are no security concerns (say some injection attack against the parsing script that does some calculations and db insert).</p>
<p>(1) What would be the best way to go about doing this that would be fast and thorough? From what I've researched I could go the path of regex or something more like <a href="http://stackoverflow.com/questions/614469/regex-to-match-anything-except-certain-delimiters">this</a>. I've looked at the python csv module but that doesnt appear to have any built in verification.</p>
<p>(2) Assuming I go for a regex, can anyone direct me to towards the best way to do this? Do I match for illegal characters and reject on that? (eg. no '/' '\' '<' '>' '{' '}' etc.) or match on all legal eg. [a-zA-Z0-9]{1,10} for the string component? I'm not too familiar with regular expressions so pointers or examples would be appreciated. </p>
<p>EDIT:
Strings should contain no commas or quotes it would just contain a name (ie. first name, last name). And yes I forgot to add they would be double quoted.</p>
<p>EDIT #2:
Thanks for all the answers. Cutplace is quite interesting but is a standalone. Decided to go with pyparsing in the end because it gives more flexibility should I add more formats.</p>
| 0 | 2009-09-07T05:17:30Z | 1,387,669 | <p>Ideally, you want your filtering to be as restrictive as possible - the fewer things you allow, the fewer potential avenues of attack. For instance, a float or int field has a very small number of characters (and very few configurations of those characters) which should actually be allowed. String filtering should ideally be restricted to only what characters people would have a reason to input - without knowing the larger context it's hard to tell you exactly which you should allow, but at a bare minimum the string match regex should require quoting of strings and disallow anything that would terminate the string early.</p>
<p>Keep in mind, however, that some names may contain things like single quotes ("O'Neil", for instance) or dashes, so you couldn't necessarily rule those out.</p>
<p>Something like...</p>
<pre><code>/"[a-zA-Z' -]+"/
</code></pre>
<p>...would probably be ideal for double-quoted strings which are supposed to contain names. You could replace the <code>+</code> with a <code>{x,y}</code> length min/max if you wanted to enforce certain lengths as well.</p>
| 0 | 2009-09-07T05:28:10Z | [
"python",
"regex",
"csv"
] |
Verify CSV against given format | 1,387,644 | <p>I am expecting users to upload a CSV file of max size 1MB to a web form that should fit a given format similar to:</p>
<pre><code>"<String>","<String>",<Int>,<Float>
</code></pre>
<p>That will be processed later. I would like to verify the file fits a specified format so that the program that shall later use the file doesnt receive unexpected input and that there are no security concerns (say some injection attack against the parsing script that does some calculations and db insert).</p>
<p>(1) What would be the best way to go about doing this that would be fast and thorough? From what I've researched I could go the path of regex or something more like <a href="http://stackoverflow.com/questions/614469/regex-to-match-anything-except-certain-delimiters">this</a>. I've looked at the python csv module but that doesnt appear to have any built in verification.</p>
<p>(2) Assuming I go for a regex, can anyone direct me to towards the best way to do this? Do I match for illegal characters and reject on that? (eg. no '/' '\' '<' '>' '{' '}' etc.) or match on all legal eg. [a-zA-Z0-9]{1,10} for the string component? I'm not too familiar with regular expressions so pointers or examples would be appreciated. </p>
<p>EDIT:
Strings should contain no commas or quotes it would just contain a name (ie. first name, last name). And yes I forgot to add they would be double quoted.</p>
<p>EDIT #2:
Thanks for all the answers. Cutplace is quite interesting but is a standalone. Decided to go with pyparsing in the end because it gives more flexibility should I add more formats.</p>
| 0 | 2009-09-07T05:17:30Z | 1,387,719 | <p>I'd vote for parsing the file, checking you've got 4 components per record, that the first two components are strings, the third is an int (checking for NaN conditions), and the fourth is a float (also checking for NaN conditions).</p>
<p>Python would be an excellent tool for the job.</p>
<p>I'm not aware of any libraries in Python to deal with validation of CSV files against a spec, but it really shouldn't be too hard to write.</p>
<pre><code>import csv
import math
dataChecker = csv.reader(open('data.csv'))
for row in dataChecker:
if len(row) != 4:
print 'Invalid row length.'
return
my_int = int(row[2])
my_float = float(row[3])
if math.isnan(my_int):
print 'Bad int found'
return
if math.isnan(my_float):
print 'Bad float found'
return
print 'All good!'
</code></pre>
| 2 | 2009-09-07T05:48:01Z | [
"python",
"regex",
"csv"
] |
Verify CSV against given format | 1,387,644 | <p>I am expecting users to upload a CSV file of max size 1MB to a web form that should fit a given format similar to:</p>
<pre><code>"<String>","<String>",<Int>,<Float>
</code></pre>
<p>That will be processed later. I would like to verify the file fits a specified format so that the program that shall later use the file doesnt receive unexpected input and that there are no security concerns (say some injection attack against the parsing script that does some calculations and db insert).</p>
<p>(1) What would be the best way to go about doing this that would be fast and thorough? From what I've researched I could go the path of regex or something more like <a href="http://stackoverflow.com/questions/614469/regex-to-match-anything-except-certain-delimiters">this</a>. I've looked at the python csv module but that doesnt appear to have any built in verification.</p>
<p>(2) Assuming I go for a regex, can anyone direct me to towards the best way to do this? Do I match for illegal characters and reject on that? (eg. no '/' '\' '<' '>' '{' '}' etc.) or match on all legal eg. [a-zA-Z0-9]{1,10} for the string component? I'm not too familiar with regular expressions so pointers or examples would be appreciated. </p>
<p>EDIT:
Strings should contain no commas or quotes it would just contain a name (ie. first name, last name). And yes I forgot to add they would be double quoted.</p>
<p>EDIT #2:
Thanks for all the answers. Cutplace is quite interesting but is a standalone. Decided to go with pyparsing in the end because it gives more flexibility should I add more formats.</p>
| 0 | 2009-09-07T05:17:30Z | 1,387,737 | <p>Here's a small snippet I made:</p>
<pre><code>import csv
f = csv.reader(open("test.csv"))
for value in f:
value[0] = str(value[0])
value[1] = str(value[1])
value[2] = int(value[2])
value[3] = float(value[3])
</code></pre>
<p>If you run that with a file that doesn't have the format your specified, you'll get an exception:</p>
<pre><code>$ python valid.py
Traceback (most recent call last):
File "valid.py", line 8, in <module>
i[2] = int(i[2])
ValueError: invalid literal for int() with base 10: 'a3'
</code></pre>
<p>You can then make a try-except ValueError to catch it and let the users know what they did wrong.</p>
| 1 | 2009-09-07T05:53:40Z | [
"python",
"regex",
"csv"
] |
Verify CSV against given format | 1,387,644 | <p>I am expecting users to upload a CSV file of max size 1MB to a web form that should fit a given format similar to:</p>
<pre><code>"<String>","<String>",<Int>,<Float>
</code></pre>
<p>That will be processed later. I would like to verify the file fits a specified format so that the program that shall later use the file doesnt receive unexpected input and that there are no security concerns (say some injection attack against the parsing script that does some calculations and db insert).</p>
<p>(1) What would be the best way to go about doing this that would be fast and thorough? From what I've researched I could go the path of regex or something more like <a href="http://stackoverflow.com/questions/614469/regex-to-match-anything-except-certain-delimiters">this</a>. I've looked at the python csv module but that doesnt appear to have any built in verification.</p>
<p>(2) Assuming I go for a regex, can anyone direct me to towards the best way to do this? Do I match for illegal characters and reject on that? (eg. no '/' '\' '<' '>' '{' '}' etc.) or match on all legal eg. [a-zA-Z0-9]{1,10} for the string component? I'm not too familiar with regular expressions so pointers or examples would be appreciated. </p>
<p>EDIT:
Strings should contain no commas or quotes it would just contain a name (ie. first name, last name). And yes I forgot to add they would be double quoted.</p>
<p>EDIT #2:
Thanks for all the answers. Cutplace is quite interesting but is a standalone. Decided to go with pyparsing in the end because it gives more flexibility should I add more formats.</p>
| 0 | 2009-09-07T05:17:30Z | 1,387,762 | <p>There can be a lot of corner-cases for parsing CSV, so you probably don't want to try doing it "by hand". At least start with a package/library built-in to the language that you're using, even if it doesn't do all the "verification" you can think of.</p>
<p>Once you get there, then examine the fields for your list of "illegal" chars, or examine the values in each field to determine they're valid (if you can do so). You also don't even need a regex for this task necessarily, but it may be more concise to do it that way.</p>
<p>You might also disallow embedded \r or \n, \0 or \t. Just loop through the fields and check them after you've loaded the data with your csv lib.</p>
| 1 | 2009-09-07T06:05:08Z | [
"python",
"regex",
"csv"
] |
Verify CSV against given format | 1,387,644 | <p>I am expecting users to upload a CSV file of max size 1MB to a web form that should fit a given format similar to:</p>
<pre><code>"<String>","<String>",<Int>,<Float>
</code></pre>
<p>That will be processed later. I would like to verify the file fits a specified format so that the program that shall later use the file doesnt receive unexpected input and that there are no security concerns (say some injection attack against the parsing script that does some calculations and db insert).</p>
<p>(1) What would be the best way to go about doing this that would be fast and thorough? From what I've researched I could go the path of regex or something more like <a href="http://stackoverflow.com/questions/614469/regex-to-match-anything-except-certain-delimiters">this</a>. I've looked at the python csv module but that doesnt appear to have any built in verification.</p>
<p>(2) Assuming I go for a regex, can anyone direct me to towards the best way to do this? Do I match for illegal characters and reject on that? (eg. no '/' '\' '<' '>' '{' '}' etc.) or match on all legal eg. [a-zA-Z0-9]{1,10} for the string component? I'm not too familiar with regular expressions so pointers or examples would be appreciated. </p>
<p>EDIT:
Strings should contain no commas or quotes it would just contain a name (ie. first name, last name). And yes I forgot to add they would be double quoted.</p>
<p>EDIT #2:
Thanks for all the answers. Cutplace is quite interesting but is a standalone. Decided to go with pyparsing in the end because it gives more flexibility should I add more formats.</p>
| 0 | 2009-09-07T05:17:30Z | 1,389,585 | <p>Try <a href="http://cutplace.sourceforge.net/" rel="nofollow">Cutplace</a>. It verifies that tabluar data conforms to an <em>interface control document</em>.</p>
| 1 | 2009-09-07T14:05:57Z | [
"python",
"regex",
"csv"
] |
Verify CSV against given format | 1,387,644 | <p>I am expecting users to upload a CSV file of max size 1MB to a web form that should fit a given format similar to:</p>
<pre><code>"<String>","<String>",<Int>,<Float>
</code></pre>
<p>That will be processed later. I would like to verify the file fits a specified format so that the program that shall later use the file doesnt receive unexpected input and that there are no security concerns (say some injection attack against the parsing script that does some calculations and db insert).</p>
<p>(1) What would be the best way to go about doing this that would be fast and thorough? From what I've researched I could go the path of regex or something more like <a href="http://stackoverflow.com/questions/614469/regex-to-match-anything-except-certain-delimiters">this</a>. I've looked at the python csv module but that doesnt appear to have any built in verification.</p>
<p>(2) Assuming I go for a regex, can anyone direct me to towards the best way to do this? Do I match for illegal characters and reject on that? (eg. no '/' '\' '<' '>' '{' '}' etc.) or match on all legal eg. [a-zA-Z0-9]{1,10} for the string component? I'm not too familiar with regular expressions so pointers or examples would be appreciated. </p>
<p>EDIT:
Strings should contain no commas or quotes it would just contain a name (ie. first name, last name). And yes I forgot to add they would be double quoted.</p>
<p>EDIT #2:
Thanks for all the answers. Cutplace is quite interesting but is a standalone. Decided to go with pyparsing in the end because it gives more flexibility should I add more formats.</p>
| 0 | 2009-09-07T05:17:30Z | 1,389,940 | <p>Pyparsing will process this data, and will be tolerant of unexpected things like spaces before and after commas, commas within quotes, etc. (csv module is too, but regex solutions force you to add "\s*" bits all over the place).</p>
<pre><code>from pyparsing import *
integer = Regex(r"-?\d+").setName("integer")
integer.setParseAction(lambda tokens: int(tokens[0]))
floatnum = Regex(r"-?\d+\.\d*").setName("float")
floatnum.setParseAction(lambda tokens: float(tokens[0]))
dblQuotedString.setParseAction(removeQuotes)
COMMA = Suppress(',')
validLine = dblQuotedString + COMMA + dblQuotedString + COMMA + \
integer + COMMA + floatnum + LineEnd()
tests = """\
"good data","good2",100,3.14
"good data" , "good2", 100, 3.14
bad, "good","good2",100,3.14
"bad","good2",100,3
"bad","good2",100.5,3
""".splitlines()
for t in tests:
print t
try:
print validLine.parseString(t).asList()
except ParseException, pe:
print pe.markInputline('?')
print pe.msg
print
</code></pre>
<p>Prints</p>
<pre><code>"good data","good2",100,3.14
['good data', 'good2', 100, 3.1400000000000001]
"good data" , "good2", 100, 3.14
['good data', 'good2', 100, 3.1400000000000001]
bad, "good","good2",100,3.14
?bad, "good","good2",100,3.14
Expected string enclosed in double quotes
"bad","good2",100,3
"bad","good2",100,?3
Expected float
"bad","good2",100.5,3
"bad","good2",100?.5,3
Expected ","
</code></pre>
<p>You will probably be stripping those quotation marks off at some future time, pyparsing can do that at parse time by adding:</p>
<pre><code>dblQuotedString.setParseAction(removeQuotes)
</code></pre>
<p>If you want to add comment support to your input file, say a '#' followed by the rest of the line, you can do this:</p>
<pre><code>comment = '#' + restOfline
validLine.ignore(comment)
</code></pre>
<p>You can also add names to these fields, so that you can access them by name instead of index position (which I find gives more robust code in light of changes down the road):</p>
<pre><code>validLine = dblQuotedString("key") + COMMA + dblQuotedString("title") + COMMA + \
integer("qty") + COMMA + floatnum("price") + LineEnd()
</code></pre>
<p>And your post-processing code can then do this:</p>
<pre><code>data = validLine.parseString(t)
print "%(key)s: %(title)s, %(qty)d in stock at $%(price).2f" % data
print data.qty*data.price
</code></pre>
| 3 | 2009-09-07T15:46:20Z | [
"python",
"regex",
"csv"
] |
PyGTK: IM Client Window | 1,387,729 | <p>I'm trying to write something very similar to an IM client (for learning purposes only). I don't know how to write the Chat window. I want to display Users picture, name and message as any other IM client. The problem is that I don't know which gtk widget is best suited for it. Currently I use TextView and TextBuffers but I can't display Pictures and Links in the TextView. How does pidgin or empathy handle this?.</p>
<p>I'm using Glade with GtkBuilder</p>
| 0 | 2009-09-07T05:51:09Z | 1,389,972 | <p>You can display images in a gtk.TextBuffer, here is how: <a href="http://pygtk.org/pygtk2tutorial/sec-TextBuffers.html#id2855808" rel="nofollow">http://pygtk.org/pygtk2tutorial/sec-TextBuffers.html#id2855808</a></p>
| 2 | 2009-09-07T15:53:27Z | [
"python",
"gtk",
"pygtk"
] |
Applescript - pygame, application bundle | 1,387,775 | <p>I'm trying to learn pygame, And I found the best way to have the finished game (assuming python 2.6 and pygame installed) is to have an applescript that runs it, and saved as an app bundle (with python files etc. inside the bundle). Here is what I have:</p>
<pre><code>do shell script "cd " & the quoted form of the POSIX path of (path to me) & "Contents/Resources/files\n/usr/local/bin/pythonw creeps.py"
</code></pre>
<p>I need the cd command because the python code uses the relative path to get at its images folder. The files directory is where my python files are, and subdirectories such as 'images'. I think having an app file like this is a lot better than a lone .py file, which could opened by anything by default. Do you think this is a good way to bundle a python script? Also, would I be able to just bundle pygame along with it instead of requiring that to be installed too? Thanks.</p>
<p>Also, now, the script runs and python is also running, each with their own dock icons. Could I make it so that the script just executes and quits, leaving python running? Thanks.</p>
<p>I changed the script to:</p>
<pre><code>do shell script ". ~/.bash_profile\npythonw2.6 " & the quoted form of the POSIX path of (path to me) & "Contents/Resources/files/creeps.py"
</code></pre>
<p>That way, it searches the path instead of only looking in /usr/local/bin. <code>~/.bash_profile</code> needs to be called to set and export the $PATH for python (which it automatically adds in <code>.bash_profile</code> when you install python).</p>
<p>A problem is that the script app bundle 'isn't responding' while its running, but the Python app is fine. How can I make the script app bundle get python going and then quit and leave python there by itself? And couldn't I just put the pygame module inside the bundle? Its only ~9MB.</p>
| 0 | 2009-09-07T06:11:16Z | 1,387,857 | <p><a href="http://www.pyinstaller.org/" rel="nofollow">pyinstaller</a> should let you bundle pygame (use the SVN version: the released one is WAY out of date). Also, I suggest you have your code find relative directories more nicely:</p>
<pre><code>import os
resourcesdir = os.path.join(os.path.dirname(__file__), 'Resources')
</code></pre>
<p>or the like, to avoid that clunky cd;-).</p>
| 1 | 2009-09-07T06:38:48Z | [
"python",
"osx",
"applescript",
"pygame"
] |
how to convert base64 /radix64 public key to a pem format in python | 1,387,867 | <p>is there any python method for converting base64 encoded key to a pem format .</p>
<p>how to convert ASCII-armored PGP public key to a MIME encoded form.</p>
<p>thanks</p>
| 0 | 2009-09-07T06:41:35Z | 1,389,908 | <p>ASCII-armored and PEM are very similar. You just need to change the BEGIN/END markers, strip the PGP headers and checksums. I've done this before in PHP. I just ported it to Python for you,</p>
<pre><code>import re
import StringIO
def pgp_pubkey_to_pem(pgp_key):
# Normalise newlines
pgp_key = re.compile('(\n|\r\n|\r)').sub('\n', pgp_key)
# Extract block
buffer = StringIO.StringIO()
# Write PEM header
buffer.write('-----BEGIN RSA PUBLIC KEY-----\n')
in_block = 0
in_body = 0
for line in pgp_key.split('\n'):
if line.startswith('-----BEGIN PGP PUBLIC KEY BLOCK-----'):
in_block = 1
elif in_block and line.strip() == '':
in_body = 1
elif in_block and line.startswith('-----END PGP PUBLIC KEY BLOCK-----'):
# No checksum, ignored for now
break
elif in_body and line.startswith('='):
# Checksum, end of the body
break
elif in_body:
buffer.write(line+'\n')
# Write PEM footer
buffer.write('-----END RSA PUBLIC KEY-----\n')
return buffer.getvalue()
</code></pre>
| 5 | 2009-09-07T15:33:57Z | [
"python",
"encoding"
] |
IF statement causing internal server error with webpy | 1,387,902 | <p>I have this class:</p>
<pre><code>class View(object):
def main_page(self, extra_placeholders = None):
file = '/media/Shared/sites/www/subdomains/pypular/static/layout.tmpl'
placeholders = { 'site_name' : 'pypular' }
# If we passed placeholders vars, append them
if extra_placeholders != None:
for k, v in extra_placeholders.iteritems():
placeholders[k] = v
</code></pre>
<p>My problem in the code above is the if statement</p>
<p>As you can see, the function takes an argument(extra_placeholders) which is a dict.</p>
<p>If i don't pass a parameter to main_page(),</p>
<pre><code>if extra_placeholders == None:
return 'i executed'
</code></pre>
<p>runs fine. however,</p>
<pre><code>if extra_placeholders != None:
return 'i cause error'
</code></pre>
<p>does not work. it causes a 500 internal server error. Why?</p>
| 1 | 2009-09-07T06:54:40Z | 1,387,918 | <p>should you be using instead</p>
<pre><code>if !( extra_placeholders is None) :
</code></pre>
<p>See <a href="http://boodebr.org/main/python/tourist/none-empty-nothing" rel="nofollow">here</a></p>
<p>Edit: To reflect comment:</p>
<p>It appears (thanks) that you can also use:</p>
<pre><code> if extra_placeholders is not None :
</code></pre>
| 1 | 2009-09-07T07:01:22Z | [
"python",
"mod-wsgi",
"web.py"
] |
C++ with Python embedding: crash if Python not installed | 1,387,906 | <p>I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing.</p>
<p>I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes.</p>
<p>I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase.</p>
<p>A few hours ago, I tried the app on my laptop that has Python <strong>2.6</strong> installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails.</p>
<p>I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash.</p>
<p>I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it.</p>
<p>What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue.</p>
<p>Thank you very much in advance.</p>
| 14 | 2009-09-07T06:56:51Z | 1,387,977 | <p>In addition to pythonxy.dll, you also need the entire Python library, i.e. the contents of the lib folder, plus the extension modules, i.e. the contents of the DLLs folder. Without the standard library, Python won't even start, since it tries to find os.py (in 3.x; string.py in 2.x). On startup, it imports a number of modules, in particular site.py.</p>
<p>There are various locations where it searches for the standard library; in your cases, it eventually finds it in the registry. Before, uses the executable name (as set through Py_SetProgramName) trying to find the landmark; it also checks for a file python31.zip which should be a zipped copy of the standard library. It also checks for a environment variable PYTHONHOME.</p>
<p>You are free to strip the library from stuff that you don't need; there are various tools that compute dependencies statically (modulefinder in particular).</p>
<p>If you want to minimize the number of files, you can</p>
<ol>
<li>link all extension modules statically into your pythonxy.dll, or even link pythonxy.dll statically into your application</li>
<li>use the freeze tool; this will allow linking the byte code of the standard library into your pythonxy.dll.</li>
<li>(alternatively to 2.) use pythonxy.zip for the standard library.</li>
</ol>
| 18 | 2009-09-07T07:16:51Z | [
"c++",
"python",
"dll",
"embed",
"distribution"
] |
C++ with Python embedding: crash if Python not installed | 1,387,906 | <p>I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing.</p>
<p>I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes.</p>
<p>I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase.</p>
<p>A few hours ago, I tried the app on my laptop that has Python <strong>2.6</strong> installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails.</p>
<p>I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash.</p>
<p>I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it.</p>
<p>What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue.</p>
<p>Thank you very much in advance.</p>
| 14 | 2009-09-07T06:56:51Z | 2,970,407 | <p>Nice. And if you do not want to zip, copy Python26\DLLs & Python26\lib to your exe directory as:</p>
<pre><code>.\myexe.exe
.\python26.dll
.\Python26\DLLs
.\Python26\lib
</code></pre>
<p>And then set PYTHONHOME with Py_SetPythonHome() API. Apparently, this API is not in the list of "allowed" calls <strong>before</strong> Py_Initialize();</p>
<p>Below worked for me on Windows (Python not <em>installed</em>):</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include "Python.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char pySearchPath[] = "Python26";
Py_SetPythonHome(pySearchPath);
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
//cerr << Py_GetPath() << endl;
Py_Finalize();
return 0;
}
</code></pre>
<p>Good that the search path is relative w.r.t the exe. Py_GetPath can show you where all it is looking for the modules. </p>
| 10 | 2010-06-03T23:02:34Z | [
"c++",
"python",
"dll",
"embed",
"distribution"
] |
C++ with Python embedding: crash if Python not installed | 1,387,906 | <p>I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing.</p>
<p>I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes.</p>
<p>I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase.</p>
<p>A few hours ago, I tried the app on my laptop that has Python <strong>2.6</strong> installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails.</p>
<p>I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash.</p>
<p>I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it.</p>
<p>What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue.</p>
<p>Thank you very much in advance.</p>
| 14 | 2009-09-07T06:56:51Z | 9,115,925 | <p>A zip of the Python standard library worked for me with Python27.</p>
<p>I zipped <strong>the contents</strong> of Lib and dll, and made sure there was no additional python27-subfolder or Lib or dll subfolder. i.e. just a zip named python27.zip containing all the files.</p>
<p>I copied that zip and the python27.dll alongside the executable.</p>
| 4 | 2012-02-02T16:25:54Z | [
"c++",
"python",
"dll",
"embed",
"distribution"
] |
C++ with Python embedding: crash if Python not installed | 1,387,906 | <p>I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing.</p>
<p>I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes.</p>
<p>I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase.</p>
<p>A few hours ago, I tried the app on my laptop that has Python <strong>2.6</strong> installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails.</p>
<p>I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash.</p>
<p>I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it.</p>
<p>What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue.</p>
<p>Thank you very much in advance.</p>
| 14 | 2009-09-07T06:56:51Z | 12,539,448 | <p>I wanted to add some additional info for others who might still be having troubles with this, as I was. I was eventually able to get my application working using the method proposed by user sambha, that is:</p>
<pre>
Program Files (x86)\
MyApplicationFolder\
MyApplication.exe
python27.dll
Python27\
DLLs\ (contents of DLLs folder)
Lib\ (contents of Lib folder)
</pre>
<p>...with one <strong>important</strong> addition: I also needed to install the MSVCR90.DLL. I'm using Python 2.7 and apparently python27.dll requires the MSVCR90.DLL (and maybe other MSVC*90.DLLs).</p>
<p>I solved this by downloading, installing, and running the 'vcredist_x86.exe' package from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=29">http://www.microsoft.com/en-us/download/details.aspx?id=29</a> . I think, though I am not certain, that you need to do it this way at least on Win7, as opposed to simply placing the MSVC*90.DLLs alongside your .exe as you may have done in the past. The Microsoft installer places the files and registers them in a special way under Win7.</p>
<p>I also tried the .zip file method but that did not work, even with the MSVCR90.DLL installed.</p>
| 5 | 2012-09-21T23:39:36Z | [
"c++",
"python",
"dll",
"embed",
"distribution"
] |
Django: Simple rate limiting | 1,387,937 | <p>Many of my views fetch external resources. I want to make sure that under heavy load I don't blow up the remote sites (and/or get banned).</p>
<p>I only have 1 crawler so having a central lock will work fine.</p>
<p>So the details: I want to allow at most 3 queries to a host per second, and have the rest block for a maximum of 15 seconds. How could I do this (easily)?</p>
<p>Some thoughts :</p>
<ul>
<li>Use django cache
<ul>
<li>Seems to only have 1 second resolution</li>
</ul></li>
<li>Use a file based semaphore
<ul>
<li>Easy to do locks for concurrency. Not sure how to make sure only 3 fetches happen a second.</li>
</ul></li>
<li>Use some shared memory state
<ul>
<li>I'd rather not install more things, but will if I have to.</li>
</ul></li>
</ul>
| 4 | 2009-09-07T07:08:12Z | 1,388,111 | <p>What about using a different process to handle scraping, and a queue for the communication between it and Django?<br />
This way you would be able to easily change the number of concurrent requests, and it would also automatically keep track of the requests, without blocking the caller.<br />
Most of all, I think it would help lowering the complexity of the main application (in Django).</p>
| 1 | 2009-09-07T08:00:28Z | [
"python",
"django",
"caching",
"mutex",
"semaphore"
] |
Django: Simple rate limiting | 1,387,937 | <p>Many of my views fetch external resources. I want to make sure that under heavy load I don't blow up the remote sites (and/or get banned).</p>
<p>I only have 1 crawler so having a central lock will work fine.</p>
<p>So the details: I want to allow at most 3 queries to a host per second, and have the rest block for a maximum of 15 seconds. How could I do this (easily)?</p>
<p>Some thoughts :</p>
<ul>
<li>Use django cache
<ul>
<li>Seems to only have 1 second resolution</li>
</ul></li>
<li>Use a file based semaphore
<ul>
<li>Easy to do locks for concurrency. Not sure how to make sure only 3 fetches happen a second.</li>
</ul></li>
<li>Use some shared memory state
<ul>
<li>I'd rather not install more things, but will if I have to.</li>
</ul></li>
</ul>
| 4 | 2009-09-07T07:08:12Z | 1,388,112 | <p>One approach; create a table like this:</p>
<pre><code>class Queries(models.Model):
site = models.CharField(max_length=200, db_index=True)
start_time = models.DateTimeField(null = True)
finished = models.BooleanField(default=False)
</code></pre>
<p>This records when each query has either taken place, or will take place in the future if the limiting prevents it from happening immediately. start_time is the time the action is to start; this is in the future if the action is currently blocking.</p>
<p>Instead of thinking in terms of queries per second, let's think in terms of seconds per query; in this case, 1/3 second per query.</p>
<p>Whenever an action is to be performed, do the following:</p>
<ul>
<li>Create a row for the action. q = Queries.objects.create(site=sitename)</li>
<li>On the object you just created (q.id), atomically set <code>start_time</code> to the greatest start_time for this site plus 1/3 second. If the greatest is 10 seconds in the future, then we can start our action at 10 1/3 seconds. If that time is in the past, clamp it to now().</li>
<li>If the start_time that was just set is in the future, sleep until that time. If it's too far in the future (eg. over 15 seconds), delete the row and error out.</li>
<li>When the query is finished, set finished to True, so the row can be purged later on.</li>
</ul>
<p>The atomic action is what's important. You can't simply do an aggregate on Queries and then save it, since it'll race. I don't know if Django can do this natively, but it's easy enough in raw SQL:</p>
<pre><code>UPDATE site_queries
SET start_time = MAX(now(), COALESCE(now(), (
SELECT MAX(start_time) + 1.0/3 FROM site_queries WHERE site = site_name
)))
WHERE id = object_id
</code></pre>
<p>Then, reload the model and sleep if necessary. You'll also need to purge old rows. Something like Queries.objects.filter(site=site, finished=True).exclude(id=id).delete() will probably work: delete all finished queries except the one you just made. (That way, you never delete the <em>latest</em> query, since later queries need that to be scheduled.)</p>
<p>Finally, make sure the UPDATE doesn't take place in a transaction. Autocommit must be turned on for this to work. Otherwise, the UPDATE won't be atomic: it'd be possible for two requests to UPDATE at the same time, and receive the same result. Django and Python typically have autocommit off, so you need to turn it on and then back off. With Postgres, this is connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) and ISOLATION_LEVEL_READ_COMMITTED. I don't know how to do this with MySQL.</p>
<p>(I consider the default of having autocommit turned off in Python's DB-API to be a seriously design flaw.)</p>
<p>The benefit of this approach is that it's quite simple, with straightforward state; you don't need things like event listeners and wakeups, which have their own sets of problems.</p>
<p>A possible issue is that if the user cancels the request during the delay, whether or not you do the action, the delay is still enforced. If you never start the action, other requests won't move down into the unused "timeslot".</p>
<p>If you're not able to get autocommit to work, a workaround would be to add a UNIQUE constraint to (site, start_time). (I don't think Django understands that directly, so you'd need to add the constraint yourself.) Then, if the race happens and two requests to the same site end up at the same time, one of them will throw a constraint exception that you can catch, and you can just retry. You could also use a normal Django aggregate instead of raw SQL. Catching constraint exceptions isn't as robust, though.</p>
| 1 | 2009-09-07T08:00:29Z | [
"python",
"django",
"caching",
"mutex",
"semaphore"
] |
Upgrade python in linux | 1,388,464 | <p>I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?</p>
| 2 | 2009-09-07T09:36:41Z | 1,388,489 | <p>The UUID module exists as a separate package for Python 2.3 and up:</p>
<p><a href="http://pypi.python.org/pypi/uuid/1.30" rel="nofollow">http://pypi.python.org/pypi/uuid/1.30</a></p>
<p>So you can either install that in your Python2.4, or install Python2.6. If your distro doesn't have it, then Python is quite simple to compile from source. Look through the requirements to make sure all the libraries you need/want are installed before compiling Python. That's it.</p>
| 2 | 2009-09-07T09:42:19Z | [
"python",
"linux"
] |
Upgrade python in linux | 1,388,464 | <p>I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?</p>
| 2 | 2009-09-07T09:36:41Z | 1,388,552 | <p>The safest way to upgrading Python is to install it to a different location (away from the default system path).</p>
<p>To do this, download the source of python and do a </p>
<p>./configure --prefix=/opt</p>
<p>(Assuming you want to install it to /opt which is where most install non system dependant stuff to)</p>
<p>The reason why I say this is because some other system libraries may depend on the current version of python.</p>
<p>Another reason is that as you are doing your own custom development, it is much better to have control over what version of the libraries (or interpreters) you are using rather than have a operating system patch break something that was working before. A controlled upgrade is better than having the application break on you all of a sudden.</p>
| 6 | 2009-09-07T10:02:02Z | [
"python",
"linux"
] |
Upgrade python in linux | 1,388,464 | <p>I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?</p>
| 2 | 2009-09-07T09:36:41Z | 1,391,295 | <p>The best solution will be installing python2.6 in the choosen directory - It will you give you access to many great features and better memory handling (infamous python=2.4 memory leak problem).</p>
<p>I have got several pythons installed onto my two computers, I found that the best solution for are two directories:</p>
<p>$HOME/usr-32
$HOME/usr-64</p>
<p>respectively to using operating system (I share $HOME between 32 and 64 bit versions of Linux).</p>
<p>In each I have one directory for every application/program, for example:</p>
<pre>
ls ~/usr-64/python-2.6.2/
bin include lib share
</pre>
<p>It leads completetely to avoiding conflicts between version and gives great portability (you can use usb pendrives etc).</p>
<p>Python 2.6.2 in previously example has been installed with option:</p>
<pre>
./configure --prefix=$HOME/usr-64/python-2.6.2
</pre>
| 0 | 2009-09-07T23:24:54Z | [
"python",
"linux"
] |
How to get output from subprocess.Popen() | 1,388,753 | <p>I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work. </p>
<p><strong>Test_Pipe.py</strong></p>
<pre><code>import time
while True :
print "Someting ..."
time.sleep(.1)
</code></pre>
<p><strong>Caller.py</strong></p>
<pre><code>import subprocess as subp
import time
proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin=subp.PIPE)
while True :
data = proc.stdout.readline() #block / wait
print data
time.sleep(.1)
</code></pre>
<p>The line <code>proc.stdout.readline()</code> was blocked, so no data prints out.</p>
| 26 | 2009-09-07T10:50:52Z | 1,388,807 | <p>You obviously can use subprocess.communicate but I think you are looking for real time input and output.</p>
<p>readline was blocked because the process is probably waiting on your input. You can read character by character to overcome this like the following:</p>
<pre><code>import subprocess
import sys
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
</code></pre>
| 29 | 2009-09-07T11:04:18Z | [
"python",
"linux",
"subprocess",
"popen"
] |
How to get output from subprocess.Popen() | 1,388,753 | <p>I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work. </p>
<p><strong>Test_Pipe.py</strong></p>
<pre><code>import time
while True :
print "Someting ..."
time.sleep(.1)
</code></pre>
<p><strong>Caller.py</strong></p>
<pre><code>import subprocess as subp
import time
proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin=subp.PIPE)
while True :
data = proc.stdout.readline() #block / wait
print data
time.sleep(.1)
</code></pre>
<p>The line <code>proc.stdout.readline()</code> was blocked, so no data prints out.</p>
| 26 | 2009-09-07T10:50:52Z | 1,390,035 | <p>To avoid the many problems that can always arise with buffering for tasks such as "getting the subprocess's output to the main process in real time", I always recommend using <a href="http://sourceforge.net/projects/pexpect/" rel="nofollow">pexpect</a> for all non-Windows platform, <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/" rel="nofollow">wexpect</a> on Windows, instead of <code>subprocess</code>, when such tasks are desired.</p>
| 11 | 2009-09-07T16:10:41Z | [
"python",
"linux",
"subprocess",
"popen"
] |
How to get output from subprocess.Popen() | 1,388,753 | <p>I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work. </p>
<p><strong>Test_Pipe.py</strong></p>
<pre><code>import time
while True :
print "Someting ..."
time.sleep(.1)
</code></pre>
<p><strong>Caller.py</strong></p>
<pre><code>import subprocess as subp
import time
proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin=subp.PIPE)
while True :
data = proc.stdout.readline() #block / wait
print data
time.sleep(.1)
</code></pre>
<p>The line <code>proc.stdout.readline()</code> was blocked, so no data prints out.</p>
| 26 | 2009-09-07T10:50:52Z | 3,536,709 | <p>Nadia's snippet does work but calling read with a 1 byte buffer is highly unrecommended. The better way to do this would be to set the stdout file descriptor to nonblocking using fcntl</p>
<pre><code>fcntl.fcntl(
proc.stdout.fileno(),
fcntl.F_SETFL,
fcntl.fcntl(proc.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,
)
</code></pre>
<p>and then using select to test if the data is ready</p>
<pre><code>while proc.poll() == None:
readx = select.select([proc.stdout.fileno()], [], [])[0]
if readx:
chunk = proc.stdout.read()
print chunk
</code></pre>
<p>She was correct in that your problem must be different from what you posted as Caller.py and Test_Pipe.py do work as provided.</p>
<ul>
<li><a href="https://derrickpetzold.com/p/capturing-output-from-ffmpeg-python/">https://derrickpetzold.com/p/capturing-output-from-ffmpeg-python/</a></li>
</ul>
| 17 | 2010-08-21T07:03:19Z | [
"python",
"linux",
"subprocess",
"popen"
] |
How to get output from subprocess.Popen() | 1,388,753 | <p>I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work. </p>
<p><strong>Test_Pipe.py</strong></p>
<pre><code>import time
while True :
print "Someting ..."
time.sleep(.1)
</code></pre>
<p><strong>Caller.py</strong></p>
<pre><code>import subprocess as subp
import time
proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin=subp.PIPE)
while True :
data = proc.stdout.readline() #block / wait
print data
time.sleep(.1)
</code></pre>
<p>The line <code>proc.stdout.readline()</code> was blocked, so no data prints out.</p>
| 26 | 2009-09-07T10:50:52Z | 17,701,672 | <p><code>Test_Pipe.py</code> buffers its stdout by default so <code>proc</code> in <code>Caller.py</code> don't see any output until the child's buffer is full (if the buffer size is 8KB then it takes around a minute to fill <code>Test_Pipe.py</code>'s stdout buffer).</p>
<p>To make the output unbuffered (line-buffered for text streams) you could pass <a href="http://docs.python.org/2/using/cmdline.html#cmdoption-u" rel="nofollow"><code>-u</code> flag</a> to the child Python script. It allows to read subprocess' output line by line in "real-time":</p>
<pre><code>import sys
from subprocess import Popen, PIPE
proc = Popen([sys.executable, "-u", "Test_Pipe.py"], stdout=PIPE, bufsize=1)
for line in iter(proc.stdout.readline, b''):
print line,
proc.communicate()
</code></pre>
<p>See links in <a href="http://stackoverflow.com/a/17698359/4279">Python: read streaming input from subprocess.communicate()</a> on how to solve the block-buffering issue for non-Python child processes.</p>
| 2 | 2013-07-17T13:53:02Z | [
"python",
"linux",
"subprocess",
"popen"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 1,388,836 | <p>Not the most efficient one, but by far the most obvious way to do it is:</p>
<pre><code>>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}
</code></pre>
<p>if order is significant you can do it with list comprehensions like this:</p>
<pre><code>>>> [i for i, j in zip(a, b) if i == j]
[5]
</code></pre>
<p>(only works for equal-sized lists, which order-significance implies).</p>
| 210 | 2009-09-07T11:10:46Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 1,388,837 | <p>The easiest way to do that is to use <a href="http://docs.python.org/library/stdtypes.html#set-types-set-frozenset">sets</a>:</p>
<pre><code>>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
set([5])
</code></pre>
| 9 | 2009-09-07T11:10:53Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 1,388,842 | <p>Use <a href="http://docs.python.org/library/stdtypes.html#set.intersection">set.intersection()</a>, it's fast and readable.</p>
<pre><code>>>> set(a).intersection(b)
set([5])
</code></pre>
| 190 | 2009-09-07T11:11:36Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 1,388,848 | <p>Quick way:</p>
<pre><code>list(set(a).intersection(set(b)))
</code></pre>
| 8 | 2009-09-07T11:12:28Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 1,388,856 | <p>Do you want duplicates? If not maybe you should use sets instead:</p>
<pre><code>
>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
set([5])
</code></pre>
| 5 | 2009-09-07T11:14:14Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 1,388,864 | <p>You can use </p>
<pre><code>def returnMatches(a,b):
return list(set(a) & set(b))
</code></pre>
| 3 | 2009-09-07T11:16:17Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 3,056,197 | <pre><code>>>> s = ['a','b','c']
>>> f = ['a','b','d','c']
>>> ss= set(s)
>>> fs =set(f)
>>> print ss.intersection(fs)
**set(['a', 'c', 'b'])**
>>> print ss.union(fs)
**set(['a', 'c', 'b', 'd'])**
>>> print ss.union(fs) - ss.intersection(fs)
**set(['d'])**
</code></pre>
| 7 | 2010-06-16T18:41:45Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 3,834,580 | <p>I prefer the set based answers, but here's one that works anyway</p>
<pre><code>[x for x in a if x in b]
</code></pre>
| 30 | 2010-09-30T20:28:23Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 5,142,340 | <p>Also you can try this,by keeping common elements in a new list. </p>
<pre><code>new_list = []
for element in a:
if element in b:
new_list.append(element)
</code></pre>
| 5 | 2011-02-28T13:04:00Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 10,872,313 | <p>A quick performance test showing Lutz's solution is the best:</p>
<pre><code>import time
def speed_test(func):
def wrapper(*args, **kwargs):
t1 = time.time()
for x in xrange(5000):
results = func(*args, **kwargs)
t2 = time.time()
print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
return results
return wrapper
@speed_test
def compare_bitwise(x, y):
set_x = frozenset(x)
set_y = frozenset(y)
return set_x & set_y
@speed_test
def compare_listcomp(x, y):
return [i for i, j in zip(x, y) if i == j]
@speed_test
def compare_intersect(x, y):
return frozenset(x).intersection(y)
# Comparing short lists
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)
# Comparing longer lists
import random
a = random.sample(xrange(100000), 10000)
b = random.sample(xrange(100000), 10000)
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)
</code></pre>
<p>These are the results on my machine:</p>
<pre><code># Short list:
compare_bitwise took 10.145 ms
compare_listcomp took 11.157 ms
compare_intersect took 7.461 ms
# Long list:
compare_bitwise took 11203.709 ms
compare_listcomp took 17361.736 ms
compare_intersect took 6833.768 ms
</code></pre>
<p>Obviously, any artificial performance test should be taken with a grain of salt, but since the <code>set().intersection()</code> answer is <em>at least as fast</em> as the other solutions, and also the most readable, it should be the standard solution for this common problem.</p>
| 51 | 2012-06-03T17:12:23Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 34,631,617 | <p>You can use:</p>
<pre><code>a = [1, 3, 4, 5, 9, 6, 7, 8]
b = [1, 7, 0, 9]
same_values = set(a) & set(b)
print same_values
</code></pre>
<p>Output:</p>
<pre><code>set([1, 7, 9])
</code></pre>
| 0 | 2016-01-06T11:07:15Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 38,180,267 | <p>another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is:</p>
<pre><code>all(i == j for i, j in zip(lst1, lst2))
</code></pre>
| 0 | 2016-07-04T08:41:34Z | [
"python",
"list"
] |
How can I compare two lists in python and return matches | 1,388,818 | <p>I want to take two lists and find the values that appear in both.</p>
<pre><code>a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
</code></pre>
<p>would return <code>[5]</code>, for instance.</p>
| 168 | 2009-09-07T11:07:27Z | 38,181,023 | <p>Can use itertools.product too.</p>
<pre><code>>>> common_elements=[]
>>> for i in list(itertools.product(a,b)):
... if i[0] == i[1]:
... common_elements.append(i[0])
</code></pre>
| 0 | 2016-07-04T09:18:34Z | [
"python",
"list"
] |
how do I determine whether a python script is imported as module or run as script? | 1,389,044 | <p>The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? Is there a difference at all in python?</p>
<p>The problem is, that I want to evaluate the command line parameters only if run as a script, but not if the module is only imported to use it in another script. (I want to be able to use one script as both library and program.) I am afraid the vanilla way would be to build the lib and a second script that uses it, but I'd like to have a second option for small tool/libs. </p>
| 13 | 2009-09-07T11:58:18Z | 1,389,048 | <p>from python <a href="http://docs.python.org/dev/tutorial/modules.html#executing-modules-as-scripts">docs</a>:</p>
<blockquote>
<p>When you run a Python module with</p>
<p>python fibo.py </p>
<p>the code in the module will be
executed, just as if you imported it,
but with the <code>__name__</code> set to
<code>"__main__"</code>. That means that by adding
this code at the end of your module:</p>
</blockquote>
<pre><code>if __name__ == '__main__':
# Running as a script
</code></pre>
<p>you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the âmainâ file</p>
| 24 | 2009-09-07T11:59:19Z | [
"python",
"module"
] |
How can I tokenize this with a regex? | 1,389,062 | <p>Suppose I have strings like the following :</p>
<pre><code>OneTwo
ThreeFour
AnotherString
DVDPlayer
CDPlayer
</code></pre>
<p>I know how to tokenize the camel-case ones, except the "DVDPlayer" and "CDPlayer". I know I could tokenize them manually, but maybe you can show me a regex that can handle all the cases?</p>
<p>EDIT:
the expected tokens are :</p>
<pre><code>OneTwo -> One Two
...
CDPlayer -> CD Player
DVDPlayer -> DVD Player
</code></pre>
| 1 | 2009-09-07T12:02:18Z | 1,389,075 | <p>Try a non-greedy look ahead. A token would be one or more uppercase characters followed by zero or more lowercase characters. The token would terminate when the next two character are an upper case and lower case - matching this section is what the non-greedy matching can be used. This approach has limitation but it should work for the examples you provided.</p>
| 0 | 2009-09-07T12:05:41Z | [
"python",
"ruby",
"regex",
"tokenize",
"lexical-analysis"
] |
How can I tokenize this with a regex? | 1,389,062 | <p>Suppose I have strings like the following :</p>
<pre><code>OneTwo
ThreeFour
AnotherString
DVDPlayer
CDPlayer
</code></pre>
<p>I know how to tokenize the camel-case ones, except the "DVDPlayer" and "CDPlayer". I know I could tokenize them manually, but maybe you can show me a regex that can handle all the cases?</p>
<p>EDIT:
the expected tokens are :</p>
<pre><code>OneTwo -> One Two
...
CDPlayer -> CD Player
DVDPlayer -> DVD Player
</code></pre>
| 1 | 2009-09-07T12:02:18Z | 1,389,108 | <p>Look at my answer on the question, <a href="http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array/155487#155487" title=".NET - How can you split a âcapsâ delimited string into an array?">.NET - How can you split a âcapsâ delimited string into an array?</a>.</p>
<p>The regex looks like this:</p>
<pre><code>/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g
</code></pre>
<p>It can be modified slightly to allow searching for camel-cased tokens, by replacing the <code>$</code> with <code>\b</code>:</p>
<pre><code>/([A-Z]+(?=\b|[A-Z][a-z])|[A-Z]?[a-z]+)/g
</code></pre>
| 4 | 2009-09-07T12:12:33Z | [
"python",
"ruby",
"regex",
"tokenize",
"lexical-analysis"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.