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
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
<h1>Installing Mercurial on Mac OS X 10.6 Snow Leopard</h1> <p>I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:</p> <pre><code>cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install </code></pre> <p>This installs the site-packages files for Mercurial in <code>/usr/local/lib/python2.6/site-packages/</code>. I know that installing Mercurial from the Mac Disk Image will install the files into <code>/Library/Python/2.6/site-packages/</code>, which is the site-packages directory for the Mac OS X default Python install.</p> <p>I have Python 2.6.2+ installed as a Framework with its site-packages directory in:</p> <blockquote> <p>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</p> </blockquote> <p>With Mercurial installed this way, I have to issue:</p> <blockquote> <p>PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}"</p> </blockquote> <p>in order to get Mercurial to work.</p> <h3>Questions</h3> <ul> <li>How can I install Mercurial from source with the site-packages in a different directory?</li> <li>Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist?</li> <li>Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)?</li> </ul> <h3>Reasons for Installing from Source</h3> <p><a href="http://hivelogic.com/about" rel="nofollow">Dan Benjamin</a> of <a href="http://hivelogic.com/" rel="nofollow">Hivelogic</a> provides the benefits of and instructions for installing Mercurial from source in his article <a href="http://hivelogic.com/articles/compiling-mercurial-on-snow-leopard/" rel="nofollow">Installing Mercurial on Snow Leopard</a>.</p>
13
2009-09-22T17:13:09Z
1,490,705
<p>Install mercurial - or any Python package in general - into your user home directory. Thus you can access them from any Python (of same version) or any virtualenv. See <a href="http://www.python.org/dev/peps/pep-0370/" rel="nofollow">PEP 370</a> for details.</p> <pre><code>$ cd mercurial-x.y.z/ $ python2.6 setup.py install --user $ ~/.local/bin/hg ... </code></pre> <p>But why do you want to build mercurial manually? I use <a href="http://www.macports.org/" rel="nofollow">macports</a>.</p> <pre><code>$ sudo port install mercurial $ which hg /opt/local/bin/hg </code></pre> <p><strong>Update</strong>: Nowadays, I simply use <a href="http://docs.activestate.com/activepython/2.6/pypm.html" rel="nofollow">PyPM</a> to install mercurial into <code>~/.local/bin/hg</code>.</p>
7
2009-09-29T05:28:44Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
<h1>Installing Mercurial on Mac OS X 10.6 Snow Leopard</h1> <p>I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:</p> <pre><code>cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install </code></pre> <p>This installs the site-packages files for Mercurial in <code>/usr/local/lib/python2.6/site-packages/</code>. I know that installing Mercurial from the Mac Disk Image will install the files into <code>/Library/Python/2.6/site-packages/</code>, which is the site-packages directory for the Mac OS X default Python install.</p> <p>I have Python 2.6.2+ installed as a Framework with its site-packages directory in:</p> <blockquote> <p>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</p> </blockquote> <p>With Mercurial installed this way, I have to issue:</p> <blockquote> <p>PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}"</p> </blockquote> <p>in order to get Mercurial to work.</p> <h3>Questions</h3> <ul> <li>How can I install Mercurial from source with the site-packages in a different directory?</li> <li>Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist?</li> <li>Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)?</li> </ul> <h3>Reasons for Installing from Source</h3> <p><a href="http://hivelogic.com/about" rel="nofollow">Dan Benjamin</a> of <a href="http://hivelogic.com/" rel="nofollow">Hivelogic</a> provides the benefits of and instructions for installing Mercurial from source in his article <a href="http://hivelogic.com/articles/compiling-mercurial-on-snow-leopard/" rel="nofollow">Installing Mercurial on Snow Leopard</a>.</p>
13
2009-09-22T17:13:09Z
1,958,044
<p>as suggested by Sridhar, macports works fine on multiple architecture and versions of MacOsX + allows updates and more:</p> <pre><code>$ port variants mercurial mercurial has the variants: bash_completion: Completion support for bash zsh_completion: Install mercurial zsh completion file $ </code></pre> <p>so that you may use:</p> <pre><code>$ sudo port install mercurial +bash_completion ---&gt; Computing dependencies for mercurial ---&gt; Fetching mercurial ---&gt; Attempting to fetch mercurial-1.3.1.tar.gz from http://arn.se.distfiles.macports.org/python ---&gt; Attempting to fetch mercurial-1.3.1.tar.gz from http://www.selenic.com/mercurial/release/ ---&gt; Verifying checksum(s) for mercurial ---&gt; Extracting mercurial ---&gt; Configuring mercurial ---&gt; Building mercurial ---&gt; Staging mercurial into destroot ---&gt; Installing mercurial @1.3.1_0+bash_completion ---&gt; Activating mercurial @1.3.1_0+bash_completion ---&gt; Cleaning mercurial $ </code></pre>
5
2009-12-24T11:47:24Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
<h1>Installing Mercurial on Mac OS X 10.6 Snow Leopard</h1> <p>I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:</p> <pre><code>cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install </code></pre> <p>This installs the site-packages files for Mercurial in <code>/usr/local/lib/python2.6/site-packages/</code>. I know that installing Mercurial from the Mac Disk Image will install the files into <code>/Library/Python/2.6/site-packages/</code>, which is the site-packages directory for the Mac OS X default Python install.</p> <p>I have Python 2.6.2+ installed as a Framework with its site-packages directory in:</p> <blockquote> <p>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</p> </blockquote> <p>With Mercurial installed this way, I have to issue:</p> <blockquote> <p>PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}"</p> </blockquote> <p>in order to get Mercurial to work.</p> <h3>Questions</h3> <ul> <li>How can I install Mercurial from source with the site-packages in a different directory?</li> <li>Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist?</li> <li>Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)?</li> </ul> <h3>Reasons for Installing from Source</h3> <p><a href="http://hivelogic.com/about" rel="nofollow">Dan Benjamin</a> of <a href="http://hivelogic.com/" rel="nofollow">Hivelogic</a> provides the benefits of and instructions for installing Mercurial from source in his article <a href="http://hivelogic.com/articles/compiling-mercurial-on-snow-leopard/" rel="nofollow">Installing Mercurial on Snow Leopard</a>.</p>
13
2009-09-22T17:13:09Z
2,565,094
<p>Why need to use macports? python <code>easy_install</code> is the easiest way and error free:</p> <pre><code>easy_install -U mercurial </code></pre> <p><em>It's just a simple gold bullet, all the time.</em></p>
13
2010-04-02T05:11:21Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
<h1>Installing Mercurial on Mac OS X 10.6 Snow Leopard</h1> <p>I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:</p> <pre><code>cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install </code></pre> <p>This installs the site-packages files for Mercurial in <code>/usr/local/lib/python2.6/site-packages/</code>. I know that installing Mercurial from the Mac Disk Image will install the files into <code>/Library/Python/2.6/site-packages/</code>, which is the site-packages directory for the Mac OS X default Python install.</p> <p>I have Python 2.6.2+ installed as a Framework with its site-packages directory in:</p> <blockquote> <p>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</p> </blockquote> <p>With Mercurial installed this way, I have to issue:</p> <blockquote> <p>PYTHONPATH=/usr/local/lib/python2.6/site-packages:"${PYTHONPATH}"</p> </blockquote> <p>in order to get Mercurial to work.</p> <h3>Questions</h3> <ul> <li>How can I install Mercurial from source with the site-packages in a different directory?</li> <li>Is there an advantage or disadvantage to having the site-packages in the current location? Would it be better in one of the Python site-package directories that already exist?</li> <li>Do I need to be concerned about virtualenv working correctly since I have modified PYTHONPATH (or any other conflicts for that matter)?</li> </ul> <h3>Reasons for Installing from Source</h3> <p><a href="http://hivelogic.com/about" rel="nofollow">Dan Benjamin</a> of <a href="http://hivelogic.com/" rel="nofollow">Hivelogic</a> provides the benefits of and instructions for installing Mercurial from source in his article <a href="http://hivelogic.com/articles/compiling-mercurial-on-snow-leopard/" rel="nofollow">Installing Mercurial on Snow Leopard</a>.</p>
13
2009-09-22T17:13:09Z
2,762,342
<p>All those answers look complicated to the average mac OS X users, because they are specific to other install platforms. As of now the Mercurial website offers an installer package (compressed as a zip file).</p>
1
2010-05-04T01:52:07Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,461,413
<p>In python lists are objects :) So no type mismatch</p>
0
2009-09-22T17:20:34Z
[ "python", "return-value" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,461,415
<p>If you are going to be returning iterators sometimes, and single objects on others, I'd say return always an iterator, so you don't have to think about it. </p> <p>Generaly, you would use that function in a context that expects an iterator, so if you'd have to check if it where a list to iterate or an object to do just one time the work, then its easier to just return an iterator and iterate always, even if its one time.</p> <p>If you need to do something different if you are returned one element, just use <code>if len(var):</code>.</p> <p>Remember, consistency is a valuable good.</p> <p>I lean towards returning a consistent object, not necesarily the same type, but if I return ever an iterable, I return always an iterable.</p>
11
2009-09-22T17:21:40Z
[ "python", "return-value" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,461,697
<p>The only situation where I would do this is with a parameterized function or method, where one or more of the parameters the caller gives determines the type returned; for example, a "factory" function that returns one of a logically similar family of objects:</p> <pre><code>newCharacter = characterFactory("human", "male", "warrior") </code></pre> <p>In the general case, where the caller doesn't get to specify, I'd avoid the "box of chocolates" behavior. :)</p>
1
2009-09-22T18:10:56Z
[ "python", "return-value" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,461,847
<p>In general, I would have to say that returning two different types is bad practice.</p> <p>Imagine the next developer coming to read and maintain your code. At first he/she will read a method using your function and think "Ah, read() returns a single item." </p> <p>Later they will see code treating read()'s result as a list. At best this will simply confuse them and force them to examine read()'s usage. At worst they might think there is a bug in the implementation using read() and attempt to fix it.</p> <p>Finally, once they understand read() returns two possible types they will have to ask themselves "is there possibly a third return type I need to be ready for?"</p> <p>This reminds me of the saying: "Code as if the next guy to maintain your code is a homicidal maniac who knows where you live." </p>
2
2009-09-22T18:36:02Z
[ "python", "return-value" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,462,139
<p>It may not be a matter of "pythonic" but rather a matter of "good design". If you returnd different things <em>AND</em> nobody has to do typechecks on them, then it's probably okay. That's polymorphism for you. OTOH, if the caller has to "pierce the veil" then you have a design problem, known as a violation of the Liskov Substitution Principle. Pythonic or not, it is clearly not an OO design, which means it will be prone to bugs and programming inconveniences. </p>
1
2009-09-22T19:35:16Z
[ "python", "return-value" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,462,353
<p>I would have read(<em>integer</em>) and read_list(<em>iterable</em>).</p> <p>That way you could do read(10) and get back a single result and read_list([5, 5, 10, 5]) and get back a list of results. This is both more flexible and explicit.</p>
1
2009-09-22T20:21:38Z
[ "python", "return-value" ]
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
<p>(Title and contents updated after reading Alex's answer)</p> <p>In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.</p> <p>For example <code>struct.unpack</code> always returns a tuple even if it contains only one item.</p> <p>I'm trying to finalise the API for a module and I have a few functions that can take one or more parameters (via <code>*args</code>) like this:</p> <pre><code>a = s.read(10) # reads 10 bits and returns a single item b, c = s.read(5, 5) # reads 5 bits twice and returns a list of two items. </code></pre> <p>So it returns a single item if there's only one parameter, otherwise it returns a list. Now I think this is fine and not at all confusing, but I suspect that others may disagree.</p> <p>The most common use-case for these functions would be to only want a single item returned, so always returning a list (or tuple) feels wrong: </p> <pre><code>a, = s.read(10) # Prone to bugs when people forget to unpack the object a = s.read(10)[0] # Ugly and it's not clear only one item is being returned </code></pre> <p>Another option is to have two functions:</p> <pre><code>a = s.read(10) b, c = s.read_list(5, 5) </code></pre> <p>which is OK, but it clutters up the API and requires the user to remember twice as many functions without adding any value.</p> <p><strong>So my question is:</strong> Is sometimes returning an iterable and sometimes a single item confusing and un-Pythonic? If so what's the best option?</p> <p><hr /></p> <p><strong>Update</strong>: I think the general consensus is that it's very naughty to only return an iterable sometimes. I think that the best option for most cases would be to always return the iterable, even if it contained only one item.</p> <p>Having said that, for my particular case I think I'll go for the splitting into two functions (<code>read(item)</code> / <code>readlist(*items)</code>), the reasoning being that I think the single item case will happen much more often than the multiple item case, so it makes it easier to use and the API change less problematic for users.</p> <p>Thanks everyone.</p>
6
2009-09-22T17:16:57Z
1,463,749
<p>Returning either a single object, or an iterable of objects, depending on arguments, is definitely hard to deal with. But the question in your title is much more general and the assertion that the standard library's function avoid (or "mostly avoid") returning different types based on the argument(s) is quite incorrect. There are many counter-examples.</p> <p>Functions <code>copy.copy</code> and <code>copy.deepcopy</code> return the same type as their argument, so of course they're "returning different types depending on" the argument. "Return same type as the input" is actually VERY common -- you could class here, also, the "fetch an object back from a container where it was put", though normally that's done with a method rather than a function;-). But also, in the same vein, consider <code>itertools.repeat</code> (once you iterate on its returned iterator), or, say, <code>filter</code>...:</p> <pre><code>&gt;&gt;&gt; filter(lambda x: x&gt;'f', 'zaplepidop') 'zplpiop' &gt;&gt;&gt; filter(lambda x: x&gt;'f', list('zaplepidop')) ['z', 'p', 'l', 'p', 'i', 'o', 'p'] </code></pre> <p>filtering a string returns a string, filtering a list returns a list. </p> <p>But wait, there's more!-) Functions <code>pickle.loads</code> and its friends (e.g. in module <code>marshal</code> &amp;c) return objects of types <em>entirely</em> dependent on the value you're passing as an argument. So does built-in function <code>eval</code> (and similarly <code>input</code>, in Python 2.*). This is the second common pattern: construct or reconstruct an object as dictated by the value of the argument(s), of a wide (or even ubbounded) variety of possible types, and return it.</p> <p>I know no good example of the specific anti-pattern you've observed (and I do believe it's an anti-pattern, mildly -- not for any high-falutin' reason, just because it's pesky and inconvenient to deal with;-). Note that these cases I have exemplified ARE handy and convenient -- that's the real design discriminant in most standard library issue!-)</p>
2
2009-09-23T03:00:41Z
[ "python", "return-value" ]
Jinja2 If Statement
1,461,484
<p>The code below is a sample form I'm using to learn jinja2. As written, it returns an error saying that it doesn't recognize the {% endif %} tag. Why does this happen?</p> <pre><code>&lt;html&gt; Name: {{ name }} Print {{ num }} times Color: {{ color }} {% if convert_to_upper %}Case: Upper {% elif not convert_to_upper %}Case: Lower{% endif %} {% for repeats in range(0,num) %} {% if convert_to_upper %} {% filter upper %} {% endif %} &lt;li&gt;&lt;p style="color:{{ color }}"&gt;{{ name }}&lt;/style&gt;&lt;/li&gt; {% endfilter %} {% endfor %} &lt;/html&gt; </code></pre>
7
2009-09-22T17:34:57Z
1,461,505
<p>I think you have your lines mixed up. Your <code>endif</code> comese before <code>endfilter</code> whereas <code>if</code> is before <code>filter</code>. That's just a syntax error.</p>
10
2009-09-22T17:39:19Z
[ "python", "jinja2" ]
Command line options with optional arguments in Python
1,461,942
<p>I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:</p> <pre><code>&gt; script.py --foo &gt; script.py --foo=bar </code></pre> <p>From the Python getopt docs it seems I have to choose one or the other.</p>
4
2009-09-22T18:53:11Z
1,462,032
<p>Also, note that the standard library also has <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a>, a more powerful options parser.</p>
3
2009-09-22T19:12:52Z
[ "python", "getopt" ]
Command line options with optional arguments in Python
1,461,942
<p>I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:</p> <pre><code>&gt; script.py --foo &gt; script.py --foo=bar </code></pre> <p>From the Python getopt docs it seems I have to choose one or the other.</p>
4
2009-09-22T18:53:11Z
1,462,034
<p>Use the <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> package. </p>
1
2009-09-22T19:13:32Z
[ "python", "getopt" ]
Command line options with optional arguments in Python
1,461,942
<p>I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:</p> <pre><code>&gt; script.py --foo &gt; script.py --foo=bar </code></pre> <p>From the Python getopt docs it seems I have to choose one or the other.</p>
4
2009-09-22T18:53:11Z
1,462,035
<p>check out argparse: <a href="http://code.google.com/p/argparse/" rel="nofollow">http://code.google.com/p/argparse/</a></p> <p>especially the 'nargs' option</p>
3
2009-09-22T19:13:41Z
[ "python", "getopt" ]
Command line options with optional arguments in Python
1,461,942
<p>I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:</p> <pre><code>&gt; script.py --foo &gt; script.py --foo=bar </code></pre> <p>From the Python getopt docs it seems I have to choose one or the other.</p>
4
2009-09-22T18:53:11Z
1,462,046
<p>There isn't an option in optparse that allows you to do this. But you can extend it to do it:</p> <p><a href="http://docs.python.org/library/optparse.html#adding-new-actions" rel="nofollow">http://docs.python.org/library/optparse.html#adding-new-actions</a></p>
2
2009-09-22T19:15:23Z
[ "python", "getopt" ]
Command line options with optional arguments in Python
1,461,942
<p>I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:</p> <pre><code>&gt; script.py --foo &gt; script.py --foo=bar </code></pre> <p>From the Python getopt docs it seems I have to choose one or the other.</p>
4
2009-09-22T18:53:11Z
1,462,395
<p><code>optparse</code> module from stdlib doesn't support it out of the box (and it shouldn't due to it is a bad practice to use command-line options in such way).</p> <p>As <a href="http://stackoverflow.com/questions/1461942/command-line-options-with-optional-arguments-in-python/1462035#1462035">@Kevin Horn pointed out</a> you can use <code>argparse</code> module (installable via <code>easy_install argparse</code> or just grab <a href="http://argparse.googlecode.com/svn/tags/r101/argparse.py" rel="nofollow">argparse.py</a> and put it anywhere in your <code>sys.path</code>).</p> <h3>Example</h3> <pre><code>#!/usr/bin/env python from argparse import ArgumentParser if __name__ == "__main__": parser = ArgumentParser(prog='script.py') parser.add_argument('--foo', nargs='?', metavar='bar', default='baz') parser.print_usage() for args in ([], ['--foo'], ['--foo', 'bar']): print "$ %s %s -&gt; foo=%s" % ( parser.prog, ' '.join(args).ljust(9), parser.parse_args(args).foo) </code></pre> <h3>Output</h3> <pre> usage: script.py [-h] [--foo [bar]] $ script.py -> foo=baz $ script.py --foo -> foo=None $ script.py --foo bar -> foo=bar </pre>
3
2009-09-22T20:28:59Z
[ "python", "getopt" ]
Django forms: how to display media (javascript) for a DateTimeInput widget?
1,462,003
<p>Hello (please excuse me for my bad english ;) ),</p> <p>Imagine the classes bellow:</p> <p><strong>models.py</strong></p> <pre><code>from django import models class MyModel(models.Model): content_type = models.ForeignKey(ContentType, verbose_name=_('content type')) object_id = models.PositiveIntegerField(_('object id')) content_object = generic.GenericForeignKey('content_type', 'object_id') published_at = models.DateTimeField() </code></pre> <p><strong>forms.py</strong></p> <pre><code>from django import forms class MyModelForm(forms.ModelForm): published_at = forms.DateTimeField(required=False, widget=DateTimeInput) </code></pre> <p><strong>admin.py</strong></p> <pre><code>from django.contrib import admin form django.contrib.contenttypes import generic class MyModelInline(generic.GenericStackedInline): model = MyModel form = MyModelForm class MyModelAdmin(admin.ModelAdmin): inlines = [MyModelInline] </code></pre> <p><strong>Problem</strong>: the <code>&lt;script&gt;</code> tags for javascript from the DateTimeInput widget don't appear in the admin site (adding a new MyModel object). i.e. these two lines :</p> <pre><code>&lt;script type="text/javascript" src="/admin/media/js/calendar.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/admin/media/js/admin/DateTimeShortcuts.js"&gt;&lt;/script&gt; </code></pre> <p>Please, do you have any idea to fix it ?</p> <p>Thank you very much and have a good day :)</p>
1
2009-09-22T19:06:13Z
1,462,285
<p>The standard DateTimeWidget doesn't include any javascript. The widget used in the admin is a different one - <code>django.contrib.admin.widgets.AdminSplitDateTime</code> - and this includes the javascript.</p>
5
2009-09-22T20:05:22Z
[ "python", "django", "django-models", "django-admin", "django-forms" ]
How much data could be stored into a Google App Engine, application?
1,462,160
<p>Answering <a href="http://stackoverflow.com/questions/1462055/is-it-correct-that-developers-have-read-only-access-to-the-filesystem-on-app-eng">this question</a> and searching for references I have this doubt my self:</p> <p>*How much data could be stored into a Google App Engine, application?</p> <p>If I'm reading well <a href="http://code.google.com/appengine/docs/quotas.html#Datastore" rel="nofollow">this</a> table:</p> <pre> Resources | Free daily | Free Max Rate | Daily Billing enable | Max Rate Billing ------------------------------------------------------------------------------------------ Stored Data | 1 gigabyte | None | 1 gigabytes free; no maximum | None </pre> <p>Does it means you can storage as much as you want for free ( as long as it is 1 gb daily? ) </p> <p>:-o </p> <p><strong>EDIT</strong></p> <p>Mmhh I was wrong. </p> <p>I have found also the official link that answer my own question:</p> <p><a href="http://code.google.com/appengine/docs/billing.html" rel="nofollow">http://code.google.com/appengine/docs/billing.html</a></p> <pre> Resource | Unit | Unit cost ------------------------------------------------- Outgoing Bandwidth | gigabytes | $0.12 ------------------------------------------------- Incoming Bandwidth | gigabytes | $0.10 ------------------------------------------------- CPU Time | CPU hours | $0.10 ------------------------------------------------- Stored Data | gigabytes per month | $0.15 ------------------------------------------------- Recipients Emailed | recipients | $0.0001 </pre> <p>So, using 7.6 gb of storage wouldcost $1 USD/month :-o Still, very cheap. Am I missing something?</p>
4
2009-09-22T19:38:49Z
1,462,234
<p>I read that to mean 1 GB stored during the course of a day, not added in a day, so in other words you can have up to 1 GB of storage for free. If you store more, calculated daily, you have to pay for that additional storage. There is no maximum on how much you can store, you just get billed for it.</p>
6
2009-09-22T19:53:44Z
[ "java", "python", "google-app-engine", "cloud" ]
How to improve performance of python cgi that reads a big file and returns it as a download?
1,462,330
<p>I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download.</p> <p>It works,but performance sucks. The bottleneck seems to be reading this huge file over and over:</p> <pre><code>def download_demo(): """ Returns the demo file """ file = open(FILENAME, 'r') buff = file.read() print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre> <p>How can I make this faster? I thought of using a ram disk to keep the file, but there must be some better solution. Would using <code>mod_wsgi</code> instead of a cgi script help? Would I be able to keep the big file in apache's memory space?</p> <p>Any help is greatly appreciated.</p>
2
2009-09-22T20:17:00Z
1,462,367
<p>Try reading and outputting (i.e. buffering) a chunk of say 16KB at a time. Probably Python is doing something slow behind the scenes and manually buffering may be faster.</p> <p>You shouldn't have to use e.g. a ramdisk - the OS disk cache ought to cache the file contents for you.</p>
1
2009-09-22T20:24:06Z
[ "python", "cgi", "performance", "mod-wsgi" ]
How to improve performance of python cgi that reads a big file and returns it as a download?
1,462,330
<p>I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download.</p> <p>It works,but performance sucks. The bottleneck seems to be reading this huge file over and over:</p> <pre><code>def download_demo(): """ Returns the demo file """ file = open(FILENAME, 'r') buff = file.read() print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre> <p>How can I make this faster? I thought of using a ram disk to keep the file, but there must be some better solution. Would using <code>mod_wsgi</code> instead of a cgi script help? Would I be able to keep the big file in apache's memory space?</p> <p>Any help is greatly appreciated.</p>
2
2009-09-22T20:17:00Z
1,462,369
<p>mod_wsgi or FastCGI would help in the sense that you don't need to reload the Python interpreter every time your script is run. However, they'd do little to improve the performance of reading the file (if that's what's really your bottleneck). I'd advise you to use something along the lines of memcached instead.</p>
1
2009-09-22T20:24:12Z
[ "python", "cgi", "performance", "mod-wsgi" ]
How to improve performance of python cgi that reads a big file and returns it as a download?
1,462,330
<p>I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download.</p> <p>It works,but performance sucks. The bottleneck seems to be reading this huge file over and over:</p> <pre><code>def download_demo(): """ Returns the demo file """ file = open(FILENAME, 'r') buff = file.read() print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre> <p>How can I make this faster? I thought of using a ram disk to keep the file, but there must be some better solution. Would using <code>mod_wsgi</code> instead of a cgi script help? Would I be able to keep the big file in apache's memory space?</p> <p>Any help is greatly appreciated.</p>
2
2009-09-22T20:17:00Z
1,462,374
<p>Why are you printing is all in one print statement? Python has to generate several temporary strings to handle the content headers and because of that last %s, it has to hold the entire contents of the file in two different string vars. This should be better.</p> <pre><code>print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n" % (os.path.split(FILENAME)[-1], len(buff)) print buff </code></pre> <p>You might also consider reading the file using the raw IO module so Python doesn't create temp buffers that you aren't using.</p>
2
2009-09-22T20:25:07Z
[ "python", "cgi", "performance", "mod-wsgi" ]
How to improve performance of python cgi that reads a big file and returns it as a download?
1,462,330
<p>I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download.</p> <p>It works,but performance sucks. The bottleneck seems to be reading this huge file over and over:</p> <pre><code>def download_demo(): """ Returns the demo file """ file = open(FILENAME, 'r') buff = file.read() print "Content-Type:application/x-download\nContent-Disposition:attachment;filename=%s\nContent-Length:%s\n\n%s" % (os.path.split(FILENAME)[-1], len(buff), buff) </code></pre> <p>How can I make this faster? I thought of using a ram disk to keep the file, but there must be some better solution. Would using <code>mod_wsgi</code> instead of a cgi script help? Would I be able to keep the big file in apache's memory space?</p> <p>Any help is greatly appreciated.</p>
2
2009-09-22T20:17:00Z
1,463,235
<p>Use mod_wsgi and use something akin to:</p> <pre><code>def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) file = open('/usr/share/dict/words', 'rb') return environ['wsgi.file_wrapper'](file) </code></pre> <p>In other words, use wsgi.file_wrapper extension of WSGI standard to allow Apache/mod_wsgi to perform optimised reply of file contents using sendfile/mmap. In other words, avoids your application even needing to read file into memory.</p>
9
2009-09-22T23:53:29Z
[ "python", "cgi", "performance", "mod-wsgi" ]
Can Python's MiniMock create mock of functions defined in the same file?
1,462,381
<p>I'm using the Python <a href="http://pypi.python.org/pypi/MiniMock" rel="nofollow">MiniMock</a> library for unit testing. I'd like to mock out a function defined in the same Python file as my doctest. Can MiniMock handle that? The naive approach fails: </p> <pre><code>def foo(): raise ValueError, "Don't call me during testing!" def bar(): """ Returns twice the value of foo() &gt;&gt;&gt; from minimock import mock &gt;&gt;&gt; mock('foo',returns=5) &gt;&gt;&gt; bar() Called foo() 10 """ return foo() * 2 if __name__ == "__main__": import doctest doctest.testmod() </code></pre> <p>Here's what happens if I try to run this code: </p> <pre><code>********************************************************************** File "test.py", line 9, in __main__.bar Failed example: bar() Exception raised: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/doctest.py", line 1212, in __run compileflags, 1) in test.globs File "&lt;doctest __main__.bar[2]&gt;", line 1, in &lt;module&gt; bar() File "test.py", line 13, in bar return foo() * 2 File "test.py", line 2, in foo raise ValueError, "Don't call me!" ValueError: Don't call me! ********************************************************************** 1 items had failures: 1 of 3 in __main__.bar ***Test Failed*** 1 failures. </code></pre> <p><strong>Edit:</strong> As per the answers below, this has been identified as a bug, and has been <a href="http://bitbucket.org/jab/minimock/changeset/bb9528bb454d/" rel="nofollow">fixed in MiniMock</a>. </p>
3
2009-09-22T20:25:39Z
1,462,434
<p>This works:</p> <pre><code>def foo(): raise ValueError, "Don't call me during testing!" def bar(): """ Returns twice the value of foo() &gt;&gt;&gt; from minimock import mock &gt;&gt;&gt; mock('foo',returns=5) &gt;&gt;&gt; bar.func_globals['foo'] = foo &gt;&gt;&gt; bar() Called foo() 10 """ return foo() * 2 if __name__ == "__main__": import doctest doctest.testmod() </code></pre> <p>It seems that the foo in bar is already bound to the original function by the time the mocking takes place.</p> <p>This happens because when running the doctests, the doctest module <a href="http://docs.python.org/library/doctest.html#what-s-the-execution-context" rel="nofollow">runs in the context of a <em>copy</em> of the module's global name space</a>, but <code>bar</code>'s globals remain their original self. So the <code>mock</code> function changes the <code>foo</code> that is in the copied namespace, but <code>bar</code> is still looking at the original.</p> <p>I don't know if there's a better way to do this.</p> <p><strong>EDIT 2</strong>: I take it back. MiniMock was specifically designed to be used in doctests. I suspect you found a bug.</p> <p><strike><strong>EDIT</strong>: I guess the recommended way to do this is to set up the mocking before starting the tests, like so:</p> <pre><code>def foo(): raise ValueError, "Don't call me during testing!" def bar(): """ Returns twice the value of foo() &gt;&gt;&gt; bar() 10 """ return foo() * 2 if __name__ == "__main__": from minimock import mock mock('foo',returns=5) import doctest doctest.testmod() </code></pre> <p>This way the "Called foo()" message is also not in the doctest.</strike></p>
1
2009-09-22T20:35:02Z
[ "python", "mocking" ]
Can Python's MiniMock create mock of functions defined in the same file?
1,462,381
<p>I'm using the Python <a href="http://pypi.python.org/pypi/MiniMock" rel="nofollow">MiniMock</a> library for unit testing. I'd like to mock out a function defined in the same Python file as my doctest. Can MiniMock handle that? The naive approach fails: </p> <pre><code>def foo(): raise ValueError, "Don't call me during testing!" def bar(): """ Returns twice the value of foo() &gt;&gt;&gt; from minimock import mock &gt;&gt;&gt; mock('foo',returns=5) &gt;&gt;&gt; bar() Called foo() 10 """ return foo() * 2 if __name__ == "__main__": import doctest doctest.testmod() </code></pre> <p>Here's what happens if I try to run this code: </p> <pre><code>********************************************************************** File "test.py", line 9, in __main__.bar Failed example: bar() Exception raised: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/doctest.py", line 1212, in __run compileflags, 1) in test.globs File "&lt;doctest __main__.bar[2]&gt;", line 1, in &lt;module&gt; bar() File "test.py", line 13, in bar return foo() * 2 File "test.py", line 2, in foo raise ValueError, "Don't call me!" ValueError: Don't call me! ********************************************************************** 1 items had failures: 1 of 3 in __main__.bar ***Test Failed*** 1 failures. </code></pre> <p><strong>Edit:</strong> As per the answers below, this has been identified as a bug, and has been <a href="http://bitbucket.org/jab/minimock/changeset/bb9528bb454d/" rel="nofollow">fixed in MiniMock</a>. </p>
3
2009-09-22T20:25:39Z
1,474,440
<p>I just replied on the mailing list with a MiniMock patch that fixes this.</p> <p>Until that's applied, instead of the following two lines in itsadok's snippet:</p> <pre><code>&gt;&gt;&gt; mock('foo',returns=5) &gt;&gt;&gt; bar.func_globals['foo'] = foo </code></pre> <p>you could also use</p> <pre><code>&gt;&gt;&gt; mock('foo', nsdicts=(bar.func_globals,), returns=5) </code></pre>
5
2009-09-24T22:10:31Z
[ "python", "mocking" ]
Automatic String to Number conversion in Python
1,462,427
<p>I am trying to compare two lists of string in python. Some of the strings are numbers however I don't want to use it as number, only for string comparison.</p> <p>I read the string from a file and put them on a list like this:</p> <pre><code>def main(): inputFileName = 'BateCarteira.csv' inputFile = open(inputFileName, "r") bankNumbers = [] for line in inputFile: values = line[0:len(line)-1].split(';'); if (len(values[0]) &gt; 3): bankNumbers.append(''+values[0]) </code></pre> <p>However, when I try to print the number, it prints like:</p> <p>1,20091E+11</p> <p>The code for the printing:</p> <pre><code> print 'not in the list: ' + bankNumber outputFile.write(bankNumber + '-') </code></pre> <p>What can I do so python never casts the string to an int?</p> <p>sorry for my english :D</p>
1
2009-09-22T20:34:07Z
1,462,475
<p>Python never transforms a string to a number, unless you try something like:</p> <pre><code>s = "1.2" a = float(s) </code></pre> <p>So I guess that your .csv file has the string "1,20091E+11" inside it. Also notice that the decimal point is a coma. So, if you tried to convert it to a float, the transformation would fail.</p>
3
2009-09-22T20:43:09Z
[ "python", "casting" ]
Automatic String to Number conversion in Python
1,462,427
<p>I am trying to compare two lists of string in python. Some of the strings are numbers however I don't want to use it as number, only for string comparison.</p> <p>I read the string from a file and put them on a list like this:</p> <pre><code>def main(): inputFileName = 'BateCarteira.csv' inputFile = open(inputFileName, "r") bankNumbers = [] for line in inputFile: values = line[0:len(line)-1].split(';'); if (len(values[0]) &gt; 3): bankNumbers.append(''+values[0]) </code></pre> <p>However, when I try to print the number, it prints like:</p> <p>1,20091E+11</p> <p>The code for the printing:</p> <pre><code> print 'not in the list: ' + bankNumber outputFile.write(bankNumber + '-') </code></pre> <p>What can I do so python never casts the string to an int?</p> <p>sorry for my english :D</p>
1
2009-09-22T20:34:07Z
1,462,742
<p>You need the locale module to read numbers in the locale format (i.e with decimal comma that's used in (most) parts of Europe).</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, '') f = locale.atof("1,20091E+11") </code></pre>
2
2009-09-22T21:31:23Z
[ "python", "casting" ]
Do I need multiple cursor objects to loop over a recordset and update at the same time?
1,462,511
<p>So I've got a large database that I can't hold in memory at once. I've got to loop over every item in a table, process it, and put the processed data into another column in the table.</p> <p>While I'm looping over my cursor, if I try to run an update statement it truncates the recordset (I believe because it's re-purposing the cursor object).</p> <p><strong>Questions:</strong></p> <p>Will creating a second cursor object to run the update statements allow me to continue looping over the original select statement?</p> <p>Do I need a second connection to the database in order to have a second cursor object, that will allow me do do this?</p> <p>How would sqlite respond to having two connections to the database, one reading from the table, the other writing to it?</p> <p><strong>My code (simplified):</strong></p> <pre><code>import sqlite3 class DataManager(): """ Manages database (used below). I cut this class way down to avoid confusion in the question. """ def __init__(self, db_path): self.connection = sqlite3.connect(db_path) self.connection.text_factory = str self.cursor = self.connection.cursor() def genRecordset(self, str_sql, subs=tuple()): """ Generate records as tuples, for str_sql. """ self.cursor.execute(str_sql, subs) for row in self.cursor: yield row select = """ SELECT id, unprocessed_content FROM data_table WHERE processed_content IS NULL """ update = """ UPDATE data_table SET processed_content = ? WHERE id = ? """ data_manager = DataManager(r'C:\myDatabase.db') subs = [] for row in data_manager.genRecordset(str_sql): id, unprocessed_content = row processed_content = processContent(unprocessed_content) subs.append((processed_content, id)) #every n records update the database (whenever I run out of memory) if len(subs) &gt;= 1000: data_manager.cursor.executemany(update, subs) data_manager.connection.commit() subs = [] #update remaining records if subs: data_manager.cursor.executemany(update, subs) data_manager.connection.commit() </code></pre> <p>The other method I tried was to modify my select statement to be:</p> <pre><code>select = """ SELECT id, unprocessed_content FROM data_table WHERE processed_content IS NULL LIMIT 1000 """ </code></pre> <p>Then I would do:</p> <pre><code>recordset = data_manager.cursor.execute(select) while recordset: #do update stuff... recordset = data_manager.cursor.execute(select) </code></pre> <p>The problem I had with this was that my <em>real</em> select statement has a JOIN in it and takes a while, so executing the JOIN that many times is very time intensive. I'm trying to speed up the process by only doing the select once, then using a generator so I don't have to hold it all in memory.</p> <p><strong>Solution:</strong></p> <p>Ok, so the answer to my first two questions is "No." To my third question, once a connection is made to a database, it locks the entire database, so another connection won't be able to do anything until the first connection is closed. </p> <p>I couldn't find the source code for it, but from empirical evidence I believe that a connection can only use one cursor object at a time and the last run query takes precedence. This means that, while I'm looping over the selected recordset yielding one row at a time, as soon as I run my first update statement my generator stops yielding rows.</p> <p>My solution is to create a temporary database that I stick the processed_content in with the id, so that I have one connection/cursor object per database and can continue looping over the selected recordset, while inserting into the temporary database periodically. Once I reach the end of my selected recordset I transfer the data in the temporary database back to the original.</p> <p>If anyone knows for sure about the connection/cursor objects, let me know in a comment.</p>
10
2009-09-22T20:48:01Z
1,462,554
<p>Cursors are bad bad bad for a multitude of reasons.</p> <p>I'd suggest (and a lot of others will definitely chime in) that you use a single UPDATE statement instead of going the CURSOR route.</p> <p>Can your Processed_Content be sent as a parameter to a single query that does set based operations like so:</p> <pre><code>UPDATE data_table SET processed_content = ? WHERE processed_content IS NULL LIMIT 1000 </code></pre> <p><strong>Edited based on responses:</strong></p> <p>Since every row has a unique value for Processed_Content, you have no option but to use a recordset and a loop. I have done this in the past on multiple occasions. What you are suggesting should work effectively.</p>
1
2009-09-22T20:55:13Z
[ "python", "database", "sqlite", "sqlite3", "cursor" ]
Do I need multiple cursor objects to loop over a recordset and update at the same time?
1,462,511
<p>So I've got a large database that I can't hold in memory at once. I've got to loop over every item in a table, process it, and put the processed data into another column in the table.</p> <p>While I'm looping over my cursor, if I try to run an update statement it truncates the recordset (I believe because it's re-purposing the cursor object).</p> <p><strong>Questions:</strong></p> <p>Will creating a second cursor object to run the update statements allow me to continue looping over the original select statement?</p> <p>Do I need a second connection to the database in order to have a second cursor object, that will allow me do do this?</p> <p>How would sqlite respond to having two connections to the database, one reading from the table, the other writing to it?</p> <p><strong>My code (simplified):</strong></p> <pre><code>import sqlite3 class DataManager(): """ Manages database (used below). I cut this class way down to avoid confusion in the question. """ def __init__(self, db_path): self.connection = sqlite3.connect(db_path) self.connection.text_factory = str self.cursor = self.connection.cursor() def genRecordset(self, str_sql, subs=tuple()): """ Generate records as tuples, for str_sql. """ self.cursor.execute(str_sql, subs) for row in self.cursor: yield row select = """ SELECT id, unprocessed_content FROM data_table WHERE processed_content IS NULL """ update = """ UPDATE data_table SET processed_content = ? WHERE id = ? """ data_manager = DataManager(r'C:\myDatabase.db') subs = [] for row in data_manager.genRecordset(str_sql): id, unprocessed_content = row processed_content = processContent(unprocessed_content) subs.append((processed_content, id)) #every n records update the database (whenever I run out of memory) if len(subs) &gt;= 1000: data_manager.cursor.executemany(update, subs) data_manager.connection.commit() subs = [] #update remaining records if subs: data_manager.cursor.executemany(update, subs) data_manager.connection.commit() </code></pre> <p>The other method I tried was to modify my select statement to be:</p> <pre><code>select = """ SELECT id, unprocessed_content FROM data_table WHERE processed_content IS NULL LIMIT 1000 """ </code></pre> <p>Then I would do:</p> <pre><code>recordset = data_manager.cursor.execute(select) while recordset: #do update stuff... recordset = data_manager.cursor.execute(select) </code></pre> <p>The problem I had with this was that my <em>real</em> select statement has a JOIN in it and takes a while, so executing the JOIN that many times is very time intensive. I'm trying to speed up the process by only doing the select once, then using a generator so I don't have to hold it all in memory.</p> <p><strong>Solution:</strong></p> <p>Ok, so the answer to my first two questions is "No." To my third question, once a connection is made to a database, it locks the entire database, so another connection won't be able to do anything until the first connection is closed. </p> <p>I couldn't find the source code for it, but from empirical evidence I believe that a connection can only use one cursor object at a time and the last run query takes precedence. This means that, while I'm looping over the selected recordset yielding one row at a time, as soon as I run my first update statement my generator stops yielding rows.</p> <p>My solution is to create a temporary database that I stick the processed_content in with the id, so that I have one connection/cursor object per database and can continue looping over the selected recordset, while inserting into the temporary database periodically. Once I reach the end of my selected recordset I transfer the data in the temporary database back to the original.</p> <p>If anyone knows for sure about the connection/cursor objects, let me know in a comment.</p>
10
2009-09-22T20:48:01Z
1,463,922
<p>I think you have roughly the right architecture -- presenting it in terms of "cursors" WILL confuse the "old SQL hands", because they'll be thinking of the many issues connected with <code>DECLARE foo CURSOR</code>, <code>FETCH FROM CURSOR</code>, <code>WHERE CURRENT OF CURSOR</code>, and other such beauts having to do with <strong>SQL</strong> cursors. Python DB API's "cursor" is simply a convenient way to package and execute SQL statements, <strong>not</strong> necessarily connected with <strong>SQL</strong> cursors -- it won't suffer from any of those problems -- though it may present its (completely original) own ones;-) But, with the "batching" of results you're doing, your proper commits, etc, you have preventively finessed most of those "original problems" I had in mind.</p> <p>On some other engines I'd suggest doing first a select into a temporary table, then reading from that temporary table while updating the primary one, but I'm uncertain how the performance would be affected in sqlite, depending on what indices you have (if no index is affected by your update, then I suspect that such a temporary table would not be an optimization at all in sqlite -- but I can't run benchmarks on your data, the only real way to check performance hypotheses).</p> <p>So, I'd say, go for it!-)</p>
3
2009-09-23T04:16:26Z
[ "python", "database", "sqlite", "sqlite3", "cursor" ]
Do I need multiple cursor objects to loop over a recordset and update at the same time?
1,462,511
<p>So I've got a large database that I can't hold in memory at once. I've got to loop over every item in a table, process it, and put the processed data into another column in the table.</p> <p>While I'm looping over my cursor, if I try to run an update statement it truncates the recordset (I believe because it's re-purposing the cursor object).</p> <p><strong>Questions:</strong></p> <p>Will creating a second cursor object to run the update statements allow me to continue looping over the original select statement?</p> <p>Do I need a second connection to the database in order to have a second cursor object, that will allow me do do this?</p> <p>How would sqlite respond to having two connections to the database, one reading from the table, the other writing to it?</p> <p><strong>My code (simplified):</strong></p> <pre><code>import sqlite3 class DataManager(): """ Manages database (used below). I cut this class way down to avoid confusion in the question. """ def __init__(self, db_path): self.connection = sqlite3.connect(db_path) self.connection.text_factory = str self.cursor = self.connection.cursor() def genRecordset(self, str_sql, subs=tuple()): """ Generate records as tuples, for str_sql. """ self.cursor.execute(str_sql, subs) for row in self.cursor: yield row select = """ SELECT id, unprocessed_content FROM data_table WHERE processed_content IS NULL """ update = """ UPDATE data_table SET processed_content = ? WHERE id = ? """ data_manager = DataManager(r'C:\myDatabase.db') subs = [] for row in data_manager.genRecordset(str_sql): id, unprocessed_content = row processed_content = processContent(unprocessed_content) subs.append((processed_content, id)) #every n records update the database (whenever I run out of memory) if len(subs) &gt;= 1000: data_manager.cursor.executemany(update, subs) data_manager.connection.commit() subs = [] #update remaining records if subs: data_manager.cursor.executemany(update, subs) data_manager.connection.commit() </code></pre> <p>The other method I tried was to modify my select statement to be:</p> <pre><code>select = """ SELECT id, unprocessed_content FROM data_table WHERE processed_content IS NULL LIMIT 1000 """ </code></pre> <p>Then I would do:</p> <pre><code>recordset = data_manager.cursor.execute(select) while recordset: #do update stuff... recordset = data_manager.cursor.execute(select) </code></pre> <p>The problem I had with this was that my <em>real</em> select statement has a JOIN in it and takes a while, so executing the JOIN that many times is very time intensive. I'm trying to speed up the process by only doing the select once, then using a generator so I don't have to hold it all in memory.</p> <p><strong>Solution:</strong></p> <p>Ok, so the answer to my first two questions is "No." To my third question, once a connection is made to a database, it locks the entire database, so another connection won't be able to do anything until the first connection is closed. </p> <p>I couldn't find the source code for it, but from empirical evidence I believe that a connection can only use one cursor object at a time and the last run query takes precedence. This means that, while I'm looping over the selected recordset yielding one row at a time, as soon as I run my first update statement my generator stops yielding rows.</p> <p>My solution is to create a temporary database that I stick the processed_content in with the id, so that I have one connection/cursor object per database and can continue looping over the selected recordset, while inserting into the temporary database periodically. Once I reach the end of my selected recordset I transfer the data in the temporary database back to the original.</p> <p>If anyone knows for sure about the connection/cursor objects, let me know in a comment.</p>
10
2009-09-22T20:48:01Z
1,473,630
<p>Is it possible to create a DB function that will process your content? If so, you should be able to write a single update statement and let the database do all the work. Eg;</p> <pre><code>Update data_table set processed_col = Process_Column(col_to_be_processed) </code></pre>
2
2009-09-24T19:14:56Z
[ "python", "database", "sqlite", "sqlite3", "cursor" ]
What are sqlite development headers and how to install them?
1,462,565
<p>I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them.</p> <p>However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them).</p> <p>Can anybody, pleas, help me with that?</p>
10
2009-09-22T20:57:06Z
1,462,623
<p>pysqlite needs to compiled/build before you can use it. This requires C language header files (*.H) which come with the source code of sqllite itself.</p> <p>i.e. sqllite and pysqlite are two different things. Did you install sqlite prior to trying and build pysqllte ? (or maybe you did, but did you do so just with the binaries; you need the source package (or at least its headers) for pysqlite purposes.</p>
0
2009-09-22T21:10:35Z
[ "python", "header", "pysqlite" ]
What are sqlite development headers and how to install them?
1,462,565
<p>I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them.</p> <p>However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them).</p> <p>Can anybody, pleas, help me with that?</p>
10
2009-09-22T20:57:06Z
1,462,624
<p>debian/ubuntu:</p> <pre><code>$ apt-get install libsqlite3-dev # or rpm -i sqlite-devel-something.rpm </code></pre> <hr> <p>I think a number of interpreters just recompile their small connection libraries on installation, but to do that they need the C .h files in addition to the library to link against. You may already have the library, because something else depended on it, but you don't necessarily have the <code>dev</code> package, which is kind of half-way between source and binary.</p> <p>Part of it is straightforward, if you are going to develop with a library you need its interface headers.</p> <p>But I think something more happened, at first, people tried all-source and all-binary distributions, but the all-binary ones were vulnerable to <em>dependency hell</em>, and the all-source ones were overkill. I think now that an interesting compromise is in use, a semi-source distribution where a program links to installed libraries by recompiling those parts of it that link to extension libraries. This makes a lot of sense with interpreters where most of the system can arrive in binary but the extension modules are dynamically loaded and compiled for the installed system. I think.</p>
16
2009-09-22T21:10:39Z
[ "python", "header", "pysqlite" ]
What are sqlite development headers and how to install them?
1,462,565
<p>I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them.</p> <p>However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them).</p> <p>Can anybody, pleas, help me with that?</p>
10
2009-09-22T20:57:06Z
5,671,345
<p>For me this worked (Redhat/CentOS):</p> <p>$ sudo yum install sqlite-devel</p>
7
2011-04-15T00:52:50Z
[ "python", "header", "pysqlite" ]
Print PDF document with python's win32print module?
1,462,842
<p>I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? </p> <p>If so, is there a module available to convert a PDF document into PCL?</p> <p>I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default printer. I need to print to a variety of printers on servers across various networks.</p> <p>Thanks for your help, Pete</p>
2
2009-09-22T21:52:15Z
1,463,214
<p>I am not sure how to specifically get win32print to work, but there might be a couple of other options. <a href="http://www.reportlab.org/" rel="nofollow">Reportlab</a> if often mentioned when creating PDFs from Python. If you are already invested in your approach, maybe using <a href="http://pyx.sourceforge.net/" rel="nofollow">PyX</a> or <a href="http://www.nongnu.org/pypsg/" rel="nofollow">pypsg</a> to generate the Postscript files and then feeding that into win32print would work.</p>
0
2009-09-22T23:44:50Z
[ "python", "windows", "pdf", "winapi", "postscript" ]
Print PDF document with python's win32print module?
1,462,842
<p>I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? </p> <p>If so, is there a module available to convert a PDF document into PCL?</p> <p>I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default printer. I need to print to a variety of printers on servers across various networks.</p> <p>Thanks for your help, Pete</p>
2
2009-09-22T21:52:15Z
1,464,974
<p>I ended up using <a href="http://pages.cs.wisc.edu/~ghost/" rel="nofollow" title="Ghostscript">Ghostscript</a> to accomplish this task. There is a command line tool that relies on Ghostscript called <a href="http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm" rel="nofollow" title="gsprint">gsprint</a>.</p> <p>You don't even need Acrobat installed to print PDFs in this fashion which is quite nice. </p> <p>Here is an example:</p> <p>on the command line:</p> <pre><code>gsprint -printer \\server\printer "test.pdf" </code></pre> <p>from python:</p> <pre><code>win32api.ShellExecute(0, 'open', 'gsprint.exe', '-printer "\\\\' + self.server + '\\' + self.printer_name + '" ' + file, '.', 0) </code></pre> <p>Note that I've added to my PATH variable in these examples, so I don't have to include the entire path when calling the executable.</p> <p>There is one downside, however. The code is licensed under the GPL, so it's no very useful in commercial software.</p> <p>Hope this helps someone, Pete</p>
8
2009-09-23T09:37:55Z
[ "python", "windows", "pdf", "winapi", "postscript" ]
Print PDF document with python's win32print module?
1,462,842
<p>I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? </p> <p>If so, is there a module available to convert a PDF document into PCL?</p> <p>I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default printer. I need to print to a variety of printers on servers across various networks.</p> <p>Thanks for your help, Pete</p>
2
2009-09-22T21:52:15Z
3,284,735
<p>I was already using the win32api.ShellExecute approach and needed to print to a non-default printer. The best way I could work out was to temporarily change the default printer. So right before I do the print I store what the current default printer is, change it, and then set it back after printing. Something like:</p> <pre><code>tempprinter = "\\\\server01\\printer01" currentprinter = win32print.GetDefaultPrinter() win32print.SetDefaultPrinter(tempprinter) win32api.ShellExecute(0, "print", filename, None, ".", 0) win32print.SetDefaultPrinter(currentprinter) </code></pre> <p>I'm not going to claim it's pretty, but it worked and it allowed me to leave my other code untouched.</p>
2
2010-07-19T20:22:27Z
[ "python", "windows", "pdf", "winapi", "postscript" ]
python system calls
1,462,878
<p>with this command, I get only the file called OUTPUT (in reality I have many more --include flags) - so works as expected:</p> <pre><code>os.system("rsync --rsh=ssh -arvuP --include='OUTPUT' --exclude='*' user@host:there/ ./here") </code></pre> <p>In this case, the --include and --exclude flags are ignored:</p> <pre><code>subprocess.call("rsync --rsh=ssh -arvuP --include='OUTPUT' --exclude='*' user@host:there/ ./here".split()) </code></pre> <p>I wonder what I am doing wrong? Thank you much!</p> <p>Edit: Sorry, this is on OS X Leopard, and I get all the files...</p>
0
2009-09-22T22:05:15Z
1,462,983
<p>Try using <code>subprocess.call</code> with <code>shell=True</code>, it will simulate os.system more closely:</p> <pre><code>subprocess.call("...", shell=True) </code></pre>
4
2009-09-22T22:31:44Z
[ "python", "shell" ]
python system calls
1,462,878
<p>with this command, I get only the file called OUTPUT (in reality I have many more --include flags) - so works as expected:</p> <pre><code>os.system("rsync --rsh=ssh -arvuP --include='OUTPUT' --exclude='*' user@host:there/ ./here") </code></pre> <p>In this case, the --include and --exclude flags are ignored:</p> <pre><code>subprocess.call("rsync --rsh=ssh -arvuP --include='OUTPUT' --exclude='*' user@host:there/ ./here".split()) </code></pre> <p>I wonder what I am doing wrong? Thank you much!</p> <p>Edit: Sorry, this is on OS X Leopard, and I get all the files...</p>
0
2009-09-22T22:05:15Z
1,463,567
<p>Python does have an rsync module if I am not wrong, why not use that instead of a call. It will make your app more manageable.</p>
1
2009-09-23T01:46:39Z
[ "python", "shell" ]
Django generates 'WHERE ... BETWEEN ...' sentences?
1,462,968
<p>Actually, somewhere in the view:</p> <pre><code>dif = datetime.timedelta(days=1) today = datetime.date.today() yesterday = today - dif ex = Fact.objects.filter(fecha_fact__lte=today ,fecha_fact__gte=yesterday ) </code></pre> <p>It results to this SQL Query:</p> <pre><code>SELECT `facts_fact`.`id` ... FROM `facts_fact` WHERE (`facts_fact`.`fecha_fact` &gt;= 2009-09-21 AND `facts_fact`.`fecha_fact` &lt;= 2009-09-22 ) </code></pre> <p>There is a way to make Django do a WHERE BETWEEN sentence instead >= &lt;= ?</p> <p>:) thx.</p>
2
2009-09-22T22:27:58Z
1,462,991
<p>Have you tried <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#range" rel="nofollow"><code>range</code></a>?</p> <pre><code>Fact.objects.filter(fecha_fact__range=(yesterday, today)) </code></pre>
4
2009-09-22T22:33:54Z
[ "python", "sql", "django", "django-models" ]
Django generates 'WHERE ... BETWEEN ...' sentences?
1,462,968
<p>Actually, somewhere in the view:</p> <pre><code>dif = datetime.timedelta(days=1) today = datetime.date.today() yesterday = today - dif ex = Fact.objects.filter(fecha_fact__lte=today ,fecha_fact__gte=yesterday ) </code></pre> <p>It results to this SQL Query:</p> <pre><code>SELECT `facts_fact`.`id` ... FROM `facts_fact` WHERE (`facts_fact`.`fecha_fact` &gt;= 2009-09-21 AND `facts_fact`.`fecha_fact` &lt;= 2009-09-22 ) </code></pre> <p>There is a way to make Django do a WHERE BETWEEN sentence instead >= &lt;= ?</p> <p>:) thx.</p>
2
2009-09-22T22:27:58Z
1,463,005
<p>i dont know, but maybe (gte / lte ):</p> <pre><code>q1 = Entry.objects.filter(headline__startswith="What") q2 = q1.exclude(pub_date__gte=datetime.now()) q3 = q1.filter(pub_date__gte=datetime.now()) q = Entry.objects.filter(headline__startswith="What") q = q.filter(pub_date__lte=datetime.now()) </code></pre>
0
2009-09-22T22:37:31Z
[ "python", "sql", "django", "django-models" ]
Lazy module variables--can it be done?
1,462,986
<p>I'm trying to find a way to lazily load a module-level variable.</p> <p>Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a <code>DOWNLOAD_FOLDER_PATH</code> module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the "Downloads" directory.</p> <p>This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.</p> <p>Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?</p>
22
2009-09-22T22:32:05Z
1,463,036
<p>If that variable lived in a class rather than a module, then you could overload getattr, or better yet, populate it in init.</p>
0
2009-09-22T22:44:47Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
Lazy module variables--can it be done?
1,462,986
<p>I'm trying to find a way to lazily load a module-level variable.</p> <p>Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a <code>DOWNLOAD_FOLDER_PATH</code> module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the "Downloads" directory.</p> <p>This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.</p> <p>Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?</p>
22
2009-09-22T22:32:05Z
1,463,121
<p><em>Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?</em></p> <p>I think you are correct in saying that a function is the best solution to your problem here. I will give you a brief example to illustrate.</p> <pre><code>#myfile.py - an example module with some expensive module level code. import os # expensive operation to crawl up in directory structure </code></pre> <p>The expensive operation will be executed on import if it is at module level. There is not a way to stop this, short of lazily importing the entire module!!</p> <pre><code>#myfile2.py - a module with expensive code placed inside a function. import os def getdownloadsfolder(curdir=None): """a function that will search upward from the user's current directory to find the 'Downloads' folder.""" # expensive operation now here. </code></pre> <p>You will be following best practice by using this method.</p>
3
2009-09-22T23:10:16Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
Lazy module variables--can it be done?
1,462,986
<p>I'm trying to find a way to lazily load a module-level variable.</p> <p>Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a <code>DOWNLOAD_FOLDER_PATH</code> module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the "Downloads" directory.</p> <p>This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.</p> <p>Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?</p>
22
2009-09-22T22:32:05Z
1,463,773
<p>You can't do it with modules, but you can disguise a class "as if" it was a module, e.g., in <code>itun.py</code>, code...:</p> <pre><code>import sys class _Sneaky(object): def __init__(self): self.download = None @property def DOWNLOAD_PATH(self): if not self.download: self.download = heavyComputations() return self.download def __getattr__(self, name): return globals()[name] # other parts of itun that you WANT to code in # module-ish ways sys.modules[__name__] = _Sneaky() </code></pre> <p>Now anybody can <code>import itun</code>... and get in fact your <code>itun._Sneaky()</code> instance. The <code>__getattr__</code> is there to let you access anything else in <code>itun.py</code> that may be more convenient for you to code as a top-level module object, than inside <code>_Sneaky</code>!_)</p>
39
2009-09-23T03:09:28Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
Lazy module variables--can it be done?
1,462,986
<p>I'm trying to find a way to lazily load a module-level variable.</p> <p>Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a <code>DOWNLOAD_FOLDER_PATH</code> module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the "Downloads" directory.</p> <p>This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.</p> <p>Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?</p>
22
2009-09-22T22:32:05Z
14,345,798
<p>I used Alex' implementation on Python 3.3, but this crashes miserably: The code</p> <pre><code> def __getattr__(self, name): return globals()[name] </code></pre> <p>is not correct because an <code>AttributeError</code> should be raised, not a <code>KeyError</code>. This crashed immediately under Python 3.3, because a lot of introspection is done during the import, looking for attributes like <code>__path__</code>, <code>__loader__</code> etc.</p> <p>Here is the version that we use now in our project to allow for lazy imports in a module. The <code>__init__</code> of the module is delayed until the first attribute access that has not a special name:</p> <pre><code>""" config.py """ # lazy initialization of this module to avoid circular import. # the trick is to replace this module by an instance! # modelled after a post from Alex Martelli :-) </code></pre> <p><a href="http://stackoverflow.com/questions/1462986/lazy-module-variables-can-it-be-done">Lazy module variables--can it be done?</a></p> <pre><code>class _Sneaky(object): def __init__(self, name): self.module = sys.modules[name] sys.modules[name] = self self.initializing = True def __getattr__(self, name): # call module.__init__ after import introspection is done if self.initializing and not name[:2] == '__' == name[-2:]: self.initializing = False __init__(self.module) return getattr(self.module, name) _Sneaky(__name__) </code></pre> <p>The module now needs to define an <strong>init</strong> function. This function can be used to import modules that might import ourselves:</p> <pre><code>def __init__(module): ... # do something that imports config.py again ... </code></pre> <p>The code can be put into another module, and it can be extended with properties as in the examples above.</p> <p>Maybe that is useful for somebody.</p>
9
2013-01-15T19:57:57Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
Lazy module variables--can it be done?
1,462,986
<p>I'm trying to find a way to lazily load a module-level variable.</p> <p>Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a <code>DOWNLOAD_FOLDER_PATH</code> module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a few podcast tracks and climbs back up the directory tree until it finds the "Downloads" directory.</p> <p>This takes a second or two, so I'd like to have it evaluated lazily, rather than at module import time.</p> <p>Is there any way to lazily assign a module variable when it's first accessed or will I have to rely on a function?</p>
22
2009-09-22T22:32:05Z
16,937,048
<p>Recently I came across the same problem, and have found a way to do it.</p> <pre><code>class LazyObject(object): def __init__(self): self.initialized = False setattr(self, 'data', None) def init(self, *args): #print 'initializing' pass def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) def __getattribute__(self, key): if object.__getattribute__(self, 'initialized') == False: object.__getattribute__(self, 'init')(self) setattr(self, 'initialized', True) if key == 'data': return object.__getattribute__(self, 'data') else: try: return object.__getattribute__(self, 'data').__getattribute__(key) except AttributeError: return super(LazyObject, self).__getattribute__(key) </code></pre> <p>With this <code>LazyObject</code>, You can define a <code>init</code> method for the object, and the object will be initialized lazily, example code looks like:</p> <pre><code>o = LazyObject() def slow_init(self): time.sleep(1) # simulate slow initialization self.data = 'done' o.init = slow_init </code></pre> <p>the <code>o</code> object above will have exactly the same methods whatever <code>'done'</code> object have, for example, you can do:</p> <pre><code># o will be initialized, then apply the `len` method assert len(o) == 4 </code></pre> <p>complete code with tests (works in 2.7) can be found here:</p> <p><a href="https://gist.github.com/observerss/007fedc5b74c74f3ea08" rel="nofollow">https://gist.github.com/observerss/007fedc5b74c74f3ea08</a></p>
2
2013-06-05T10:04:07Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
How can I get an email message's text content using python?
1,463,074
<p>Given an RFC822 message in Python 2.6, how can I get the <em>right</em> text/plain content part? Basically, the algorithm I want is this:</p> <pre><code>message = email.message_from_string(raw_message) if has_mime_part(message, "text/plain"): mime_part = get_mime_part(message, "text/plain") text_content = decode_mime_part(mime_part) elif has_mime_part(message, "text/html"): mime_part = get_mime_part(message, "text/html") html = decode_mime_part(mime_part) text_content = render_html_to_plaintext(html) else: # fallback text_content = str(message) return text_content </code></pre> <p>Of these things, I have <code>get_mime_part</code> and <code>has_mime_part</code> down pat, but I'm not quite sure how to get the decoded text from the MIME part. I can get the <em>encoded</em> text using <code>get_payload()</code>, but if I try to use the <code>decode</code> parameter of the <code>get_payload()</code> method (see <a href="http://docs.python.org/library/email.message.html#email.message.Message.get%5Fpayload">the doc</a>) I get an error when I call it on the text/plain part:</p> <pre><code> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/email/message.py", line 189, in get_payload raise TypeError('Expected list, got %s' % type(self._payload)) TypeError: Expected list, got &lt;type 'str'&gt; </code></pre> <p>In addition, I don't know how to take HTML and render it to text as closely as possible.</p>
19
2009-09-22T22:56:24Z
1,463,144
<p>In a multipart e-mail, <code>email.message.Message.get_payload()</code> returns a list with one item for each part. The easiest way is to walk the message and get the payload on each part:</p> <pre><code>import email msg = email.message_from_string(raw_message) for part in msg.walk(): # each part is a either non-multipart, or another multipart message # that contains further parts... Message is organized like a tree if part.get_content_type() == 'text/plain': print part.get_payload() # prints the raw text </code></pre> <p>For a non-multipart message, no need to do all the walking. You can go straight to get_payload(), regardless of content_type.</p> <pre><code>msg = email.message_from_string(raw_message) msg.get_payload() </code></pre> <p>If the content is encoded, you need to pass <code>None</code> as the first parameter to <code>get_payload()</code>, followed by True (the decode flag is the second parameter). For example, suppose that my e-mail contains an MS Word document attachment:</p> <pre><code>msg = email.message_from_string(raw_message) for part in msg.walk(): if part.get_content_type() == 'application/msword': name = part.get_param('name') or 'MyDoc.doc' f = open(name, 'wb') f.write(part.get_payload(None, True)) # You need None as the first param # because part.is_multipart() # is False f.close() </code></pre> <p>As for getting a reasonable plain-text approximation of an HTML part, I've found that <a href="http://www.aaronsw.com/2002/html2text/">html2text</a> works pretty darn well.</p>
51
2009-09-22T23:17:31Z
[ "python", "email", "mime", "rfc822" ]
How can I get an email message's text content using python?
1,463,074
<p>Given an RFC822 message in Python 2.6, how can I get the <em>right</em> text/plain content part? Basically, the algorithm I want is this:</p> <pre><code>message = email.message_from_string(raw_message) if has_mime_part(message, "text/plain"): mime_part = get_mime_part(message, "text/plain") text_content = decode_mime_part(mime_part) elif has_mime_part(message, "text/html"): mime_part = get_mime_part(message, "text/html") html = decode_mime_part(mime_part) text_content = render_html_to_plaintext(html) else: # fallback text_content = str(message) return text_content </code></pre> <p>Of these things, I have <code>get_mime_part</code> and <code>has_mime_part</code> down pat, but I'm not quite sure how to get the decoded text from the MIME part. I can get the <em>encoded</em> text using <code>get_payload()</code>, but if I try to use the <code>decode</code> parameter of the <code>get_payload()</code> method (see <a href="http://docs.python.org/library/email.message.html#email.message.Message.get%5Fpayload">the doc</a>) I get an error when I call it on the text/plain part:</p> <pre><code> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/email/message.py", line 189, in get_payload raise TypeError('Expected list, got %s' % type(self._payload)) TypeError: Expected list, got &lt;type 'str'&gt; </code></pre> <p>In addition, I don't know how to take HTML and render it to text as closely as possible.</p>
19
2009-09-22T22:56:24Z
34,039,927
<p>Flat is better than nested ;)</p> <pre><code>from email.mime.multipart import MIMEMultipart assert isinstance(msg, MIMEMultipart) for _ in [k.get_payload() for k in msg.walk() if k.get_content_type() == 'text/plain']: print _ </code></pre>
0
2015-12-02T10:06:28Z
[ "python", "email", "mime", "rfc822" ]
django - using a common header with some dynamic elements
1,463,153
<p>I'm planning to create a website using django that will have a common header throughout the entire website. I've read django's documentation on templating inheritance, but I can't seem to find an elegant solution for the "dynamic" elements in my header.</p> <p>For example, the header in the website will include tabs, say similar to <a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a> (where it has "Web", "Images", etc), where the selected tab will describe your current location in the website.</p> <p>Using the django template inheritance, it would seem like you would create a base template like this:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;title&gt;{% block title %}My Amazing Site{% endblock %}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt; {% block header %} .... html to create tabs ... {% endblock header %} &lt;/div&gt; </code></pre> <p>and then in all of my other pages, i would do this:</p> <pre><code>{% extends "base.html" %} {% block header % } .... html to create tabs with one tab "selected" ... {% endblock header %} </code></pre> <p>which seems annoying as every single one of my pages would have to have duplicated HTML with the header information, but slightly different. So when its time to add a new tab, i have to modify every single HTML file.</p> <p>Upon further reading, it seems like some other possible solutions are:</p> <p>1 - Create a custom template tag that takes in which tab is currently selected, that way in each HTML page i just call: {% block header %} {% mycustomtag abc %} {% endblock header %}</p> <p>I don't like this solution because it would requiring placing HTML into the python code for creating this custom tag.</p> <p>2 - Create X number of sub-templates of base.html, all with the appropriate tab selected. Then each page would inherit from the appropriate sub-template based on which tab they want selected. </p> <p>This solution seems fine, except for the fact that it will require X number of almost exactly the same HTML, and still runs into the issue of having to modify all the files when a tab is added or removed.</p> <p>3 - Use javascript (like jquery) to modify the header on page load to "select" the correct tab.</p> <p>This solution is fine but then would require one to remember to add this functionality to every page's javascript. the good part is that the header HTML would only live in a single HTML file.</p> <p>Any other suggestions?</p> <p>Thanks!</p>
3
2009-09-22T23:20:04Z
1,463,319
<p>A version of #1 will do the trick — with a separate template file for the tag.</p> <p>Lets say you have the models "Category" and "Article".</p> <pre><code>class Category(models.Model): title = models.CharField(_("Name"), max_length=200) introduction = models.TextField(blank=True, null=True) slug = models.SlugField(help_text=_("Used for URLs")) sort_order = models.IntegerField(_("Sortierung")) class Article(models.Model): title = models.CharField(_("Full Name"), max_length=255) slug = models.SlugField(_("Slug Name"), unique=True, help_text=_("This is a short, descriptive name of article that will be used in the URL link to this item")) text = models.TextField(_("Text of Article"), blank=True, null=True) category = models.ForeignKey(Category) </code></pre> <p>in your views you would pass the category you are viewing to the template:</p> <pre><code>@render_to('cat_index.html') def category_view(request,string): cat = Category.objects.get(slug=string) articles = Article.objects.filter(category = cat).order_by('date') return { 'articles':articles, 'category':cat, } </code></pre> <p>(Note: using the <a href="http://bitbucket.org/offline/django-annoying/" rel="nofollow">annoying</a> <code>render_to</code>-decorator – same as <code>render_to_response</code>)</p> <p>and in your template you call a inclusion_tag like this:</p> <pre><code>@register.inclusion_tag('snippets/navigation.html') def navigation(cat=None): return {'cats':Category.objects.order_by('sort_order'), 'cat':cat } </code></pre> <p>by using this in your base-template (often called base.html)</p> <pre><code>{% navigation category %} </code></pre> <p>Now in the inclusions_tags's template (<code>snippets/navigation.html</code>) you would for-loop over <code>cats</code> and if one of it equals <code>cat</code> you can assign other styles</p> <pre><code> &lt;ul&gt; {% for c in cats %} &lt;li{% ifequal c cat %} class="active"{% endifequal %}&gt; &lt;a href="{{c|url}}"&gt;{{ c }}&lt;/a&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre>
1
2009-09-23T00:22:03Z
[ "javascript", "python", "django" ]
django - using a common header with some dynamic elements
1,463,153
<p>I'm planning to create a website using django that will have a common header throughout the entire website. I've read django's documentation on templating inheritance, but I can't seem to find an elegant solution for the "dynamic" elements in my header.</p> <p>For example, the header in the website will include tabs, say similar to <a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a> (where it has "Web", "Images", etc), where the selected tab will describe your current location in the website.</p> <p>Using the django template inheritance, it would seem like you would create a base template like this:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;title&gt;{% block title %}My Amazing Site{% endblock %}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt; {% block header %} .... html to create tabs ... {% endblock header %} &lt;/div&gt; </code></pre> <p>and then in all of my other pages, i would do this:</p> <pre><code>{% extends "base.html" %} {% block header % } .... html to create tabs with one tab "selected" ... {% endblock header %} </code></pre> <p>which seems annoying as every single one of my pages would have to have duplicated HTML with the header information, but slightly different. So when its time to add a new tab, i have to modify every single HTML file.</p> <p>Upon further reading, it seems like some other possible solutions are:</p> <p>1 - Create a custom template tag that takes in which tab is currently selected, that way in each HTML page i just call: {% block header %} {% mycustomtag abc %} {% endblock header %}</p> <p>I don't like this solution because it would requiring placing HTML into the python code for creating this custom tag.</p> <p>2 - Create X number of sub-templates of base.html, all with the appropriate tab selected. Then each page would inherit from the appropriate sub-template based on which tab they want selected. </p> <p>This solution seems fine, except for the fact that it will require X number of almost exactly the same HTML, and still runs into the issue of having to modify all the files when a tab is added or removed.</p> <p>3 - Use javascript (like jquery) to modify the header on page load to "select" the correct tab.</p> <p>This solution is fine but then would require one to remember to add this functionality to every page's javascript. the good part is that the header HTML would only live in a single HTML file.</p> <p>Any other suggestions?</p> <p>Thanks!</p>
3
2009-09-22T23:20:04Z
1,463,395
<p>I'm assuming each tab is a list item in your template <code>base.html</code>.</p> <pre><code>&lt;ul&gt; &lt;li&gt;Tab 1&lt;/li&gt; &lt;li&gt;Tab 2&lt;/li&gt; ... &lt;/ul&gt; </code></pre> <p>Add an extra block to each <code>li</code>.</p> <pre><code>&lt;ul&gt; &lt;li class="{% block class_tab1 %}inactive{% endblock %}"&gt;Tab 1&lt;/li&gt; &lt;li class="{% block class_tab2 %}inactive{% endblock %}"&gt;Tab 2&lt;/li&gt; &lt;li class="{% block class_tab3 %}inactive{% endblock %}"&gt;Tab 3&lt;/li&gt; ... &lt;/ul&gt; </code></pre> <p>Then in your template if tab 1 is to be selected:</p> <pre><code>{% extends "base.html" %} {% block class_tab1 %}active{% endblock %} ... </code></pre> <p>So the html rendered for Tab 1 is:</p> <pre><code>&lt;ul&gt; &lt;li class="active"&gt;Tab 1&lt;/li&gt; &lt;li class="inactive"&gt;Tab 2&lt;/li&gt; &lt;li class="inactive"&gt;Tab 3&lt;/li&gt; ... &lt;/ul&gt; </code></pre> <p>and you can write CSS to target the <code>li .active</code> as you wish.</p>
9
2009-09-23T00:47:22Z
[ "javascript", "python", "django" ]
django - using a common header with some dynamic elements
1,463,153
<p>I'm planning to create a website using django that will have a common header throughout the entire website. I've read django's documentation on templating inheritance, but I can't seem to find an elegant solution for the "dynamic" elements in my header.</p> <p>For example, the header in the website will include tabs, say similar to <a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a> (where it has "Web", "Images", etc), where the selected tab will describe your current location in the website.</p> <p>Using the django template inheritance, it would seem like you would create a base template like this:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;title&gt;{% block title %}My Amazing Site{% endblock %}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt; {% block header %} .... html to create tabs ... {% endblock header %} &lt;/div&gt; </code></pre> <p>and then in all of my other pages, i would do this:</p> <pre><code>{% extends "base.html" %} {% block header % } .... html to create tabs with one tab "selected" ... {% endblock header %} </code></pre> <p>which seems annoying as every single one of my pages would have to have duplicated HTML with the header information, but slightly different. So when its time to add a new tab, i have to modify every single HTML file.</p> <p>Upon further reading, it seems like some other possible solutions are:</p> <p>1 - Create a custom template tag that takes in which tab is currently selected, that way in each HTML page i just call: {% block header %} {% mycustomtag abc %} {% endblock header %}</p> <p>I don't like this solution because it would requiring placing HTML into the python code for creating this custom tag.</p> <p>2 - Create X number of sub-templates of base.html, all with the appropriate tab selected. Then each page would inherit from the appropriate sub-template based on which tab they want selected. </p> <p>This solution seems fine, except for the fact that it will require X number of almost exactly the same HTML, and still runs into the issue of having to modify all the files when a tab is added or removed.</p> <p>3 - Use javascript (like jquery) to modify the header on page load to "select" the correct tab.</p> <p>This solution is fine but then would require one to remember to add this functionality to every page's javascript. the good part is that the header HTML would only live in a single HTML file.</p> <p>Any other suggestions?</p> <p>Thanks!</p>
3
2009-09-22T23:20:04Z
1,463,556
<p>This is a rather common problems and I've come up with some various ways to solve it.</p> <p>Since you're asking for options, here's 3 other alternative ways achieve this effect. The options you mentioned and these listed below all have thier positives and negatives. It's really up to you to decide which is a best fit.</p> <p><strong>Alternate 1 - Use Regular Expressions and a Hash Table</strong></p> <p>This could be performed either client-side (less advantageous) or server-side (a better pick). To do this you could have a tag that had 1 input: a regular expression. In use it would look like this...</p> <pre><code>// In base.html... &lt;li class="tab {% is_tab_active r'^/cars/' %}"&gt;&lt;a&gt;Cars&lt;/a&gt;&lt;/li&gt; &lt;li class="tab {% is_tab_active r'^/trucks/' %}"&gt;&lt;a&gt;Trucks&lt;/a&gt;&lt;/li&gt; </code></pre> <p>The custom tag applies the regular expression against the current page being viewed. If successfull, it adds a css class "active" if not "inactive" (or whatever your CSS classes are).</p> <p>I've been pondering this method for a while. I feel as if there should be some good way to come up with a way to tie it into urls.py, but I haven't seen it yet.</p> <p><strong>Alternate 2 - Use CSS</strong></p> <p>If you were to identify each [body] tag, or at least have a common template for the sections of your site, CSS could be used to assign which was active. Consider the following:</p> <pre><code>body.cars_section .navigation #cars_tab { color: #00000; } body.truck_section .navigation #trucks_tab { color: #00000; } </code></pre> <p>For your base template...</p> <pre><code>&lt;body class="{% block category %}{% endblock %}"&gt; ... &lt;ul class="navigation"&gt; &lt;li id="cars_tab"&gt;&lt;a&gt;Cars&lt;/a&gt;&lt;/li&gt; &lt;li id="trucks_tab"&gt;&lt;a&gt;Trucks&lt;/a&gt;&lt;/li&gt; </code></pre> <p>Then for any page you simply put the category it's a part of (matching the CSS rule)...</p> <pre><code>{% extends "base.html" %} ... {% block category %}cars_section{% endblock %} </code></pre> <p><strong>Alternate 3 - Have Some Bloated Middleware</strong></p> <p>Django lets you write Middleware to affect the behavior of just about whatever you want. This seems like a bloated and complex route with potential negative performance impact, but I figured I'd at least mention it as an option.</p>
1
2009-09-23T01:41:37Z
[ "javascript", "python", "django" ]
How to create user defined fields in Django
1,463,242
<p>Ok, I am working on a Django application with several different models, namely Accounts, Contacts, etc, each with a different set of fields. I need to be able to allow each of my users to define their own fields in addition to the existing fields. I have seen several different ways to implement this, from having a large number of CustomFields and just mapping a custom name to each field used by each user. I have also seem recommendations for implementing complex mapping or XML/JSON style storage/retrieval of user defined fields. </p> <p>So my question is this, has anyone implemented user defined fields in a Django application? If so, how did you do it and what was your experience with the overall implementation (stability, performance, etc)?</p> <p>Update: My goal is to allow each of my users to create n number of each record type (accounts, contacts, etc) and associate user defined data with each record. So for example, one of my users might want to associate an SSN with each of his contacts, so I would need to store that additional field for each Contact record he creates.</p> <p>Thanks!</p> <p>Mark</p>
2
2009-09-22T23:56:33Z
1,463,676
<p>What if you were to use a ForeignKey?</p> <p>This code (untested and for demo) is assuming there is a system-wide set of custom fields. To make it user-specific, you'd add a "user = models.ForiegnKey(User)" onto the class CustomField.</p> <pre><code>class Account(models.Model): name = models.CharField(max_length=75) # ... def get_custom_fields(self): return CustomField.objects.filter(content_type=ContentType.objects.get_for_model(Account)) custom_fields = property(get_fields) class CustomField(models.Model): """ A field abstract -- it describe what the field is. There are one of these for each custom field the user configures. """ name = models.CharField(max_length=75) content_type = models.ForeignKey(ContentType) class CustomFieldValueManager(models.Manager): get_value_for_model_instance(self, model): content_type = ContentType.objects.get_for_model(model) return self.filter(model__content_type=content_type, model__object_id=model.pk) class CustomFieldValue(models.Model): """ A field instance -- contains the actual data. There are many of these, for each value that corresponds to a CustomField for a given model. """ field = models.ForeignKey(CustomField, related_name='instance') value = models.CharField(max_length=255) model = models.GenericForeignKey() objects = CustomFieldValueManager() # If you wanted to enumerate the custom fields and their values, it would look # look like so: account = Account.objects.get(pk=1) for field in account.custom_fields: print field.name, field.instance.objects.get_value_for_model_instance(account) </code></pre>
2
2009-09-23T02:26:37Z
[ "python", "django", "configuration", "modeling" ]
How does exec work with locals?
1,463,306
<p>I thought this would print 3, but it prints 1:</p> <pre><code>def f(): a = 1 exec("a = 3") print(a) </code></pre>
10
2009-09-23T00:18:47Z
1,463,370
<p>This issue is somewhat discussed in the <a href="http://bugs.python.org/issue4831">Python3 bug list</a>. Ultimately, to get this behavior, you need to do:</p> <pre><code>def foo(): ldict = locals() exec("a=3",globals(),ldict) a = ldict['a'] print(a) </code></pre> <p>And if you check <a href="http://docs.python.org/3.1/library/functions.html#exec">the Python3 documentation on <code>exec</code></a>, you'll see the following note:</p> <blockquote> <p>The default locals act as described for function <code>locals()</code> below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.</p> </blockquote> <p>Referring back to <a href="http://bugs.python.org/msg79061">a specific message on the bug report</a>, Georg Brandl says:</p> <blockquote> <p>To modify the locals of a function on the fly is not possible without several consequences: <strong>normally, function locals are not stored in a dictionary, but an array</strong>, whose indices are determined at compile time from the known locales. This collides at least with new locals added by exec. The old exec statement circumvented this, because the compiler knew that if an exec without globals/locals args occurred in a function, that namespace would be "unoptimized", i.e. not using the locals array. Since exec() is now a normal function, <strong>the compiler does not know what "exec" may be bound to, and therefore can not treat is specially</strong>.</p> </blockquote> <p>Emphasis is mine.</p> <p>So the gist of it is that Python3 can better optimize the use of local variables by <em>not</em> allowing this behavior by default.</p> <p>And for the sake of completeness, as mentioned in the comments above, this <em>does</em> work as expected in Python 2.X:</p> <pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; def f(): ... a = 1 ... exec "a=3" ... print a ... &gt;&gt;&gt; f() 3 </code></pre>
18
2009-09-23T00:37:27Z
[ "python", "python-3.x", "exec", "locals" ]
How does exec work with locals?
1,463,306
<p>I thought this would print 3, but it prints 1:</p> <pre><code>def f(): a = 1 exec("a = 3") print(a) </code></pre>
10
2009-09-23T00:18:47Z
32,828,675
<p>If you are inside a method, you can do so:</p> <pre><code>class Thing(): def __init__(self): exec('self.foo = 2') x = Thing() print(x.foo) </code></pre> <p><a href="http://chimera.labs.oreilly.com/books/1230000000393/ch09.html#_problem_166" rel="nofollow">You can read more about it here</a></p>
2
2015-09-28T17:32:06Z
[ "python", "python-3.x", "exec", "locals" ]
Django: how to including inline model fields in the list_display?
1,463,398
<p>I'm attempting to extend django's contrib.auth User model, using an inline 'Profile' model to include extra fields.</p> <pre><code>from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin class Profile(models.Model): user = models.ForeignKey(User, unique=True, related_name='profile') avatar = '/images/avatar.png' nickname = 'Renz' class UserProfileInline(admin.StackedInline): model = Profile class UserProfileAdmin(UserAdmin): inlines = (UserProfileInline,) admin.site.unregister(User) admin.site.register(User, UserProfileAdmin) </code></pre> <p>This works just fine for the admin 'Change User' page, but I can't find a way to add inline model fields in the list_display. Just specifying the names of Profile fields in list_display give me an error:</p> <blockquote> <p>UserProfileAdmin.list_display[4], 'avatar' is not a callable or an attribute of 'UserProfileAdmin' or found in the model 'User'.</p> </blockquote> <p>I can create a callable which looks up the user in the Profile table and returns the relevant field, but this leaves me without the ability to sort the list view by the inline fields, which I really need to be able to do.</p> <p>Any suggestions?</p>
3
2009-09-23T00:48:30Z
1,464,624
<p>You've mentioned the only solution - creating a callable. There's currently no other way to do it, and yes this does mean you can't sort by that column. </p>
7
2009-09-23T08:09:18Z
[ "python", "django", "django-models", "django-admin" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
1,463,501
<p>You can't. HttpResponseRedirect sends a client-side redirect (HTTP status code 302) to the browser, and then the browser re-requests another page.</p> <p>You can set a URL query string on the redirect, though that will be visible to the user and anyone intercepting HTTP requests (i.e. proxies), and is therefore not suitable for sensitive information.</p>
4
2009-09-23T01:24:46Z
[ "python", "django", "http", "redirect" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
1,463,504
<p>You add ?saved=1 to the query string and check for it with something like:</p> <pre><code>saved = request.GET.get('saved', False) </code></pre>
0
2009-09-23T01:25:42Z
[ "python", "django", "http", "redirect" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
1,463,508
<p>The only way I know of to pass any data with a redirect is to add GET parameters to the URL you're passing in. To avoid XSS hacks you'd want to pass a specific constant like:</p> <p>[current path you're passing in]?message=saved</p> <p>And then process the message=saved parameter in the handler for the path you passed in.</p> <p>A somewhat more complicated way would be not passing the data in the redirect, and instead using something like <a href="http://code.google.com/p/django-notify/" rel="nofollow">http://code.google.com/p/django-notify/</a> to store session-based data that is displayed to the user following the redirect.</p>
1
2009-09-23T01:26:35Z
[ "python", "django", "http", "redirect" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
1,463,511
<p>The best way would probably be to use a coded querystring on the redirect URL... its an old school approach.</p> <p>You could do something like</p> <p>/page/?m=1, /page/?m=2, etc</p> <p>You would then parse that variable with request.GET in the view code and show the appropriate message.</p>
5
2009-09-23T01:27:14Z
[ "python", "django", "http", "redirect" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
1,463,857
<p>if you are using auth and have a logged in user you could: </p> <p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.message_set.create" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.message_set.create</a></p> <p>GET params are also hackable. Teh querystring, as mentioned in other answers.</p> <p>I think that the most choice way would be to use the sessions framework. That way you can load up whatever you want in the context and get</p> <pre><code>{{ request.session.foo }} </code></pre> <p>could be the message or you could </p> <pre><code>{% ifequal request.session.foo 1 %} Nice work! {% else %} Almost! {% endifequal %} </code></pre> <p>and other fun stuff.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views</a></p>
7
2009-09-23T03:51:39Z
[ "python", "django", "http", "redirect" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
5,735,480
<p>From your views.py you hast have to put a key/value-pair into the session and then read it from the HTML template.</p> <p>For example:</p> <p><strong>views.py</strong></p> <pre><code># your code here request.session['vote'] = 1 return HttpResponseRedirect(request.path) </code></pre> <p><strong>your_template.html</strong></p> <pre><code>{% ifequal request.session.vote 1 %} &lt;!-- Your action here --&gt; {% endifequal %} </code></pre>
0
2011-04-20T19:17:20Z
[ "python", "django", "http", "redirect" ]
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
<p>I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning</p> <pre><code>HttpResponseRedirect(request.path) </code></pre> <p>which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.</p> <p>So how can I pass template context information when using HttpResponseRedirect? </p> <p>What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.</p>
24
2009-09-23T01:19:17Z
11,594,329
<p>For the sake of completion and future reference, you can now use <a href="https://docs.djangoproject.com/en/dev/ref/contrib/messages/">the messages framework</a>. After you install it:</p> <p><strong>views.py</strong></p> <pre><code>from django.contrib import messages def view(request): # your code messages.success(request, "Your data has been saved!") HttpResponseRedirect(request.path) </code></pre> <p><strong>template.html</strong></p> <pre><code>{% if messages %} &lt;ul class="messages"&gt; {% for message in messages %} &lt;li{% if message.tags %} class="{{ message.tags }}"{% endif %}&gt;{{ message }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} </code></pre>
34
2012-07-21T17:25:09Z
[ "python", "django", "http", "redirect" ]
What is the accepted python alternative to C++ overloaded input stream operators?
1,463,499
<p>In C++, you can do this to easily read data into a class:</p> <pre><code>istream&amp; operator &gt;&gt; (istream&amp; instream, SomeClass&amp; someclass) { ... } </code></pre> <p>In python, the only way I can find to read from the console is the "raw_input" function, which isn't very adaptable to this sort of thing. Is there a pythonic way to go about this?</p>
2
2009-09-23T01:24:01Z
1,463,518
<p>You are essentially looking for deserialization. Python has a myriad of options for this depending on the library used. The default is python <a href="http://www.network-theory.co.uk/docs/pytut/pickleModule.html" rel="nofollow">pickling</a>. There are lots of other options you can have a look <a href="http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/" rel="nofollow">here</a>.</p>
6
2009-09-23T01:28:52Z
[ "python", "input", "operator-overloading" ]
What is the accepted python alternative to C++ overloaded input stream operators?
1,463,499
<p>In C++, you can do this to easily read data into a class:</p> <pre><code>istream&amp; operator &gt;&gt; (istream&amp; instream, SomeClass&amp; someclass) { ... } </code></pre> <p>In python, the only way I can find to read from the console is the "raw_input" function, which isn't very adaptable to this sort of thing. Is there a pythonic way to go about this?</p>
2
2009-09-23T01:24:01Z
1,463,539
<p>Rather than use raw_input, you can read from sys.stdin (a file-like object):</p> <pre><code>import sys input_line = sys.stdin.readline() # do something with input_line </code></pre>
2
2009-09-23T01:34:50Z
[ "python", "input", "operator-overloading" ]
What is the accepted python alternative to C++ overloaded input stream operators?
1,463,499
<p>In C++, you can do this to easily read data into a class:</p> <pre><code>istream&amp; operator &gt;&gt; (istream&amp; instream, SomeClass&amp; someclass) { ... } </code></pre> <p>In python, the only way I can find to read from the console is the "raw_input" function, which isn't very adaptable to this sort of thing. Is there a pythonic way to go about this?</p>
2
2009-09-23T01:24:01Z
1,463,950
<p>No, there's no widespread Pythonic convention for "read the next instance of class X from this open input text file". I believe this applies to most languages, including e.g. Java; C++ is kind of the outlier there (and many C++ shops forbid the <code>operator&gt;&gt;</code> use in their local style guides). Serialization (to/from JSON or XML if you need allegedly-human readable text files), suggested by another answer, is one possible approach, but not too hot (no standardized way to serialize completely general class instances to either XML or JSON).</p>
3
2009-09-23T04:26:45Z
[ "python", "input", "operator-overloading" ]
Deploying CherryPy (daemon)
1,463,510
<p>I've followed the basic CherryPy tutorial (<a href="http://www.cherrypy.org/wiki/CherryPyTutorial">http://www.cherrypy.org/wiki/CherryPyTutorial</a>). One thing not discussed is deployment.</p> <p>How can I launch a CherryPy app as a daemon and "forget about it"? What happens if the server reboots?</p> <p>Is there a standard recipe? Maybe something that will create a service script (/etc/init.d/cherrypy...)</p> <p>Thanks!</p>
21
2009-09-23T01:27:13Z
1,463,562
<p>There is a <a href="http://docs.cherrypy.org/stable/refman/process/plugins/daemonizer.html">Daemonizer</a> plugin for CherryPy included by default which is useful for getting it to start but by far the easiest way for simple cases is to use the cherryd script:</p> <pre><code>&gt; cherryd -h Usage: cherryd [options] Options: -h, --help show this help message and exit -c CONFIG, --config=CONFIG specify config file(s) -d run the server as a daemon -e ENVIRONMENT, --environment=ENVIRONMENT apply the given config environment -f start a fastcgi server instead of the default HTTP server -s start a scgi server instead of the default HTTP server -i IMPORTS, --import=IMPORTS specify modules to import -p PIDFILE, --pidfile=PIDFILE store the process id in the given file </code></pre> <p>As far as an init.d script goes I think there are examples that can be Googled.</p> <p>And the <code>cherryd</code> is found in your:</p> <blockquote> <p>virtualenv/lib/python2.7/site-packages/cherrypy/cherryd</p> </blockquote> <p>or in: <a href="https://bitbucket.org/cherrypy/cherrypy/src/default/cherrypy/cherryd">https://bitbucket.org/cherrypy/cherrypy/src/default/cherrypy/cherryd</a></p>
13
2009-09-23T01:44:58Z
[ "python", "deployment", "cherrypy" ]
Deploying CherryPy (daemon)
1,463,510
<p>I've followed the basic CherryPy tutorial (<a href="http://www.cherrypy.org/wiki/CherryPyTutorial">http://www.cherrypy.org/wiki/CherryPyTutorial</a>). One thing not discussed is deployment.</p> <p>How can I launch a CherryPy app as a daemon and "forget about it"? What happens if the server reboots?</p> <p>Is there a standard recipe? Maybe something that will create a service script (/etc/init.d/cherrypy...)</p> <p>Thanks!</p>
21
2009-09-23T01:27:13Z
5,353,332
<p>Daemonizer can be pretty simple to use:</p> <pre><code># this works for cherrypy 3.1.2 on Ubuntu 10.04 from cherrypy.process.plugins import Daemonizer # before mounting anything Daemonizer(cherrypy.engine).subscribe() cherrypy.tree.mount(MyDaemonApp, "/") cherrypy.engine.start() cherrypy.engine.block() </code></pre> <p><a href="https://help.ubuntu.com/community/RcLocalHowto" rel="nofollow">There is a decent HOWTO for SysV style here.</a></p> <p>To summarize:</p> <ol> <li><p>Create a file named for your application in <code>/etc/init.d</code> that calls <code>/bin/sh</code></p> <p><code>sudo vim /etc/init.d/MyDaemonApp</code></p> <pre><code>#!/bin/sh echo "Invoking MyDaemonApp"; /path/to/MyDaemonApp echo "Started MyDaemonApp. Tremble, Ye Mighty." </code></pre></li> <li><p>Make it executable</p> <p><code>sudo chmod +x /etc/init.d/MyDaemonApp</code></p></li> <li><p>Run <code>update-rc.d</code> to create our proper links in the proper runtime dir.</p> <p><code>sudo update-rc.d MyDaemonApp defaults 80</code></p></li> <li><p><code>sudo /etc/init.d/MyDaemonApp</code></p></li> </ol>
10
2011-03-18T14:22:32Z
[ "python", "deployment", "cherrypy" ]
Deploying CherryPy (daemon)
1,463,510
<p>I've followed the basic CherryPy tutorial (<a href="http://www.cherrypy.org/wiki/CherryPyTutorial">http://www.cherrypy.org/wiki/CherryPyTutorial</a>). One thing not discussed is deployment.</p> <p>How can I launch a CherryPy app as a daemon and "forget about it"? What happens if the server reboots?</p> <p>Is there a standard recipe? Maybe something that will create a service script (/etc/init.d/cherrypy...)</p> <p>Thanks!</p>
21
2009-09-23T01:27:13Z
24,467,279
<p>I wrote a tutorial/project skeleton, <a href="https://bitbucket.org/saaj/cherrypy-webapp-skeleton" rel="nofollow">cherrypy-webapp-skeleton</a>, which goal was to fill the gaps for deploying a real-world CherryPy application on Debian* for a web-developer. It features extended <code>cherryd</code> for daemon privilege drop. There's also a number of important script and config files for <code>init.d</code>, <code>nginx</code>, <code>monit</code>, <code>logrotate</code>. The tutorial part describes how to put things together and eventually <em>forget about it</em>. The skeleton part proposes a way of possible arrangement of CherryPy webapp project assets.</p> <hr> <p>* It was written for Squeeze but practically it should be same for Wheezy.</p>
3
2014-06-28T13:27:24Z
[ "python", "deployment", "cherrypy" ]
How can this python function code work?
1,463,588
<p>this is from the source code of csv2rec in matplotlib</p> <p>how can this function work, if its only parameters are 'func, default'?</p> <pre><code>def with_default_value(func, default): def newfunc(name, val): if ismissing(name, val): return default else: return func(val) return newfunc </code></pre> <p>ismissing takes a name and a value and determines if the row should be masked in a numpy array.</p> <p>func will either be str, int, float, or dateparser...it converts data. Maybe not important. I'm just wondering how it can get a 'name' and a 'value'</p> <p>I'm a beginner. Thanks for any 2cents! I hope to get good enough to help others!</p>
6
2009-09-23T01:51:28Z
1,463,598
<p>This is a function that returns another function. <code>name</code> and <code>value</code> are the parameters of the returned function.</p>
0
2009-09-23T01:54:58Z
[ "python", "function", "matplotlib" ]
How can this python function code work?
1,463,588
<p>this is from the source code of csv2rec in matplotlib</p> <p>how can this function work, if its only parameters are 'func, default'?</p> <pre><code>def with_default_value(func, default): def newfunc(name, val): if ismissing(name, val): return default else: return func(val) return newfunc </code></pre> <p>ismissing takes a name and a value and determines if the row should be masked in a numpy array.</p> <p>func will either be str, int, float, or dateparser...it converts data. Maybe not important. I'm just wondering how it can get a 'name' and a 'value'</p> <p>I'm a beginner. Thanks for any 2cents! I hope to get good enough to help others!</p>
6
2009-09-23T01:51:28Z
1,463,600
<p>This is a Python decorator -- basically a function wrapper. (Read all about decorators in PEP 318 -- <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">http://www.python.org/dev/peps/pep-0318/</a>)</p> <p>If you look through the code, you will probably find something like this:</p> <pre><code>def some_func(name, val): # ... some_func = with_default_value(some_func, 'the_default_value') </code></pre> <p>The intention of this decorator seems to supply a default value if either the name or val arguments are missing (presumably, if they are set to None).</p>
6
2009-09-23T01:55:59Z
[ "python", "function", "matplotlib" ]
How can this python function code work?
1,463,588
<p>this is from the source code of csv2rec in matplotlib</p> <p>how can this function work, if its only parameters are 'func, default'?</p> <pre><code>def with_default_value(func, default): def newfunc(name, val): if ismissing(name, val): return default else: return func(val) return newfunc </code></pre> <p>ismissing takes a name and a value and determines if the row should be masked in a numpy array.</p> <p>func will either be str, int, float, or dateparser...it converts data. Maybe not important. I'm just wondering how it can get a 'name' and a 'value'</p> <p>I'm a beginner. Thanks for any 2cents! I hope to get good enough to help others!</p>
6
2009-09-23T01:51:28Z
1,463,612
<p>As for why it works:</p> <p>with_default_value returns a function object, which is basically going to be a <em>copy</em> of that nested newfunc, with the 'func' call and default value substited with whatever was passed to with_default_value.</p> <p>If someone does 'foo = with_default_value(bar, 3)', the return value is basically going to be a new function:</p> <pre><code>def foo(name, val): ifismissing(name, val): return 3 else: return bar(val) </code></pre> <p>so you can then take that return value, and call it. </p>
1
2009-09-23T02:01:41Z
[ "python", "function", "matplotlib" ]
How can this python function code work?
1,463,588
<p>this is from the source code of csv2rec in matplotlib</p> <p>how can this function work, if its only parameters are 'func, default'?</p> <pre><code>def with_default_value(func, default): def newfunc(name, val): if ismissing(name, val): return default else: return func(val) return newfunc </code></pre> <p>ismissing takes a name and a value and determines if the row should be masked in a numpy array.</p> <p>func will either be str, int, float, or dateparser...it converts data. Maybe not important. I'm just wondering how it can get a 'name' and a 'value'</p> <p>I'm a beginner. Thanks for any 2cents! I hope to get good enough to help others!</p>
6
2009-09-23T01:51:28Z
1,463,706
<p>This <code>with_default_value</code> function is what's often referred to (imprecisely) as "a closure" (technically, the closure is rather the <em>inner</em> function that gets returned, here <code>newfunc</code> -- see e.g. <a href="http://en.wikipedia.org/wiki/Closure%5F%28computer%5Fscience%29" rel="nofollow">here</a>). More generically, <code>with_default_value</code> is a <em>higher-order function</em> ("HOF"): it takes a function (<code>func</code>) as an argument, it also returns a function (<code>newfunc</code>) as the result.</p> <p>I've seen answers confusing this with the <em>decorator</em> concept and construct in Python, which is definitely <strong>not</strong> the case -- especially since you mention <code>func</code> as often being a built-in such as <code>int</code>. Decorators are also higher-order functions, but rather specific ones: ones which return a decorated, i.e. "enriched", version of their function argument (which must be the <em>only</em> argument -- "decorators with arguments" are obtained through one more level of function/closure nesting, <em>not</em> by giving the decorator HOF more than one argument), which gets reassigned to exactly the same name as that function argument (and so typically has the same signature -- using a decorator otherwise would be <em>extremely</em> peculiar, un-idiomatic, unreadable, etc).</p> <p>So forget decorators, which have absolutely nothing to do with the case, and focus on the <code>newfunc</code> closure. A lexically nested function can refer to (though not rebind) all local variable names (including argument names, since arguments are local variables) of the enclosing function(s) -- that's why it's known as a closure: it's "closed over" these "free variables". Here, <code>newfunc</code> can refer to <code>func</code> and <code>default</code> -- and does.</p> <p>Higher-order functions are a very natural thing in Python, especially since functions are first-class objects (so there's nothing special you need to do to pass them as arguments, return them as function values, or even storing them in lists or other containers, etc), and there's no namespace distinction between functions and other kinds of objects, no automatic calling of functions just because they're mentioned, etc, etc. (It's harder - a bit harder, or MUCH harder, depending - in other languages that do draw lots of distinctions of this sort). In Python, mentioning a function is just that -- a mention; the CALL only happens if and when the function object (referred to by name, or otherwise) is followed by parentheses.</p> <p>That's about all there is to this example -- please do feel free to edit your question, comment here, etc, if there's some other specific aspect that you remain in doubt about!</p> <p><strong>Edit</strong>: so the OP commented courteously asking for more examples of "closure factories". Here's one -- imagine some abstract kind of GUI toolkit, and you're trying to do:</p> <pre><code>for i in range(len(buttons)): buttons[i].onclick(lambda: mainwin.settitle("button %d click!" % i)) </code></pre> <p>but this doesn't work right -- <code>i</code> within the <code>lambda</code> is late-bound, so by the time one button is clicked <code>i</code>'s value is always going to be the index of the <em>last</em> button, no matter which one was clicked. There are various feasible solutions, but a closure factory's an elegant possibility:</p> <pre><code>def makeOnclick(message): return lambda: mainwin.settitle(message) for i in range(len(buttons)): buttons[i].onclick(makeOnClick("button %d click!" % i)) </code></pre> <p>Here, we're using the closure factory to tweak the binding time of variables!-) In one specific form or another, this is a pretty common use case for closure factories.</p>
8
2009-09-23T02:41:30Z
[ "python", "function", "matplotlib" ]
How do I get this program to start over in python?
1,463,710
<p>I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?</p> <pre><code>from random import randint print 'Good Morning Pete!' X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) count = 0 if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == '10': print 'Time to kill \'em' </code></pre> <p>how do I get it to spit out a new problem for me to solve? I'm a beginner. Thanks all!</p>
-1
2009-09-23T02:44:43Z
1,463,737
<p>A loop? See the <code>for</code> statement and the <code>range()</code> function. They're in the <a href="http://docs.python.org/tutorial/controlflow.html" rel="nofollow">Python tutorial</a>.</p> <p>And you might want to read the next chapter in whatever book you're using to teach yourself programming.</p>
1
2009-09-23T02:57:42Z
[ "python", "recursion" ]
How do I get this program to start over in python?
1,463,710
<p>I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?</p> <pre><code>from random import randint print 'Good Morning Pete!' X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) count = 0 if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == '10': print 'Time to kill \'em' </code></pre> <p>how do I get it to spit out a new problem for me to solve? I'm a beginner. Thanks all!</p>
-1
2009-09-23T02:44:43Z
1,463,740
<p>Pete, you wouldn't need <em>recursion</em> in this case, but merely a <em>loop</em>.</p> <p>I suggest you put the bulk of the logic of this program (the part that asks the multiplcation problem and check your answer), into a function. Say One Problem(). This function could return 0 if you answered wrong, 1 if you answered correctly and -1 if you entered some key indicating that you want to stop. (BTW, this function is introduced to help you structure the program, make it more readeable but it is not needed for introducing a loop. you could well keep all this stuff inside the loop. Also, you should know that there are other loop constructs in python, for exampe while loops.)</p> <p>Then you'd just need in your main section something like that :</p> <pre><code>GoodReplyCtr = 0 for i in range(0, 10): # or 100 or 1000 if you feel ambitious... cc = OneProblem() if cc &lt; 0: break GoodReplyCtr += cc print(GoodReplyCtr) </code></pre> <p>The concept of recursion (again not needed here), is when a function calls itself. This is a common practice when navigating graphs (like say the directory structure on you drive C:), or with some mathematical problems. We typically do not need to cover recursion early in the learning of computer languages concepts, but once you have a good mastery of things, you may find it quite useful (and challenging at time ;-) )</p> <p>Keep at it! Math and python are cool.</p> <p><strong>Edit</strong>: One last trick:</p> <p>You may find that you need to work on some multiplication tables more than other. Rather than using randint you can use the random's module random.choice() method to favor some numbers or to eliminate others. for example</p> <pre><code>import random X = random.choice((2, 3, 4, 6, 7, 8, 9, 7, 9)) # see, no 0, 1,or 5 but more chance to get 7 or 9 </code></pre>
3
2009-09-23T02:58:09Z
[ "python", "recursion" ]
How do I get this program to start over in python?
1,463,710
<p>I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?</p> <pre><code>from random import randint print 'Good Morning Pete!' X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) count = 0 if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == '10': print 'Time to kill \'em' </code></pre> <p>how do I get it to spit out a new problem for me to solve? I'm a beginner. Thanks all!</p>
-1
2009-09-23T02:44:43Z
1,463,799
<p>to incorporate the loop, you might add this to the beginning of your code:</p> <p>running = True while True: //Add your code here</p> <pre><code>//Add this to the end of your code: print 'Another problem? Enter y or n' answer = raw_input().lower() if answer == 'n': running = False break elif answer == 'y': running = True </code></pre> <p><hr /></p> <p>this will allow the user to choose if they want another problem each time.</p>
0
2009-09-23T03:20:05Z
[ "python", "recursion" ]
How do I get this program to start over in python?
1,463,710
<p>I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?</p> <pre><code>from random import randint print 'Good Morning Pete!' X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) count = 0 if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == '10': print 'Time to kill \'em' </code></pre> <p>how do I get it to spit out a new problem for me to solve? I'm a beginner. Thanks all!</p>
-1
2009-09-23T02:44:43Z
1,463,803
<p>I agree 100% with those who said this isn't a good case for recursion, but calls for a loop instead. However, for the sake of showing how it might be done, I post the code below:</p> <pre><code>import random def do_mult(num_questions): x = random.randint(0, 10) y = random.randint(0, 10) a = x * y z = int(raw_input('%i * %i = ?' % (x, y))) if z == a: print 'good job!' else: print 'sorry!' if num_questions &gt; 1: do_mult(num_questions - 1) do_mult(10) </code></pre>
0
2009-09-23T03:22:47Z
[ "python", "recursion" ]
How do I get this program to start over in python?
1,463,710
<p>I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?</p> <pre><code>from random import randint print 'Good Morning Pete!' X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) count = 0 if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == '10': print 'Time to kill \'em' </code></pre> <p>how do I get it to spit out a new problem for me to solve? I'm a beginner. Thanks all!</p>
-1
2009-09-23T02:44:43Z
1,463,815
<p>I believe you want something like this</p> <pre><code>from random import randint print 'Good Morning Pete!' count = 0 while True: X = randint(0, 10) Y = randint(0, 10) A = X * Y Z = int(raw_input('%i * %i = ? ' % (X, Y))) if Z == A: count += 1 print 'Good Job!' else: print 'Sorry!' if count == 10: print 'Time to kill \'em' break </code></pre>
2
2009-09-23T03:29:11Z
[ "python", "recursion" ]
Calculate brute force size dynamically?
1,463,832
<p>How you could calculate size of brute force method dynamically? For example how many iterations and space would take if you printed all IPv6 addresses from 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff to file? The tricky parts are those when length of line varies. IP address is only example. </p> <p>Idea is that you give the format and maximum lenghts of given parts. So if variable type is '%c' (char), and maxlen is 26 then iteration count is 26 and needed space in human format in text file is 26 + 26 (one char for separator)</p> <pre><code>def calculate(format, rules): end = format for i in rules: (vartype, maxlen) = rules[i] end = end.replace(i, vartype % maxlen) start = format for i in rules: (vartype, maxlen) = rules[i] minlen = 0 start = start.replace(i, vartype % minlen) start_bytes = len(start) end_bytes = len(end) # how to add for example IPv4 calculations # 0.0.0.0 - 9.9.9.9 # 10.10.10.10 - 99.99.99.99 # 100.100.100.100 - 255.255.255.255 iterations = 0 for i in rules: if format.find(i) is not -1: (vartype, maxlen) = rules[i] if iterations == 0: iterations = int(maxlen) + 1 else: iterations *= int(maxlen) + 1 iterations -= 1 needed_space = 0 if start_bytes == end_bytes: # +1 for separator (space / new line) needed_space = (1 + start_bytes) * iterations else: needed_space = "How to calculate?" return [iterations, needed_space, start, end, start_bytes, end_bytes] if __name__ == '__main__': # IPv4 print calculate( "%a.%b.%c.%d", { '%a': ['%d', 255], '%b': ['%d', 255], '%c': ['%d', 255], '%d': ['%d', 255] }, ) # IPv4 zero filled version print calculate( "%a.%b.%c.%d", { '%a': ['%03d', 255], '%b': ['%03d', 255], '%c': ['%03d', 255], '%d': ['%03d', 255] }, ) # IPv6 print calculate( "%a:%b:%c:%d:%e:%f:%g:%h", { '%a': ['%x', 65535], '%b': ['%x', 65535], '%c': ['%x', 65535], '%d': ['%x', 65535], '%e': ['%x', 65535], '%f': ['%x', 65535], '%g': ['%x', 65535], '%h': ['%x', 65535] }, ) # days in year, simulate with day numbers print calculate( "ddm%a", #ddmmyy { '%a': ['%03d', 365], }, ) </code></pre> <p>So for example:</p> <ul> <li>1.2.3.4 takes 7 bytes</li> <li>9.9.9.10 takes 8 bytes</li> <li>1.1.1.100 takes 9 bytes</li> <li>5.7.10.100 takes 10 bytes</li> <li>128.1.1.1 takes 9 bytes</li> <li>and so on</li> </ul> <p><hr /></p> <p>Example 0.0.0.0 - 10.10.10.10:</p> <pre><code> iterations = 0 needed_space = 0 for a in range(0, 11): for b in range(0, 11): for c in range(0, 11): for d in range(0, 11): line = "%d.%d.%d.%d\n" % (a, b, c, d) needed_space += len(line) iterations += 1 print "iterations: %d needed_space: %d bytes" % (iterations, needed_space) </code></pre> <p>iterations: 14641 needed_space: 122452 bytes</p> <p>Into</p> <pre><code> print calculate( "%a.%b.%c.%d", { '%a': ['%d', 10], '%b': ['%d', 10], '%c': ['%d', 10], '%d': ['%d', 10] }, ) </code></pre> <p>Result: [14641, 122452]</p>
0
2009-09-23T03:34:31Z
1,463,899
<p>Using <a href="http://en.wikipedia.org/wiki/Combinatorics" rel="nofollow">combinatorics</a> and discrete math:</p> <p>The IPv4 address space is 256<code>*</code>256<code>*</code>256<code>*</code>256 = 2^32 = 4,294,967,296 addresses.</p> <p>IPv6 has 2^128 addresses (8 groups of 16<code>*</code>16<code>*</code>16<code>*</code>16).</p> <p>An IPv4 address use 32 bits, so 32 bits * 4,294,967,296 addresses = <strong><a href="http://www.google.com/search?rlz=1C1GGLS%5FenUS291US303&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=32+bits+%2A+4,294,967,296+in+gigabytes" rel="nofollow">16 gigabytes</a></strong> if stored e.g. on disk.</p> <p>An IPv6 address uses 128 bits, so 128 bits * 2^128 addresses = <strong><a href="http://www.google.com/search?hl=en&amp;rlz=1C1GGLS%5FenUS291US303&amp;q=128+bits+%2A+%2816%2A16%2A16%2A16%29%2A%2A8+in+gigabytes&amp;aq=f&amp;oq=&amp;aqi=" rel="nofollow">5.07 * 10^30 gigabytes</a></strong>.</p>
4
2009-09-23T04:08:43Z
[ "python", "math", "brute-force" ]
Calculate brute force size dynamically?
1,463,832
<p>How you could calculate size of brute force method dynamically? For example how many iterations and space would take if you printed all IPv6 addresses from 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff to file? The tricky parts are those when length of line varies. IP address is only example. </p> <p>Idea is that you give the format and maximum lenghts of given parts. So if variable type is '%c' (char), and maxlen is 26 then iteration count is 26 and needed space in human format in text file is 26 + 26 (one char for separator)</p> <pre><code>def calculate(format, rules): end = format for i in rules: (vartype, maxlen) = rules[i] end = end.replace(i, vartype % maxlen) start = format for i in rules: (vartype, maxlen) = rules[i] minlen = 0 start = start.replace(i, vartype % minlen) start_bytes = len(start) end_bytes = len(end) # how to add for example IPv4 calculations # 0.0.0.0 - 9.9.9.9 # 10.10.10.10 - 99.99.99.99 # 100.100.100.100 - 255.255.255.255 iterations = 0 for i in rules: if format.find(i) is not -1: (vartype, maxlen) = rules[i] if iterations == 0: iterations = int(maxlen) + 1 else: iterations *= int(maxlen) + 1 iterations -= 1 needed_space = 0 if start_bytes == end_bytes: # +1 for separator (space / new line) needed_space = (1 + start_bytes) * iterations else: needed_space = "How to calculate?" return [iterations, needed_space, start, end, start_bytes, end_bytes] if __name__ == '__main__': # IPv4 print calculate( "%a.%b.%c.%d", { '%a': ['%d', 255], '%b': ['%d', 255], '%c': ['%d', 255], '%d': ['%d', 255] }, ) # IPv4 zero filled version print calculate( "%a.%b.%c.%d", { '%a': ['%03d', 255], '%b': ['%03d', 255], '%c': ['%03d', 255], '%d': ['%03d', 255] }, ) # IPv6 print calculate( "%a:%b:%c:%d:%e:%f:%g:%h", { '%a': ['%x', 65535], '%b': ['%x', 65535], '%c': ['%x', 65535], '%d': ['%x', 65535], '%e': ['%x', 65535], '%f': ['%x', 65535], '%g': ['%x', 65535], '%h': ['%x', 65535] }, ) # days in year, simulate with day numbers print calculate( "ddm%a", #ddmmyy { '%a': ['%03d', 365], }, ) </code></pre> <p>So for example:</p> <ul> <li>1.2.3.4 takes 7 bytes</li> <li>9.9.9.10 takes 8 bytes</li> <li>1.1.1.100 takes 9 bytes</li> <li>5.7.10.100 takes 10 bytes</li> <li>128.1.1.1 takes 9 bytes</li> <li>and so on</li> </ul> <p><hr /></p> <p>Example 0.0.0.0 - 10.10.10.10:</p> <pre><code> iterations = 0 needed_space = 0 for a in range(0, 11): for b in range(0, 11): for c in range(0, 11): for d in range(0, 11): line = "%d.%d.%d.%d\n" % (a, b, c, d) needed_space += len(line) iterations += 1 print "iterations: %d needed_space: %d bytes" % (iterations, needed_space) </code></pre> <p>iterations: 14641 needed_space: 122452 bytes</p> <p>Into</p> <pre><code> print calculate( "%a.%b.%c.%d", { '%a': ['%d', 10], '%b': ['%d', 10], '%c': ['%d', 10], '%d': ['%d', 10] }, ) </code></pre> <p>Result: [14641, 122452]</p>
0
2009-09-23T03:34:31Z
1,463,926
<p>First start by counting the number of lines you need. IPv6 addresses are 128 bits, so your output file will be 2<sup>128</sup> lines long. That's roughly 3.4 &times; 10<sup>38</sup> bytes, if all your lines are <em>empty</em>. A terabyte is only about 10<sup>12</sup> bytes, so you would need over 3 &times; 10<sup>26</sup> 1-terabyte hard drives just to store the <em>empty</em> lines before putting any data in them.</p> <p>Storing 40 bytes per line would require proportionally more storage. </p>
0
2009-09-23T04:17:40Z
[ "python", "math", "brute-force" ]
Calculate brute force size dynamically?
1,463,832
<p>How you could calculate size of brute force method dynamically? For example how many iterations and space would take if you printed all IPv6 addresses from 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff to file? The tricky parts are those when length of line varies. IP address is only example. </p> <p>Idea is that you give the format and maximum lenghts of given parts. So if variable type is '%c' (char), and maxlen is 26 then iteration count is 26 and needed space in human format in text file is 26 + 26 (one char for separator)</p> <pre><code>def calculate(format, rules): end = format for i in rules: (vartype, maxlen) = rules[i] end = end.replace(i, vartype % maxlen) start = format for i in rules: (vartype, maxlen) = rules[i] minlen = 0 start = start.replace(i, vartype % minlen) start_bytes = len(start) end_bytes = len(end) # how to add for example IPv4 calculations # 0.0.0.0 - 9.9.9.9 # 10.10.10.10 - 99.99.99.99 # 100.100.100.100 - 255.255.255.255 iterations = 0 for i in rules: if format.find(i) is not -1: (vartype, maxlen) = rules[i] if iterations == 0: iterations = int(maxlen) + 1 else: iterations *= int(maxlen) + 1 iterations -= 1 needed_space = 0 if start_bytes == end_bytes: # +1 for separator (space / new line) needed_space = (1 + start_bytes) * iterations else: needed_space = "How to calculate?" return [iterations, needed_space, start, end, start_bytes, end_bytes] if __name__ == '__main__': # IPv4 print calculate( "%a.%b.%c.%d", { '%a': ['%d', 255], '%b': ['%d', 255], '%c': ['%d', 255], '%d': ['%d', 255] }, ) # IPv4 zero filled version print calculate( "%a.%b.%c.%d", { '%a': ['%03d', 255], '%b': ['%03d', 255], '%c': ['%03d', 255], '%d': ['%03d', 255] }, ) # IPv6 print calculate( "%a:%b:%c:%d:%e:%f:%g:%h", { '%a': ['%x', 65535], '%b': ['%x', 65535], '%c': ['%x', 65535], '%d': ['%x', 65535], '%e': ['%x', 65535], '%f': ['%x', 65535], '%g': ['%x', 65535], '%h': ['%x', 65535] }, ) # days in year, simulate with day numbers print calculate( "ddm%a", #ddmmyy { '%a': ['%03d', 365], }, ) </code></pre> <p>So for example:</p> <ul> <li>1.2.3.4 takes 7 bytes</li> <li>9.9.9.10 takes 8 bytes</li> <li>1.1.1.100 takes 9 bytes</li> <li>5.7.10.100 takes 10 bytes</li> <li>128.1.1.1 takes 9 bytes</li> <li>and so on</li> </ul> <p><hr /></p> <p>Example 0.0.0.0 - 10.10.10.10:</p> <pre><code> iterations = 0 needed_space = 0 for a in range(0, 11): for b in range(0, 11): for c in range(0, 11): for d in range(0, 11): line = "%d.%d.%d.%d\n" % (a, b, c, d) needed_space += len(line) iterations += 1 print "iterations: %d needed_space: %d bytes" % (iterations, needed_space) </code></pre> <p>iterations: 14641 needed_space: 122452 bytes</p> <p>Into</p> <pre><code> print calculate( "%a.%b.%c.%d", { '%a': ['%d', 10], '%b': ['%d', 10], '%c': ['%d', 10], '%d': ['%d', 10] }, ) </code></pre> <p>Result: [14641, 122452]</p>
0
2009-09-23T03:34:31Z
1,463,953
<p>Breaking it up into components is probably the way to go; for IPv4 you've got four parts, separated by three dots, and each part can be 1, 2 or 3 characters (0-9, 10-99, 100-255) long. So your combinations are:</p> <pre><code>comp_length = {1: 10, 2: 90, 3: 156} </code></pre> <p>You can work out the total lengths by iterating through each combo:</p> <pre><code>def ipv4_comp_length(n=4): if n == 1: return comp_length res = {} for rest, restcnt in ipv4_comp_length(n-1).iteritems(): for first, firstcnt in comp_length.iteritems(): l = first + 1 + rest # "10" + "." + "0.0.127" res[l] = res.get(l,0) + (firstcnt * restcnt) return res print sum( l*c for l,c in ipv4_comp_length().iteritems() ) </code></pre> <p>Note that this doesn't take record separators into account (the space in "1.2.3.4 1.2.3.5").</p> <p>Extending to IPv6 should be mostly straightforward -- unless you want to cope with abbreviated IPv6 addresses like 0::0 == 0:0:0:0:0:0:0:0.</p>
0
2009-09-23T04:27:32Z
[ "python", "math", "brute-force" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,037
<p>You can use <a href="http://docs.python.org/library/functions.html?highlight=isinstance#isinstance" rel="nofollow"><code>isinstance</code></a> to check a variables type:</p> <pre><code>if isinstance(param, list): # it is a list print len(list) </code></pre>
1
2009-09-23T04:57:15Z
[ "python", "list" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,038
<p>Just use the type method? Or am I misinterpreting the question</p> <pre><code>if type(objectname) is list: do something else: do something else :P </code></pre>
-3
2009-09-23T04:57:28Z
[ "python", "list" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,049
<p>You don't.</p> <p><em>This works only for Python >= 2.6. If you're targeting anything below use <a href="http://stackoverflow.com/questions/1464028/what-is-the-pythonic-way-of-checking-if-an-object-is-a-list/">Alex' solution</a>.</em></p> <p>Python supports something called <a href="http://docs.python.org/glossary.html#term-duck-typing" rel="nofollow" title="If it looks like a duck and quacks like a duck, it must be a duck.">Duck Typing</a>. You can look for certain functionality using the <a href="http://www.python.org/dev/peps/pep-3119/" rel="nofollow">ABC classes</a>.</p> <pre><code>import collections def mymethod(myvar): # collections.Sqeuence to check for list capabilities # collections.Iterable to check for iterator capabilities if not isinstance(myvar, collections.Iterable): raise TypeError() </code></pre>
11
2009-09-23T05:00:23Z
[ "python", "list" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,050
<pre><code>if isinstance(your_object, list): print("your object is a list!") </code></pre> <p>This is more Pythonic than checking with type.</p> <p>Seems faster too:</p> <pre><code>&gt;&gt;&gt; timeit('isinstance(x, list)', 'x = [1, 2, 3, 4]') 0.40161490440368652 &gt;&gt;&gt; timeit('type(x) is list', 'x = [1, 2, 3, 4]') 0.46065497398376465 &gt;&gt;&gt; </code></pre>
13
2009-09-23T05:00:29Z
[ "python", "list" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,089
<p>In such situations, you normally need to check for ANY iterable, not just lists -- if you're accepting lists OR numbers, rejecting (e.g) a tuple would be weird. The one kind of iterable you might want to treat as a "scalar" is a string -- in Python 2.*, this means <code>str</code> or <code>unicode</code>. So, either:</p> <pre><code>def isNonStringIterable(x): if isinstance(x, basestring): return False try: iter(x) except: return False else: return True </code></pre> <p>or, usually much handier:</p> <pre><code>def makeNonStringIterable(x): if isinstance(x, basestring): return (x,) try: return iter(x) except: return (x,) </code></pre> <p>where you just go <code>for i in makeNonStringIterable(x): ...</code></p>
21
2009-09-23T05:17:53Z
[ "python", "list" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,124
<p>I don't want to be a pest, BUT: Are you sure the query set/object is a good interface? Make two functions, like:</p> <pre><code>def fobject(i): # do something def fqueryset(q): for obj in q: fobject( obj ) </code></pre> <p>Might not be the <em>pythonic</em> way to discern an int from a list, but seems a far better design to me.</p> <p><strong>Reason being</strong>: Your function should be working on ducks. As long as it quacks, whack it. Actually picking the duck up, turning it upside down to check the markings on the belly before choosing the right club to whack it is <em>unpythonic</em>. Sorry. Just don't go there.</p>
2
2009-09-23T05:34:58Z
[ "python", "list" ]
What is the pythonic way of checking if an object is a list?
1,464,028
<p>I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]</p> <p>Edit:</p> <p>I seem to have started a war of words down below by not giving enough info. For completeness let me provide more details so that I may pick and get the best answer for my situation:</p> <p>I'm running Django on Python 2.6 and I'm writing a function that may take in a Django model instance or a queryset object and perform operations on it one of which involves using the filter 'in' that requires a list (the queryset input), or alternately if it is not a list then I would use the 'get' filter (the django get filter).</p>
10
2009-09-23T04:54:10Z
1,464,235
<p>I think the way OP is doing, checking if it supports what he wants, is ok.</p> <p>Simpler way in this scenario would be to not check for list which can be of many types depending on definition, you may check if input is number, do something on it else try to use it as list if that throws exception bail out.</p> <p>e.g you may not want iterate over list but just wanted to append something to it if it is list else add to it</p> <pre><code>def add2(o): try: o.append(2) except AttributeError: o += 2 l=[] n=1 s="" add2(l) add2(n) add2(s) # will throw exception, let the user take care of that ;) </code></pre> <p>So bottom line is answer may vary depending on what you want to do with object</p>
0
2009-09-23T06:16:57Z
[ "python", "list" ]
Pyqt - QMenu dynamically populated and clicked
1,464,548
<p>I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation.</p> <pre><code>def populateShotInfoMenus(self): self.menuFilms = QMenu() films = self.getList() for film in films: menuItem_Film = self.menuFilms.addAction(film) self.connect(menuItem_Film, SIGNAL('triggered()'), self.onFilmSet) self.menuFilms.addAction(menuItem_Film) def onFilmRightClick(self, value): self.menuFilms.exec_(self.group1_inputFilm.mapToGlobal(value)) def onFilmSet(self, value): print 'Menu Clicked ', value </code></pre>
3
2009-09-23T07:53:24Z
1,464,589
<p>Instead of using <code>onFilmSet</code> directly as the receiver of your connection, use a lambda function so you can pass additional parameters:</p> <pre><code>receiver = lambda film=film: self.onFilmSet(self, film) self.connect(menuItem_Film, SIGNAL('triggered()'), receiver) </code></pre>
9
2009-09-23T08:01:51Z
[ "python", "user-interface", "qt", "pyqt" ]
Pyqt - QMenu dynamically populated and clicked
1,464,548
<p>I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation.</p> <pre><code>def populateShotInfoMenus(self): self.menuFilms = QMenu() films = self.getList() for film in films: menuItem_Film = self.menuFilms.addAction(film) self.connect(menuItem_Film, SIGNAL('triggered()'), self.onFilmSet) self.menuFilms.addAction(menuItem_Film) def onFilmRightClick(self, value): self.menuFilms.exec_(self.group1_inputFilm.mapToGlobal(value)) def onFilmSet(self, value): print 'Menu Clicked ', value </code></pre>
3
2009-09-23T07:53:24Z
1,464,602
<p>Take a look at the Qt's property system. You can dynamically add a property containing a string or anything you desire, which defines the action. Then you can use sender() method in the slot to obtain the QObject calling the slot. Then, query the property you set and do whatever you want accordingly.</p> <p>But, this is not the best method to do this. Using sender() is not advised because it violates the object oriented principle of modularity.</p> <p>The best method would be using QSignalMapper class. This class maps signals from different objects to the same slot with different arguments.</p> <p>I haven't used PyQt therefore i cannot give you exact syntax or an example, but it shouldn't be hard to find with a little research.</p>
1
2009-09-23T08:03:54Z
[ "python", "user-interface", "qt", "pyqt" ]
Pyqt - QMenu dynamically populated and clicked
1,464,548
<p>I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation.</p> <pre><code>def populateShotInfoMenus(self): self.menuFilms = QMenu() films = self.getList() for film in films: menuItem_Film = self.menuFilms.addAction(film) self.connect(menuItem_Film, SIGNAL('triggered()'), self.onFilmSet) self.menuFilms.addAction(menuItem_Film) def onFilmRightClick(self, value): self.menuFilms.exec_(self.group1_inputFilm.mapToGlobal(value)) def onFilmSet(self, value): print 'Menu Clicked ', value </code></pre>
3
2009-09-23T07:53:24Z
4,703,668
<p>I was trying to figure out a similar issue and after looking at the code above this is what worked for me. Thought it would be good to show it all together. =)</p> <pre><code>self.taskMenu = QtGui.QMenu("Task") self.tasks = self.getTasks() #FETCHES A LIST OF LIST self.menuTasks = QtGui.QMenu() for item in self.tasks: menuItem_Task = self.taskMenu.addAction(item[1]) receiver = lambda taskType=item[0]: self.setTask(taskType) self.connect(menuItem_Task, QtCore.SIGNAL('triggered()'), receiver) self.taskMenu.addAction(menuItem_Task) def setTask(self,taskType): print taskType </code></pre>
1
2011-01-16T03:41:19Z
[ "python", "user-interface", "qt", "pyqt" ]
Pyqt - QMenu dynamically populated and clicked
1,464,548
<p>I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation.</p> <pre><code>def populateShotInfoMenus(self): self.menuFilms = QMenu() films = self.getList() for film in films: menuItem_Film = self.menuFilms.addAction(film) self.connect(menuItem_Film, SIGNAL('triggered()'), self.onFilmSet) self.menuFilms.addAction(menuItem_Film) def onFilmRightClick(self, value): self.menuFilms.exec_(self.group1_inputFilm.mapToGlobal(value)) def onFilmSet(self, value): print 'Menu Clicked ', value </code></pre>
3
2009-09-23T07:53:24Z
15,099,818
<p>Just some additional information, I don't know why, but lambda function doesn't work with new pyqt syntax for connections :</p> <p>Example of code not working :</p> <pre><code> self.contextTreeMenuAssignTo = QtGui.QMenu(self) actionAssign = contextMenu.addMenu( self.contextTreeMenuAssignTo ) actionAssign.setText("Assign to : ") for user in self.whoCanBeAssignated() : actionAssignTo = QtGui.QAction( user[0] ,self) self.contextTreeMenuAssignTo.addAction( actionAssignTo ) actionAssignTo.triggered.connect( lambda userID = user[1] : self.assignAllTo( userID ) ) </code></pre> <p>But if you subsitute the last line with the old style connection syntax :</p> <pre><code>self.connect(actionAssignTo, QtCore.SIGNAL('triggered()'), lambda userID = user[1] : self.assignAllTo( userID ) ) </code></pre> <p>Everything is fine. With the new connection syntax, you only get the last element of the loop :(</p>
1
2013-02-26T21:37:56Z
[ "python", "user-interface", "qt", "pyqt" ]
Pyqt - QMenu dynamically populated and clicked
1,464,548
<p>I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation.</p> <pre><code>def populateShotInfoMenus(self): self.menuFilms = QMenu() films = self.getList() for film in films: menuItem_Film = self.menuFilms.addAction(film) self.connect(menuItem_Film, SIGNAL('triggered()'), self.onFilmSet) self.menuFilms.addAction(menuItem_Film) def onFilmRightClick(self, value): self.menuFilms.exec_(self.group1_inputFilm.mapToGlobal(value)) def onFilmSet(self, value): print 'Menu Clicked ', value </code></pre>
3
2009-09-23T07:53:24Z
35,053,109
<p>I found <a href="http://stackoverflow.com/questions/28319889/pyqt5-whats-this-boolean-passed-when-a-menu-action-is-triggered">this</a> answer here for dealing with this issue in PyQt5, python3. I don't like it, the bVal variable to be precise, as I don't fully understand it but it took a long time to find so I thought I'd share it here. The bVal picks up the boolean value from triggered and allows the taskType to be passed.</p> <pre><code>self.taskMenu = QtGui.QMenu("Task") self.tasks = self.getTasks() #FETCHES A LIST OF LIST self.menuTasks = QtGui.QMenu() for item in self.tasks: menuItem_Task = self.taskMenu.addAction(item[1]) receiver = lambda: bVal, taskType=item: self.setTask(bVal, taskType) menuItem_Task.triggered.connect(receiver) self.taskMenu.addAction(menuItem_Task) def setTask(self, ignore_bVal, taskType): print taskType </code></pre>
0
2016-01-28T04:51:48Z
[ "python", "user-interface", "qt", "pyqt" ]
internal server error (500) in simple cgi script
1,464,728
<p>I am trying to run a simple cgi script after configuring my server.</p> <p>My script looks like this:</p> <pre><code>print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;&lt;title&gt;CGI&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;" print "hello cgi" print "&lt;/body&gt;" print "&lt;/html&gt;" </code></pre> <p>When I go to my scripts url <code>http://127.0.0.1/~flybywire/cgi-bin/main.py</code> I get:</p> <p><strong>Internal Server Error</strong></p> <p><strong>The server encountered an internal error or misconfiguration and was unable to complete your request.</strong></p> <p>And in <code>error.log</code> I get the following:</p> <p><code> [error] (8)Exec format error: exec of '/home/flybywire/www/cgi-bin/main.py' failed [error] [client 127.0.0.1] Premature end of script headers: main.py </code></p> <p><strong>Other info:</strong> <code>Apache/2.2.8 (Ubuntu) DAV/2 SVN/1.4.6 Server at 127.0.0.1 Port 80</code></p>
7
2009-09-23T08:33:52Z
1,464,762
<p>You might need a <code>#!/usr/bin/python</code> at the top of your script to tell Apache to use Python to execute it. At least, I did that and it worked for me :-) .</p>
18
2009-09-23T08:44:12Z
[ "python", "apache", "cgi" ]
internal server error (500) in simple cgi script
1,464,728
<p>I am trying to run a simple cgi script after configuring my server.</p> <p>My script looks like this:</p> <pre><code>print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;&lt;title&gt;CGI&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;" print "hello cgi" print "&lt;/body&gt;" print "&lt;/html&gt;" </code></pre> <p>When I go to my scripts url <code>http://127.0.0.1/~flybywire/cgi-bin/main.py</code> I get:</p> <p><strong>Internal Server Error</strong></p> <p><strong>The server encountered an internal error or misconfiguration and was unable to complete your request.</strong></p> <p>And in <code>error.log</code> I get the following:</p> <p><code> [error] (8)Exec format error: exec of '/home/flybywire/www/cgi-bin/main.py' failed [error] [client 127.0.0.1] Premature end of script headers: main.py </code></p> <p><strong>Other info:</strong> <code>Apache/2.2.8 (Ubuntu) DAV/2 SVN/1.4.6 Server at 127.0.0.1 Port 80</code></p>
7
2009-09-23T08:33:52Z
1,464,770
<p>It looks like Apache has trouble executing it. Typically for a unix script you also need to specify the interpreter at the top of the script.</p> <p>Try adding this to the top:</p> <pre><code>#!/usr/bin/python </code></pre>
0
2009-09-23T08:45:40Z
[ "python", "apache", "cgi" ]
internal server error (500) in simple cgi script
1,464,728
<p>I am trying to run a simple cgi script after configuring my server.</p> <p>My script looks like this:</p> <pre><code>print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;&lt;title&gt;CGI&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;" print "hello cgi" print "&lt;/body&gt;" print "&lt;/html&gt;" </code></pre> <p>When I go to my scripts url <code>http://127.0.0.1/~flybywire/cgi-bin/main.py</code> I get:</p> <p><strong>Internal Server Error</strong></p> <p><strong>The server encountered an internal error or misconfiguration and was unable to complete your request.</strong></p> <p>And in <code>error.log</code> I get the following:</p> <p><code> [error] (8)Exec format error: exec of '/home/flybywire/www/cgi-bin/main.py' failed [error] [client 127.0.0.1] Premature end of script headers: main.py </code></p> <p><strong>Other info:</strong> <code>Apache/2.2.8 (Ubuntu) DAV/2 SVN/1.4.6 Server at 127.0.0.1 Port 80</code></p>
7
2009-09-23T08:33:52Z
1,464,804
<p>Also, save the file (if this is a Linux server) with Unix line endings. You did make it executable using <code>chmod +x</code> didn't you?</p> <p>You can use <code>#!/usr/bin/env python</code> to cover the current running Python version if you're running in various environments (hence the <code>env</code> part).</p>
8
2009-09-23T08:53:14Z
[ "python", "apache", "cgi" ]
internal server error (500) in simple cgi script
1,464,728
<p>I am trying to run a simple cgi script after configuring my server.</p> <p>My script looks like this:</p> <pre><code>print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;&lt;title&gt;CGI&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;" print "hello cgi" print "&lt;/body&gt;" print "&lt;/html&gt;" </code></pre> <p>When I go to my scripts url <code>http://127.0.0.1/~flybywire/cgi-bin/main.py</code> I get:</p> <p><strong>Internal Server Error</strong></p> <p><strong>The server encountered an internal error or misconfiguration and was unable to complete your request.</strong></p> <p>And in <code>error.log</code> I get the following:</p> <p><code> [error] (8)Exec format error: exec of '/home/flybywire/www/cgi-bin/main.py' failed [error] [client 127.0.0.1] Premature end of script headers: main.py </code></p> <p><strong>Other info:</strong> <code>Apache/2.2.8 (Ubuntu) DAV/2 SVN/1.4.6 Server at 127.0.0.1 Port 80</code></p>
7
2009-09-23T08:33:52Z
4,127,033
<p>Putting</p> <pre><code>#!/usr/bin/env python </code></pre> <p>on the top of the script works fine. I put it on top, but Netbeans was putting extra code (import commands) by itself on the top of the page which drove me crazy :(</p>
1
2010-11-08T19:01:36Z
[ "python", "apache", "cgi" ]
internal server error (500) in simple cgi script
1,464,728
<p>I am trying to run a simple cgi script after configuring my server.</p> <p>My script looks like this:</p> <pre><code>print "Content-type: text/html" print print "&lt;html&gt;&lt;head&gt;&lt;title&gt;CGI&lt;/title&gt;&lt;/head&gt;" print "&lt;body&gt;" print "hello cgi" print "&lt;/body&gt;" print "&lt;/html&gt;" </code></pre> <p>When I go to my scripts url <code>http://127.0.0.1/~flybywire/cgi-bin/main.py</code> I get:</p> <p><strong>Internal Server Error</strong></p> <p><strong>The server encountered an internal error or misconfiguration and was unable to complete your request.</strong></p> <p>And in <code>error.log</code> I get the following:</p> <p><code> [error] (8)Exec format error: exec of '/home/flybywire/www/cgi-bin/main.py' failed [error] [client 127.0.0.1] Premature end of script headers: main.py </code></p> <p><strong>Other info:</strong> <code>Apache/2.2.8 (Ubuntu) DAV/2 SVN/1.4.6 Server at 127.0.0.1 Port 80</code></p>
7
2009-09-23T08:33:52Z
37,512,768
<p>Maybe your problem is that new python version needs parentheses ( ). </p> <p>So your:</p> <pre><code>print "&lt;body&gt;" </code></pre> <p>Now should to be:</p> <pre><code>print ("&lt;body&gt;") </code></pre>
0
2016-05-29T17:15:40Z
[ "python", "apache", "cgi" ]
Windows impersonation for WMI calls via python?
1,464,894
<p>I'm using PyWin32 to make WMI calls to the system in python from my django web application. My goal is to allow users to add printers to the system via a web interface. To do this, I'm using win32print.AddPrinterConnection.</p> <p>This works well running the development server under my user account. I can add all the printers I want. However, eventually, this will need to run under apache which runs as the LocalSystem account.</p> <p>This is problematic for two reasons:</p> <ol> <li>The LocalSystem account has no network privileges at all, and this is a network printer. The AddPrinterConnection WMI call eventually makes a COM call that will be disallowed.</li> <li>The LocalSystem account has no access to the domain these printers are on. They require a domain account to access.</li> </ol> <p>Therefore, I've come to the conclusion that I need to impersonate domain user(s) to accomplish this task. I've done so using the code found here:</p> <p><a href="http://code.activestate.com/recipes/81402/" rel="nofollow">http://code.activestate.com/recipes/81402/</a></p> <p>This seems to work as I'm able to verify that I've successfully impersonated the calling code. Unfortunately, after impersonation I always get this error from the win32print.AddPrinterConnection API call:</p> <pre><code>Exception Type: error Exception Value: (2, 'AddPrinterConnection', 'The system cannot find the file specified.') </code></pre> <p>Do you have any idea why this may be?</p> <p>Thanks a bunch! Pete</p> <p><strong>Update</strong></p> <p>Playing around, I noticed the the AddPrinterConnection API call completes successfully if the user that I'm impersonating is currently logged into the system. Once I log that user out and retry the command while impersonating that user, I get the error stated above.</p> <p>What is going on here?</p>
0
2009-09-23T09:17:44Z
1,844,714
<p>I can't help with the specific problem, but I do know that if I had to work with WMI stuff on Windows, with Python, I would definitely reach for Tim Golden's <a href="http://timgolden.me.uk/python/wmi/index.html" rel="nofollow">Python WMI</a> module instead of pywin32. Perhaps in the documentation/cookbook or Google searches using that module you can find a solution.</p>
0
2009-12-04T03:47:13Z
[ "python", "django", "wmi", "pywin32" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,464,942
<p>Python:</p> <pre><code>for x in a[::3]: something(x) </code></pre>
7
2009-09-23T09:30:57Z
[ "python", "arrays", "perl" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,464,951
<p>Python</p> <pre><code>print list[::3] # print it newlist = list[::3] # copy it </code></pre> <p>Perl</p> <pre><code>for ($i = 0; $i &lt; @list; $i += 3) { print $list[$i]; # print it push @y, $list[$i]; # copy it } </code></pre>
11
2009-09-23T09:33:15Z
[ "python", "arrays", "perl" ]
How can I print only every third index in Perl or Python?
1,464,923
<p>How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.</p>
5
2009-09-23T09:27:09Z
1,464,964
<p>In Perl:</p> <pre><code>$size = @array; for ($i=0; $i&lt;$size; $i+=3) # or start from $i=2, depends what you mean by "every third index" { print "$array[$i] "; } </code></pre>
2
2009-09-23T09:34:57Z
[ "python", "arrays", "perl" ]