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 list |
|---|---|---|---|---|---|---|---|---|---|
Accessing Microsoft Automation Objects from Python | 659,018 | <p>I have a set of macros that I have turned into an add-in in excel. The macros allow me to interact with another program that has what are called Microsoft Automation Objects that provide some control over what the other program does. For example, I have a filter tool in the add-in that filters the list provided by... | 4 | 2009-03-18T16:28:03Z | 659,286 | <p>You will probably need the win32com package.</p>
<p>This is a sample exemple I found at : <a href="http://www.markcarter.me.uk/computing/python/excel.html">http://www.markcarter.me.uk/computing/python/excel.html</a> which shows how to use com with Excel. This might be a good start.</p>
<pre><code># this example st... | 13 | 2009-03-18T17:22:27Z | [
"python",
"object",
"automation"
] |
Python sequence naming convention | 659,415 | <p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous ... | 4 | 2009-03-18T17:51:50Z | 659,428 | <p>Whatever you little heart desires....</p>
<p>Just kidding, but I wouldn't get to hung up on it. If it's ugly, do something to make it more readable like <code>seq_weight</code> and <code>seq_weights</code></p>
| 0 | 2009-03-18T17:55:36Z | [
"python",
"naming-conventions",
"sequence"
] |
Python sequence naming convention | 659,415 | <p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous ... | 4 | 2009-03-18T17:51:50Z | 659,430 | <p>Why not just <code>thing_list</code> or <code>thing_seq</code>?</p>
| -1 | 2009-03-18T17:55:50Z | [
"python",
"naming-conventions",
"sequence"
] |
Python sequence naming convention | 659,415 | <p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous ... | 4 | 2009-03-18T17:51:50Z | 659,439 | <p>In general, avoid this kind of behaviour. Notice from <a href="http://www.python.org/dev/peps/pep-0008/">PEP8</a></p>
<blockquote>
<p>A Foolish Consistency is the Hobgoblin
of Little Minds</p>
</blockquote>
<p>which is exactly what calling a variable <code>weightss</code> would be doing. So in general have you... | 20 | 2009-03-18T18:00:41Z | [
"python",
"naming-conventions",
"sequence"
] |
Python sequence naming convention | 659,415 | <p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous ... | 4 | 2009-03-18T17:51:50Z | 659,448 | <blockquote>
<p>The "s" naming convention would name the variable weightss, which is ugly. I am sure there is be a better naming convention for sequences.</p>
</blockquote>
<p>I think the convention you're describing is meant to be interpreted as "whenever you have list of something, make it clear that it's a list b... | 10 | 2009-03-18T18:03:23Z | [
"python",
"naming-conventions",
"sequence"
] |
What's the correct way to add extra find-links to easy_install when called as a function? | 659,575 | <p>I need to call easy_install as a function to install some Python eggs from a bunch of servers. Precisely what I install and where I get it from is determined at run-time: For example which servers I use depends on the geographic location of the computer.</p>
<p>Since I cannot guarantee that any single server will a... | 1 | 2009-03-18T18:37:52Z | 679,035 | <p>Quote:</p>
<pre><code>myargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99']
setuptools.command.easy_install.main( myargs )
</code></pre>
<p>This first problem I see with this is that you're missing a single quote on the end of your... | 3 | 2009-03-24T20:04:42Z | [
"python",
"setuptools"
] |
Python: How to add RSA padding? | 659,737 | <p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br />
I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p>
<p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signa... | 4 | 2009-03-18T19:24:04Z | 659,745 | <p>Not entirely sure, but if you add a random component to your RSA message it prevents dictionary attacks</p>
| 0 | 2009-03-18T19:26:03Z | [
"python",
"encryption",
"rsa"
] |
Python: How to add RSA padding? | 659,737 | <p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br />
I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p>
<p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signa... | 4 | 2009-03-18T19:24:04Z | 661,147 | <p>I recently fought through figuring out encryption...this article helped alot in explaining what was ment by padding:</p>
<p><a href="http://www.di-mgt.com.au/cryptopad.html" rel="nofollow">http://www.di-mgt.com.au/cryptopad.html</a></p>
<p>(method one seemed the easiest for me to implement)</p>
<p>I can share som... | 1 | 2009-03-19T05:28:53Z | [
"python",
"encryption",
"rsa"
] |
Python: How to add RSA padding? | 659,737 | <p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br />
I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p>
<p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signa... | 4 | 2009-03-18T19:24:04Z | 661,276 | <p>One of the reason for <strong>random</strong> padding might be that "from the book" RSA with low exponent (let's say 3) can be cracked really simply if the exact same message is sent to several people (three).</p>
<p>You'd therefore better make sure that you don't send the exact same message by applying some kind o... | 3 | 2009-03-19T07:02:35Z | [
"python",
"encryption",
"rsa"
] |
Python: How to add RSA padding? | 659,737 | <p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br />
I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p>
<p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signa... | 4 | 2009-03-18T19:24:04Z | 663,290 | <p>PyCrypto doesn't add the mentioned padding.<br />
M2Crypto instead does.</p>
<p>M2Crypto is built on top of openSSL, supports mostlyl everything you need, is still maintained and up to date while PyCrypto issues several deprecation warnings.</p>
| 6 | 2009-03-19T17:52:53Z | [
"python",
"encryption",
"rsa"
] |
Python: How to add RSA padding? | 659,737 | <p>I've been looking at most python crypto libraries, I've decided to use either PyCrypto or M2Crypto.<br />
I've discarded ezPyCrypto because it only supports MD5 for signing and Keyczar because it's not mature enough.</p>
<p>So I've read that RSA is vulnerable to several attacks if the to-be-encrypted text (or signa... | 4 | 2009-03-18T19:24:04Z | 10,399,555 | <p>Firstly, you should be using AES, since it is the de-facto standard.</p>
<p>AES encrypts bytes in block-sizes of 16 bytes. Obviously this works fine for any large piece of data. But the last bit of it, obviously maybe lesser than 16 bytes.</p>
<p>For the last block, you'll need to pad it,and typical padding is don... | 0 | 2012-05-01T14:59:01Z | [
"python",
"encryption",
"rsa"
] |
Reversing Django URLs With Extra Options | 659,832 | <p>Suppose I have a URLconf like below, and <code>'foo'</code> and <code>'bar'</code> are valid values for <code>page_slug</code>.</p>
<pre><code>urlpatterns = patterns('',
(r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)
</code></pre>
<p>Then, I could reconstruct the URLs using the below, right?</p... | 10 | 2009-03-18T19:45:58Z | 659,922 | <p>Here's what we do.</p>
<p>urls.py has patterns like this</p>
<pre><code>url(r'^(?P< datarealm >.*?)/json/someClass/(?P<object_id>.*?)/$', 'json_someClass_resource', ),
</code></pre>
<p>views.py as reverse calls like this</p>
<pre><code> object = SomeModel.objects.get(...)
url= reverse('json_so... | 6 | 2009-03-18T20:17:11Z | [
"python",
"django"
] |
Reversing Django URLs With Extra Options | 659,832 | <p>Suppose I have a URLconf like below, and <code>'foo'</code> and <code>'bar'</code> are valid values for <code>page_slug</code>.</p>
<pre><code>urlpatterns = patterns('',
(r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)
</code></pre>
<p>Then, I could reconstruct the URLs using the below, right?</p... | 10 | 2009-03-18T19:45:58Z | 660,339 | <p>Named urls ought to be an option. Your case is highlighted in the Django reference:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2</a></p>
<p>I'm not sure the designers left another wo... | 4 | 2009-03-18T22:24:25Z | [
"python",
"django"
] |
Reversing Django URLs With Extra Options | 659,832 | <p>Suppose I have a URLconf like below, and <code>'foo'</code> and <code>'bar'</code> are valid values for <code>page_slug</code>.</p>
<pre><code>urlpatterns = patterns('',
(r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)
</code></pre>
<p>Then, I could reconstruct the URLs using the below, right?</p... | 10 | 2009-03-18T19:45:58Z | 2,853,959 | <p>You should try naming your urlconfs. Example:</p>
<pre><code>urlpatterns = patterns('',
url(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}, name='foo-direct'),
url(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}, name='bar-page'),
)
</code></pre>
<p>Then just edit your reverse... | 15 | 2010-05-18T00:52:50Z | [
"python",
"django"
] |
Checking file attributes in python | 659,847 | <p>I'd like to check the archive bit for each file in a directory using python. So far i've got the following but i can't get it to work properly. The idea of the script is to be able to see all the files that have the archive bit on.</p>
<p>Thanks</p>
<pre><code># -*- coding: latin-1 -*-
import os , win32file, win32... | 2 | 2009-03-18T19:51:17Z | 660,223 | <p>The file list returned from os.walk are not fully qualified paths, so when you call</p>
<pre><code>win32file.GetFileAttributes(i)
</code></pre>
<p>it can't find the file and returns an error code; which happens to be -1. So the operation</p>
<pre><code>fattrs & win32con.FILE_ATTRIBUTE_ARCHIVE
</code></pre>
<... | 6 | 2009-03-18T21:37:52Z | [
"python"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 659,888 | <p>"Do child processes spawned via multiprocessing share objects created earlier in the program?"</p>
<p>No. </p>
<p>Processes have independent memory space.</p>
<p><strong>Solution 1</strong></p>
<p>To make best use of a large structure with lots of workers, do this.</p>
<ol>
<li><p>Write each worker as a "filte... | 31 | 2009-03-18T20:06:08Z | [
"python",
"multiprocessing"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 659,913 | <p>Different processes have different address space. Like running different instances of the interpreter. That's what IPC (interprocess communication) is for.</p>
<p>You can use either queues or pipes for this purpose. You can also use rpc over tcp if you want to distribute the processes over a network later.</p>
<p>... | 2 | 2009-03-18T20:14:54Z | [
"python",
"multiprocessing"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 660,024 | <p>If you're running under Unix, they may share the same object, due to <a href="http://unixfaq.blogspot.com/2008/08/whats-difference-between-fork-and-vfork.html" rel="nofollow">how fork works</a> (i.e., the child processes have separate memory but it's copy-on-write, so it may be shared as long as nobody modifies it).... | 4 | 2009-03-18T20:44:52Z | [
"python",
"multiprocessing"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 660,026 | <p><a href="http://stackoverflow.com/questions/659865/python-multiprocessing-sharing-a-large-read-only-object-between-processes/659888#659888">S.Lott</a> is correct. Python's multiprocessing shortcuts effectively give you a separate, duplicated chunk of memory.</p>
<p>On most *nix systems, using a lower-level call to ... | 19 | 2009-03-18T20:45:37Z | [
"python",
"multiprocessing"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 660,215 | <p>Not directly related to multiprocessing per se, but from your example, it would seem you could just use the <a href="http://docs.python.org/library/shelve.html" rel="nofollow">shelve</a> module or something like that. Does the "big_lookup_object" really have to be completely in memory?</p>
| 1 | 2009-03-18T21:35:08Z | [
"python",
"multiprocessing"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 660,468 | <h3>Do child processes spawned via multiprocessing share objects created <em>earlier</em> in the program?</h3>
<p>It depends. For global read-only variables it can be often considered so (apart from the memory consumed) else it should not. </p>
<p><a href="http://docs.python.org/dev/library/multiprocessing.html#multi... | 24 | 2009-03-18T23:17:12Z | [
"python",
"multiprocessing"
] |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | <p>Do child processes spawned via <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> share objects created earlier in the program?</p>
<p>I have the following setup:</p>
<pre><code>do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_... | 56 | 2009-03-18T19:58:46Z | 34,143,699 | <p>For Linux/Unix/MacOS platform, forkmap is a quick-and-dirty solution. </p>
| 0 | 2015-12-07T21:37:24Z | [
"python",
"multiprocessing"
] |
.NET Framework equivalent of Python's imghdr.what function | 660,057 | <p>Does .NET Framework have a function similar to Python's imghdr.what function to determine what type of image a file (or stream) is? I can't find anything.</p>
| 0 | 2009-03-18T20:54:38Z | 660,142 | <p>Just recently I needed to determine mime type used in file. I don't know the exact logic behind this windows API calls, but I suspect it goes inside the file to get idea of it's mime type. Hope this will help</p>
<pre><code>using System;
using System.IO;
using System.Runtime.InteropServices;
namespace SomeNamespac... | 0 | 2009-03-18T21:16:07Z | [
"c#",
"python"
] |
.NET Framework equivalent of Python's imghdr.what function | 660,057 | <p>Does .NET Framework have a function similar to Python's imghdr.what function to determine what type of image a file (or stream) is? I can't find anything.</p>
| 0 | 2009-03-18T20:54:38Z | 660,169 | <p><em>If</em> you can trust the file's extension, you can do something like the rails plugin <a href="http://github.com/mattetti/mimetype-fu" rel="nofollow">mimetype-fu</a>.</p>
<p>This plugin has a yaml list of extensions and their known mime types. It is fairly exhaustive. We found a yaml parser for .net and simply... | 0 | 2009-03-18T21:23:29Z | [
"c#",
"python"
] |
How to manage a CPU intensive process on a server | 660,059 | <p>I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.</p>
<p>The script takes up to 20 seconds to run and I am concerned about the performance on my server. Is there a good approach to either lower the... | 7 | 2009-03-18T20:54:54Z | 660,068 | <p>Assuming it's a UNIX server, you could use the <a href="http://www.builderau.com.au/program/linux/print.htm?TYPE=story&AT=339286637-339028299t-320002022c" rel="nofollow">nice command</a> to lower its priority. That should do the trick.</p>
| 7 | 2009-03-18T20:57:42Z | [
"python",
"performance",
"signal-processing"
] |
How to manage a CPU intensive process on a server | 660,059 | <p>I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.</p>
<p>The script takes up to 20 seconds to run and I am concerned about the performance on my server. Is there a good approach to either lower the... | 7 | 2009-03-18T20:54:54Z | 660,141 | <p>You can use <a href="http://cpulimit.sourceforge.net/" rel="nofollow">cpulimit</a> on a linux based server. It will allow you to limit the CPU usage (specify the limit as a percentage) even of scripts that have already started running, and its usage is pretty straightforward.</p>
<p>It's available on the Debian rep... | 5 | 2009-03-18T21:15:54Z | [
"python",
"performance",
"signal-processing"
] |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | <p>How do I list all tga files in a directory (non recursive) in Python?</p>
| 4 | 2009-03-18T21:21:30Z | 660,178 | <pre><code>
>>> import os
>>> for file in [tga for tga in os.listdir(directory) if tga.endswith(".tga")]:
>>> print file
</code></pre>
| 1 | 2009-03-18T21:25:29Z | [
"python"
] |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | <p>How do I list all tga files in a directory (non recursive) in Python?</p>
| 4 | 2009-03-18T21:21:30Z | 660,179 | <pre><code>import glob, os
for filename in glob.glob(os.path.join(yourPath, "*.tga"))
print(filename)
</code></pre>
| 13 | 2009-03-18T21:25:51Z | [
"python"
] |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | <p>How do I list all tga files in a directory (non recursive) in Python?</p>
| 4 | 2009-03-18T21:21:30Z | 660,190 | <p>If you are doing it based on file extension, you can do something like this:</p>
<pre><code>import os
directory = "C:/"
extension = ".tga"
list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)]
</code></pre>
<p>Obviously you can omit the lower() if you can garantee the case of... | 19 | 2009-03-18T21:27:56Z | [
"python"
] |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | <p>How do I list all tga files in a directory (non recursive) in Python?</p>
| 4 | 2009-03-18T21:21:30Z | 10,376,226 | <p>The following example uses <code>filter</code>, which offers an elegant solution as shown below:</p>
<pre><code>import os
files = filter(lambda x: x.endswith('.tga'), os.listdir(DIR))
</code></pre>
| 2 | 2012-04-29T21:38:56Z | [
"python"
] |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | <p>How do I list all tga files in a directory (non recursive) in Python?</p>
| 4 | 2009-03-18T21:21:30Z | 10,718,762 | <p>My Targa/Vista have often .vst and .tga, sometimes other extension:</p>
<pre><code>import os
from glob import glob
import PIL
filenames = []
for filename in glob(os.path.join(dirname, "*.*")):
try:
img = PIL.Image(filename)
if img.format == "TGA":
filenames.append(filename)
exce... | 0 | 2012-05-23T11:12:15Z | [
"python"
] |
Python: decorator specific argument (unrelated to wrapped function)? | 660,727 | <p>I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:</p>
<pre><code>@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
</code></pre>
<p>The argument to the decorator is comple... | 6 | 2009-03-19T01:11:03Z | 660,751 | <p>The idea is that your decorator is a function returning a decorator.</p>
<p><strong>FIRST</strong> Write your decorator as if you knew your argument was a global variable. Let's say something like:</p>
<p>-</p>
<pre><code>def decorator(f):
def decorated(*args,**kwargs):
cache = Cache(cachepath)
if c... | 9 | 2009-03-19T01:22:45Z | [
"python",
"decorator"
] |
Python: decorator specific argument (unrelated to wrapped function)? | 660,727 | <p>I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:</p>
<pre><code>@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
</code></pre>
<p>The argument to the decorator is comple... | 6 | 2009-03-19T01:11:03Z | 660,758 | <p>Yes it is. As you know, a decorator is a function. When written in the form:</p>
<pre><code>def mydecorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@mydecorator
def foo(a, b, c):
pass
</code></pre>
<p>the argument passed to <code>mydecorator</code> is the ... | 5 | 2009-03-19T01:25:48Z | [
"python",
"decorator"
] |
Python: decorator specific argument (unrelated to wrapped function)? | 660,727 | <p>I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:</p>
<pre><code>@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
</code></pre>
<p>The argument to the decorator is comple... | 6 | 2009-03-19T01:11:03Z | 660,834 | <p>Paul's answer is good, I would move the cache object so it doesn't need to be built every time, and design your cache so that it raises KeyError when there is a cache miss:</p>
<pre>def cache(filepath):
def decorator(f):
f._cache = Cache(cachepath)
def decorated(*args,**kwargs):
try:... | 3 | 2009-03-19T02:11:19Z | [
"python",
"decorator"
] |
Python Django loop logic: Error says 'int' is not iterable - check my syntax? | 660,773 | <pre><code>return sum(jobrecord.get_cost() or 0
for jobrecord in self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date) or 0)
</code></pre>
| 0 | 2009-03-19T01:38:37Z | 660,779 | <p>After a small rewrite</p>
<pre><code>query = self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date)
values= ( jobrecord.get_cost() or 0 for jobrecord in query or 0 )
return sum( values )
</code></pre>
<p>Look closely at the <code>values= ( jobrecord.get_cost() or 0 for jobrec... | 3 | 2009-03-19T01:42:52Z | [
"python",
"django"
] |
Python Django loop logic: Error says 'int' is not iterable - check my syntax? | 660,773 | <pre><code>return sum(jobrecord.get_cost() or 0
for jobrecord in self.project.jobrecord_set.filter(
date__lte=date,
date__gte=self.start_date) or 0)
</code></pre>
| 0 | 2009-03-19T01:38:37Z | 660,842 | <p>0 is indeed not iterable. I think you want to drop that last <code>or 0</code>. when the filter query matches no elements, it will return an empty query, and your sum will just be 0, since <code>sum([])</code> is zero.</p>
<p>If there's some reason why the query might raise an exception (invalid dates or some such... | 1 | 2009-03-19T02:13:33Z | [
"python",
"django"
] |
Django-way of specifying channel image in rss feed | 660,836 | <p>What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.</p>
<p><b>Edit</b>
dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds</p>
| 9 | 2009-03-19T02:11:26Z | 660,906 | <p>I suggesting to use <a href="http://code.google.com/p/django-atompub/" rel="nofollow">django-atompub</a> for Atom feed generation.
It has very nice Class abstraction with lots of options, so no any XML hacking, high-level Python code only.</p>
<p>Example:</p>
<pre><code># Define feed class
class StreamFeed(Feed):
... | 4 | 2009-03-19T02:50:45Z | [
"python",
"django",
"rss"
] |
Django-way of specifying channel image in rss feed | 660,836 | <p>What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.</p>
<p><b>Edit</b>
dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds</p>
| 9 | 2009-03-19T02:11:26Z | 695,464 | <p>Found the <em>right</em> way of doing it. As the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/?from=olddocs#custom-feed-generators">documentation</a> describes, I needed to create a custom feed generator by subclassing from <em>Rss201rev2Feed</em> and overriding method </p>
<pre>
add_root_e... | 8 | 2009-03-29T21:55:08Z | [
"python",
"django",
"rss"
] |
Django-way of specifying channel image in rss feed | 660,836 | <p>What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.</p>
<p><b>Edit</b>
dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds</p>
| 9 | 2009-03-19T02:11:26Z | 8,894,216 | <p>For valid RSS 2.0 you shoud use this:</p>
<pre><code>class ImageRssFeedGenerator(Rss201rev2Feed):
def add_root_elements(self, handler):
super(ImageRssFeedGenerator, self).add_root_elements(handler)
handler.startElement(u'image', {})
handler.addQuickElement(u"url", self.feed['image_url'])... | 5 | 2012-01-17T11:58:11Z | [
"python",
"django",
"rss"
] |
django : using admin datepicker | 660,898 | <p>I'm trying to use the admin datepicker in my own django forms.</p>
<p>Roughly following the discussion here : <a href="http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html">http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html</a></p>
<p>I've</p>
<p>a) In my forms.py included ... | 9 | 2009-03-19T02:48:29Z | 660,986 | <p>No, it's not a bug. </p>
<p>It's trying to call the gettext() internationalization function in js. You can do js internationalization much like you do it in python code or templates, it's only a less known feature.</p>
<p>If you don't use js internationalization in your project you can just put.</p>
<pre><co... | 4 | 2009-03-19T03:42:13Z | [
"python",
"django",
"forms",
"django-forms",
"date"
] |
django : using admin datepicker | 660,898 | <p>I'm trying to use the admin datepicker in my own django forms.</p>
<p>Roughly following the discussion here : <a href="http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html">http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html</a></p>
<p>I've</p>
<p>a) In my forms.py included ... | 9 | 2009-03-19T02:48:29Z | 660,996 | <p>I think I solved the first half by explicitly adding these lines to my template :</p>
<pre><code><script type="text/javascript" src="../../../jsi18n/"></script>
<script type="text/javascript" src="/admin_media/js/core.js"></script>
<script type="text/javascript" src="/admin_media/js/admi... | 2 | 2009-03-19T03:46:03Z | [
"python",
"django",
"forms",
"django-forms",
"date"
] |
django : using admin datepicker | 660,898 | <p>I'm trying to use the admin datepicker in my own django forms.</p>
<p>Roughly following the discussion here : <a href="http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html">http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html</a></p>
<p>I've</p>
<p>a) In my forms.py included ... | 9 | 2009-03-19T02:48:29Z | 685,606 | <p>You may find the following works for you:</p>
<pre><code><link href="/media/css/base.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/media/js/core.js"></script>
{{ form.media }}
<... | 1 | 2009-03-26T12:42:14Z | [
"python",
"django",
"forms",
"django-forms",
"date"
] |
Overriding python threading.Thread.run() | 660,961 | <p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p>
<blockquote>
<p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constru... | 17 | 2009-03-19T03:26:56Z | 660,968 | <p>You define the run method to accept 3 arguments, but you call it with one argument (python calls it with the reference to the object).</p>
<p>You need to pass the arguments to run instead of <code>__init__</code>.</p>
<p>Or make the <code>__init__</code> method accept the arguments instead.</p>
| 0 | 2009-03-19T03:32:42Z | [
"python",
"multithreading"
] |
Overriding python threading.Thread.run() | 660,961 | <p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p>
<blockquote>
<p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constru... | 17 | 2009-03-19T03:26:56Z | 660,974 | <p>You really don't need to subclass Thread. The only reason the API supports this is to make it more comfortable for people coming from Java where that's the only way to do it sanely.</p>
<p>The pattern that we recommend you use is to pass a method to the Thread constructor, and just call .start().</p>
<pre><code> d... | 39 | 2009-03-19T03:35:18Z | [
"python",
"multithreading"
] |
Overriding python threading.Thread.run() | 660,961 | <p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p>
<blockquote>
<p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constru... | 17 | 2009-03-19T03:26:56Z | 4,890,401 | <p>The documentation of threading.Thread may seem to imply that any unused positional and keyword args are passed to run. They are not.</p>
<p>Any extra positional args and keyword kwargs are indeed trapped by the default threading.Thread.<strong>init</strong> method -- but they are ONLY passed to a method specified ... | 2 | 2011-02-03T18:53:50Z | [
"python",
"multithreading"
] |
Overriding python threading.Thread.run() | 660,961 | <p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p>
<blockquote>
<p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constru... | 17 | 2009-03-19T03:26:56Z | 4,974,726 | <p>Here's is an example of passing arguments using threading and not extending <strong>init</strong>:</p>
<pre><code>import threading
class Example(threading.Thread):
def run(self):
print '%s from %s' % (self._Thread__kwargs['example'],
self.name)
example = Example(kwargs={... | 4 | 2011-02-11T22:29:40Z | [
"python",
"multithreading"
] |
Overriding python threading.Thread.run() | 660,961 | <p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p>
<blockquote>
<p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constru... | 17 | 2009-03-19T03:26:56Z | 19,942,496 | <p>If you want to keep your object-oriented approach and also have run arguments, you can do the following:</p>
<pre><code>import threading
class Destination:
def run(self, name, config):
print 'In thread'
destination = Destination()
thread = threading.Thread(target=destination.run,
args=(destination_... | -1 | 2013-11-12T23:56:29Z | [
"python",
"multithreading"
] |
Overriding python threading.Thread.run() | 660,961 | <p>Given the documentation at <a href="http://docs.python.org/library/threading.html">http://docs.python.org/library/threading.html</a> which states for Thread.run():</p>
<blockquote>
<p>You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constru... | 17 | 2009-03-19T03:26:56Z | 29,850,862 | <p>In order to address some of the confusion about whether an overridden <code>run()</code> method takes additional arguments, here is an implementation of an overridden <code>run()</code> method that does what the method inherited from <code>threading.Thread</code> does.</p>
<p>Note, this just to see how one would ov... | 0 | 2015-04-24T14:59:59Z | [
"python",
"multithreading"
] |
Access to errno from Python? | 661,017 | <p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p>
<p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p>
<p>Using ctype... | 18 | 2009-03-19T04:00:33Z | 661,030 | <p>It looks like you can use this patch that will provide you with <code>ctypes.get_errno/set_errno</code></p>
<p><a href="http://bugs.python.org/issue1798">http://bugs.python.org/issue1798</a></p>
<p>This is the patch that was actually applied to the repository:</p>
<p><a href="http://svn.python.org/view?view=rev&a... | 6 | 2009-03-19T04:10:16Z | [
"python",
"linux",
"python-2.5",
"errno"
] |
Access to errno from Python? | 661,017 | <p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p>
<p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p>
<p>Using ctype... | 18 | 2009-03-19T04:00:33Z | 661,150 | <p>I'm not sure if this is what you and Jerub are referring to, but you could write a very short C extension that just exports errno, i.e. with <a href="http://www.python.org/doc/2.5.1/ext/simpleExample.html" rel="nofollow">the python language interface</a>. </p>
<p>Otherwise, I agree with you that having to add this ... | 1 | 2009-03-19T05:30:18Z | [
"python",
"linux",
"python-2.5",
"errno"
] |
Access to errno from Python? | 661,017 | <p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p>
<p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p>
<p>Using ctype... | 18 | 2009-03-19T04:00:33Z | 661,295 | <p>Gave up and tracked through the C headers.</p>
<pre><code>import ctypes
c = ctypes.CDLL("libc.so.6")
c.__errno_location.restype = ctypes.POINTER(ctypes.c_int)
c.write(5000, "foo", 4)
print c.__errno_location().contents # -> c_long(9)
</code></pre>
<p>It doesn't work in the python command prompt because it reset... | 6 | 2009-03-19T07:18:23Z | [
"python",
"linux",
"python-2.5",
"errno"
] |
Access to errno from Python? | 661,017 | <p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p>
<p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p>
<p>Using ctype... | 18 | 2009-03-19T04:00:33Z | 661,300 | <p>Belowed code is not reliable (or comprehensive, there are a plefora of ways <code>errno</code> could be defined) but it should get you started (or reconsider your position on a tiny extension module (after all on Debian <code>python setup.py install</code> or <code>easy_install</code> should have no problem to build... | 11 | 2009-03-19T07:19:50Z | [
"python",
"linux",
"python-2.5",
"errno"
] |
Access to errno from Python? | 661,017 | <p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p>
<p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p>
<p>Using ctype... | 18 | 2009-03-19T04:00:33Z | 661,303 | <p>Here is a snippet of code that allows to access <code>errno</code>:</p>
<pre><code>from ctypes import *
libc = CDLL("libc.so.6")
get_errno_loc = libc.__errno_location
get_errno_loc.restype = POINTER(c_int)
def errcheck(ret, func, args):
if ret == -1:
e = get_errno_loc()[0]
raise OSError(e)
... | 15 | 2009-03-19T07:20:16Z | [
"python",
"linux",
"python-2.5",
"errno"
] |
Access to errno from Python? | 661,017 | <p>I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.</p>
<p>Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.</p>
<p>Using ctype... | 18 | 2009-03-19T04:00:33Z | 6,170,629 | <p>ctypes actually gives a standard way to access python's c implementation, which is using errno. I haven't tested this on anything other than my (linux) system, but this should be very portable:</p>
<p>ctypes.c_int.in_dll(ctypes.pythonapi,"errno")</p>
<p>which returns a c_int containing the current value.</p>
| 0 | 2011-05-29T21:47:21Z | [
"python",
"linux",
"python-2.5",
"errno"
] |
Can I make pdb start debugging right away? | 661,034 | <p>I want to debug a python project</p>
<p>The problem is, I don't know where to set a break point,</p>
<p>what I want to do, is be able to call a method </p>
<pre><code>SomeClass( some_ctor_arguments ).some_method()`
</code></pre>
<p>and have the debugger be fired right away</p>
<p>How do I do that?</p>
<p>I tri... | 5 | 2009-03-19T04:12:05Z | 661,044 | <p>Found it ..</p>
<pre><code>pdb.runcall( object.method )
</code></pre>
| 5 | 2009-03-19T04:15:06Z | [
"python",
"debugging",
"pdb"
] |
Can I make pdb start debugging right away? | 661,034 | <p>I want to debug a python project</p>
<p>The problem is, I don't know where to set a break point,</p>
<p>what I want to do, is be able to call a method </p>
<pre><code>SomeClass( some_ctor_arguments ).some_method()`
</code></pre>
<p>and have the debugger be fired right away</p>
<p>How do I do that?</p>
<p>I tri... | 5 | 2009-03-19T04:12:05Z | 661,322 | <pre><code>pdb.set_trace()
</code></pre>
<p>will start the debugger at this point.</p>
<p>Place it at the beginning of the method you want to debug.</p>
| 4 | 2009-03-19T07:27:40Z | [
"python",
"debugging",
"pdb"
] |
Security of Python's eval() on untrusted strings? | 661,084 | <p>If I am evaluating a Python string using eval(), and have a class like:</p>
<pre><code>class Foo(object):
a = 3
def bar(self, x): return x + a
</code></pre>
<p>What are the security risks if I do not trust the string? In particular:</p>
<ol>
<li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That ... | 20 | 2009-03-19T04:39:50Z | 661,128 | <p><code>eval()</code> will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.</p>
<p>There was recently a thread about how to do this kind of thing safely on the python-dev list, and the conclusions were:</p>
<ul>
<li>It's really hard to do this properly.</... | 41 | 2009-03-19T05:13:44Z | [
"python",
"security",
"eval"
] |
Security of Python's eval() on untrusted strings? | 661,084 | <p>If I am evaluating a Python string using eval(), and have a class like:</p>
<pre><code>class Foo(object):
a = 3
def bar(self, x): return x + a
</code></pre>
<p>What are the security risks if I do not trust the string? In particular:</p>
<ol>
<li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That ... | 20 | 2009-03-19T04:39:50Z | 661,196 | <p>You are probably better off turning the question around: </p>
<ol>
<li>What sort of expressions are you wanting to eval?</li>
<li>Can you insure that only strings matching some narrowly defined syntax are eval()d?</li>
<li>Then consider if <em>that</em> is safe.</li>
</ol>
<p>For example, if you are wanting to let... | 3 | 2009-03-19T05:57:13Z | [
"python",
"security",
"eval"
] |
Security of Python's eval() on untrusted strings? | 661,084 | <p>If I am evaluating a Python string using eval(), and have a class like:</p>
<pre><code>class Foo(object):
a = 3
def bar(self, x): return x + a
</code></pre>
<p>What are the security risks if I do not trust the string? In particular:</p>
<ol>
<li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That ... | 20 | 2009-03-19T04:39:50Z | 663,953 | <p>Note that even if you pass empty dictionaries to eval(), it's still possible to segfault (C)Python with some syntax tricks. For example, try this on your interpreter: <code>eval("()"*8**5)</code></p>
| 6 | 2009-03-19T20:36:24Z | [
"python",
"security",
"eval"
] |
Security of Python's eval() on untrusted strings? | 661,084 | <p>If I am evaluating a Python string using eval(), and have a class like:</p>
<pre><code>class Foo(object):
a = 3
def bar(self, x): return x + a
</code></pre>
<p>What are the security risks if I do not trust the string? In particular:</p>
<ol>
<li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That ... | 20 | 2009-03-19T04:39:50Z | 664,224 | <p>You can get to <code>os</code> using builtin functions: <code>__import__('os')</code>.</p>
<p>For python 2.6+, the <a href="http://docs.python.org/library/ast.html#ast-helpers">ast module</a> may help; in particular <code>ast.literal_eval</code>, although it depends on exactly what you want to eval.</p>
| 9 | 2009-03-19T21:55:19Z | [
"python",
"security",
"eval"
] |
Security of Python's eval() on untrusted strings? | 661,084 | <p>If I am evaluating a Python string using eval(), and have a class like:</p>
<pre><code>class Foo(object):
a = 3
def bar(self, x): return x + a
</code></pre>
<p>What are the security risks if I do not trust the string? In particular:</p>
<ol>
<li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That ... | 20 | 2009-03-19T04:39:50Z | 1,994,506 | <p>There is a very good <a href="http://www.diveintopython3.net/advanced-iterators.html#eval" rel="nofollow">article on the un-safety of <code>eval()</code></a> in Mark Pilgrim's <a href="http://www.diveintopython3.net/" rel="nofollow">Dive into Python</a> tutorial.</p>
<p>Quoted from this article: </p>
<blockquote>
... | 1 | 2010-01-03T10:14:40Z | [
"python",
"security",
"eval"
] |
Security of Python's eval() on untrusted strings? | 661,084 | <p>If I am evaluating a Python string using eval(), and have a class like:</p>
<pre><code>class Foo(object):
a = 3
def bar(self, x): return x + a
</code></pre>
<p>What are the security risks if I do not trust the string? In particular:</p>
<ol>
<li>Is <code>eval(string, {"f": Foo()}, {})</code> unsafe? That ... | 20 | 2009-03-19T04:39:50Z | 10,964,364 | <p>You cannot secure eval with a blacklist approach like this. See <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html">Eval really is dangerous</a> for examples of input that will segfault the CPython interpreter, give access to any class you like, and so on.</p>
| 11 | 2012-06-09T20:28:25Z | [
"python",
"security",
"eval"
] |
Is there a parser/way available to parser Wikipedia dump files using Python? | 661,584 | <p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p>
<p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer ... | 6 | 2009-03-19T09:44:26Z | 661,625 | <p>There is example code for the same at <a href="http://jjinux.blogspot.com/2009/01/python-parsing-wikipedia-dumps-using.html" rel="nofollow">http://jjinux.blogspot.com/2009/01/python-parsing-wikipedia-dumps-using.html</a></p>
| 3 | 2009-03-19T10:00:28Z | [
"python",
"xml",
"parsing",
"wiki",
"wikipedia"
] |
Is there a parser/way available to parser Wikipedia dump files using Python? | 661,584 | <p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p>
<p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer ... | 6 | 2009-03-19T09:44:26Z | 661,626 | <p>I don't know about licensing, but <a href="http://linux.softpedia.com/get/Education/Wikipedia-Dump-Reader-30091.shtml" rel="nofollow">this</a> is implemented in python, and includes the source.</p>
| 1 | 2009-03-19T10:00:45Z | [
"python",
"xml",
"parsing",
"wiki",
"wikipedia"
] |
Is there a parser/way available to parser Wikipedia dump files using Python? | 661,584 | <p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p>
<p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer ... | 6 | 2009-03-19T09:44:26Z | 922,960 | <p>Another good module is <em>mwlib</em> from <a href="http://code.pediapress.com/wiki/wiki/mwlib" rel="nofollow">here</a> - it is a pain to install with all dependencies (at least on Windows), but it works well.</p>
| 1 | 2009-05-28T20:23:25Z | [
"python",
"xml",
"parsing",
"wiki",
"wikipedia"
] |
Is there a parser/way available to parser Wikipedia dump files using Python? | 661,584 | <p>I have a project where I collect all the Wikipedia articles belonging to a particular category, pull out the dump from Wikipedia, and put it into our db. </p>
<p>So I should be parsing the Wikipedia dump file to get the stuff done. Do we have an efficient parser to do this job? I am a python developer. So I prefer ... | 6 | 2009-03-19T09:44:26Z | 28,220,070 | <p><a href="https://dizzylogic.com/wikiparser" rel="nofollow">Wiki Parser</a> is a very fast parser for Wikipedia dump files (~2 hours to parse all 55GB of English Wikipedia). It produces XML that preserves both content and article structure.</p>
<p>You can then use python to do anything you want with the XML output.<... | 0 | 2015-01-29T16:46:08Z | [
"python",
"xml",
"parsing",
"wiki",
"wikipedia"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 661,624 | <pre><code>>>> gen = (i for i in [])
>>> next(gen)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
next(gen)
StopIteration
</code></pre>
<p>At the end of generator <code>StopIteration</code> is raised, since in your case end is reached immediately, except... | 1 | 2009-03-19T10:00:23Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 661,653 | <p>Sorry for the obvious approach, but the best way would be to do:</p>
<pre><code>for item in my_generator:
print item
</code></pre>
<p>Now you have detected that the generator is empty while you are using it. Of course, item will never be displayed if the generator is empty.</p>
<p>This may not exactly fit in... | 2 | 2009-03-19T10:14:14Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 661,673 | <p>I hate to offer a second solution, especially one that I would not use myself, but, if you absolutely <em>had</em> to do this and to not consume the generator, as in other answers:</p>
<pre><code>def do_something_with_item(item):
print item
empty_marker = object()
try:
first_item = my_generator.next() ... | 7 | 2009-03-19T10:23:37Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 661,765 | <p>Here is a recipe for an iterator wrapper, it probably allows to do what you want:</p>
<p><a href="http://code.activestate.com/recipes/502304/" rel="nofollow">http://code.activestate.com/recipes/502304/</a></p>
<p>Note: I have not tested if it works or not.
Nor am I sure that the functionality is useful.</p>
| 3 | 2009-03-19T10:59:03Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 661,967 | <p>The best approach, IMHO, would be to avoid a special test. Most times, use of a generator <em>is</em> the test:</p>
<pre><code>thing_generated = False
# Nothing is lost here. if nothing is generated,
# the for block is not executed. Often, that's the only check
# you need to do. This can be done in the course of ... | 6 | 2009-03-19T12:08:48Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 662,925 | <p>The simple answer to your question: no, there is no simple way. There are a whole lot of work-arounds.</p>
<p>There really shouldn't be a simple way, because of what generators are: a way to output a sequence of values <em>without holding the sequence in memory</em>. So there's no backward traversal.</p>
<p>You ... | 25 | 2009-03-19T16:25:12Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 664,239 | <p>Suggestion:</p>
<pre><code>def peek(iterable):
try:
first = next(iterable)
except StopIteration:
return None
return first, itertools.chain([first], iterable)
</code></pre>
<p>Usage:</p>
<pre><code>res = peek(mysequence)
if res is None:
# sequence is empty. Do stuff.
else:
firs... | 33 | 2009-03-19T22:01:31Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 7,971,996 | <p>If you need to know <em>before</em> you use the generator, then no, there is no simple way. If you can wait until <em>after</em> you have used the generator, there is a simple way:</p>
<pre><code>was_empty = True
for some_item in some_generator:
was_empty = False
do_something_with(some_item)
if was_empty... | 0 | 2011-11-01T19:47:29Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 21,525,143 | <p>A simple way is to use the optional parameter for <a href="http://docs.python.org/2/library/functions.html#next" rel="nofollow">next()</a> which is used if the generator is exhausted (or empty). For example: </p>
<pre><code>iterable = some_generator()
_exhausted = object()
if next(iterable, _exhausted) == _exhaus... | 7 | 2014-02-03T10:41:42Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 22,594,020 | <p>I realize that this post is 5 years old at this point, but I found it while looking for an idiomatic way of doing this, and did not see my solution posted. So for posterity:</p>
<pre><code>import itertools
def get_generator():
"""
Returns (bool, generator) where bool is true iff the generator is not empty... | 2 | 2014-03-23T17:02:20Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 24,199,042 | <p>All you need to do to see if the generator is empty is to try to get the next result. Of course if you're not <em>ready</em> to use that result then you have to store it to return it again later.</p>
<p>Here's a wrapper class that can be added to an existing iterator to add an <code>__nonzero__</code> test, so you ... | 2 | 2014-06-13T06:30:58Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 32,039,643 | <p>Here is my simple approach that i use to keep on returning an iterator while checking if something was yielded
I just check if the loop runs:</p>
<pre><code> n = 0
for key, value in iterator:
n+=1
yield key, value
if n == 0:
print ("nothing found in iterato... | 0 | 2015-08-16T20:32:33Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 37,375,898 | <p><code>next(generator, None) is not None</code></p>
<p>Or replace <code>None</code> but whatever value you know it's <em>not</em> in your generator.</p>
| 5 | 2016-05-22T14:58:54Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 37,821,192 | <p>I solved it by using the sum function. See below for an example I used with glob.iglob (which returns a generator).</p>
<pre><code>def isEmpty():
files = glob.iglob(search)
if sum(1 for _ in files):
return True
return False
</code></pre>
<p>*This will probably not work for HUGE generators but s... | -1 | 2016-06-14T20:09:31Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 38,087,154 | <p>Simply wrap the generator with <a href="https://docs.python.org/2.7/library/itertools.html#itertools.chain" rel="nofollow">itertools.chain</a>, put something that will represent the end of the iterable as the second iterable, then simply check for that.</p>
<p>Ex:</p>
<pre><code>import itertools
g = some_iterable... | 0 | 2016-06-28T22:14:12Z | [
"python",
"generator"
] |
How do I know if a generator is empty from the start? | 661,603 | <p>Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines?</p>
| 57 | 2009-03-19T09:51:24Z | 38,650,175 | <p>Here's a simple decorator which wraps the generator, so it returns None if empty. This can be useful if your code needs to know whether the generator will produce anything <em>before</em> looping through it.</p>
<pre><code>def generator_or_none(func):
"""Wrap a generator function, returning None if it's empty. ... | 0 | 2016-07-29T03:43:42Z | [
"python",
"generator"
] |
Can I use a single file as a buffer? I.e. write to and read from at same time | 661,826 | <p>I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.</p>
<p>The simplest way I can think to do this is by writing the data to a buffer file from the application, and th... | 2 | 2009-03-19T11:20:44Z | 661,836 | <p>Most systems has several solutions for what you want to do, such as pipes and unix sockets. These are intended for this, unlike regular files. There are however programs that does this on regular files, and I think the clearest example of this is the unix-utility tail, which can "follow" a file.</p>
<p>Take a look ... | 4 | 2009-03-19T11:26:55Z | [
"python",
"file-io"
] |
Can I use a single file as a buffer? I.e. write to and read from at same time | 661,826 | <p>I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.</p>
<p>The simplest way I can think to do this is by writing the data to a buffer file from the application, and th... | 2 | 2009-03-19T11:20:44Z | 661,992 | <p>What you're talking about is called "Interprocess Communication". There are lots of ways of doing this.</p>
<p>Using Unix pipes.</p>
<p><a href="https://docs.python.org/library/pipes.html" rel="nofollow">https://docs.python.org/library/pipes.html</a></p>
<p>Using sockets.</p>
<p><a href="https://docs.python.org... | 1 | 2009-03-19T12:17:51Z | [
"python",
"file-io"
] |
Can I use a single file as a buffer? I.e. write to and read from at same time | 661,826 | <p>I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.</p>
<p>The simplest way I can think to do this is by writing the data to a buffer file from the application, and th... | 2 | 2009-03-19T11:20:44Z | 669,335 | <p>You can use memory-mapped files, standard Python module called mmap.</p>
| 2 | 2009-03-21T13:48:06Z | [
"python",
"file-io"
] |
write a table with empty cells based on dictionary of values | 662,463 | <p>I have this view in my app:</p>
<pre><code>def context_detail(request, context_id):
c = get_object_or_404(Context, pk=context_id)
scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True)
total = sum(sc.count for sc in scs)
table = []
forms = []
for a in c.assemblage_set.all():
for sc i... | 1 | 2009-03-19T14:40:44Z | 663,424 | <p>Here's the data structure.</p>
<pre><code>[{<Type1>: 16,
<Type2>: 10,
<Type3>: 12,
<Type4>: 7,
<Type5>: 0,
'assemblage': <Assemblage1>},
{<Type1>: 85,
<Type2>: 18,
<Type3>: 21,
<Type4>: 12,
<Type5>: 2,
'assemblage': <Assemblag... | 2 | 2009-03-19T18:25:34Z | [
"python",
"django",
"django-templates"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 662,713 | <blockquote>
<p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
</blockquote>
<p>With minidom no, the datatype used to store attributes is an unordered dictionary. <a href="http://www.doxdesk.com/software/py/pxdom.html">pxdom</a> can do it, though it is considerab... | 6 | 2009-03-19T15:42:55Z | [
"python",
"xml",
"minidom"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 989,585 | <p>I've ended up using the <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> library instead of minidom.</p>
| 0 | 2009-06-13T00:11:41Z | [
"python",
"xml",
"minidom"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 5,908,853 | <p>It is clear that xml attribute are not ordered.
I just have found this strange behavior !</p>
<p>It seems that this related to a sort added in xml.dom.minidom.Element.writexml function !!</p>
<pre><code>class Element(Node):
... snip ...
def writexml(self, writer, indent="", addindent="", newl=""):
# i... | 2 | 2011-05-06T08:36:58Z | [
"python",
"xml",
"minidom"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 8,345,268 | <p>To keep the attribute order I made this slight modification in minidom:</p>
<pre><code>from collections import OrderedDict
</code></pre>
<p>In the Element class : </p>
<pre><code>__init__(...)
self._attrs = OrderedDict()
#self._attrs = {}
writexml(...)
#a_names.sort()
</code></pre>
<p>Now this will o... | 5 | 2011-12-01T17:00:35Z | [
"python",
"xml",
"minidom"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 8,429,008 | <p>Before Python 2.7, I used following <em>hotpatching</em>:</p>
<pre><code>class _MinidomHooker(object):
def __enter__(self):
minidom.NamedNodeMap.keys_orig = minidom.NamedNodeMap.keys
minidom.NamedNodeMap.keys = self._NamedNodeMap_keys_hook
return self
def __exit__(self, *args):
... | 2 | 2011-12-08T09:47:45Z | [
"python",
"xml",
"minidom"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 22,303,750 | <p>You guys can put up as many disclaimers you want.
While reordering the attributes has no meaning for the program it does have a meaning for the programmer/user.</p>
<p>For Fredrick it was important to have the RGB order since that is how the order of the colors is.
For me it is the name attribute in particular.</... | 1 | 2014-03-10T15:02:13Z | [
"python",
"xml",
"minidom"
] |
Preserve order of attributes when modifying with minidom | 662,624 | <p>Is there a way I can preserve the original order of attributes when processing XML with minidom?</p>
<p>Say I have: <code><color red="255" green="255" blue="233" /></code>
when I modify this with minidom the attributes are rearranged alphabetically blue, green, and red. I'd like to preserve the original order... | 6 | 2009-03-19T15:23:11Z | 29,696,911 | <p><strong>1.Custom your own 'Element.writexml' method.</strong></p>
<p>from 'minidom.py' copy Element's writexml code to your own file.</p>
<p>rename it to writexml_nosort,</p>
<p>delete 'a_names.sort()' (python 2.7)
or change 'a_names = sorted(attrs.keys())' to 'a_names = attrs.keys()'(python 3.4)</p>
<p>change ... | 0 | 2015-04-17T10:37:44Z | [
"python",
"xml",
"minidom"
] |
How to Alter Photographed Document to Look "Scanned" | 662,638 | <p>How can I <a href="http://www.techcrunch.com/2009/03/17/jotnot-turns-your-iphones-camera-into-a-document-scanner/" rel="nofollow">do this</a> in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it?</... | 6 | 2009-03-19T15:27:18Z | 662,694 | <p>Look at transform() with method set to QUAD</p>
<p><a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">http://effbot.org/imagingbook/image.htm</a></p>
<blockquote>
<pre><code>im.transform(size, QUAD, data) => image
im.transform(size, QUAD, data, filter) => image
</code></pre>
<p>Maps a quad... | 8 | 2009-03-19T15:37:38Z | [
"python",
"image-processing",
"python-imaging-library",
"image-scanner"
] |
Help with subprocess.call on a Windows machine | 662,641 | <p>I am trying to modify a <a href="http://trac.edgewall.org" rel="nofollow">trac</a> plugin that allows downloading of wiki pages to word documents. pagetodoc.py throws an exception on this line:</p>
<pre><code># Call the subprocess using convenience method
retval = subprocess.call(command, shell=True, stderr=errptr,... | 2 | 2009-03-19T15:27:59Z | 663,054 | <p>close_fds <em><a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow">is</a></em> supported on windows starting with python 2.6 (if stdin/stdout/stderr are not redirected). you might consider upgrading.</p>
| 1 | 2009-03-19T16:59:33Z | [
"python",
"trac",
"python-2.4"
] |
Can I write Python web application for Windows and Linux platforms at the same time? | 662,762 | <p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p>
<p>CGI? Maybe something new? WSGI | FastCGI ? </p>
| 3 | 2009-03-19T15:52:10Z | 662,784 | <p>web.py includes a server... It will do the trick for small jobs.</p>
<p>By the way, Apache works on windows.</p>
| 2 | 2009-03-19T15:55:29Z | [
"python",
"cgi",
"fastcgi",
"wsgi"
] |
Can I write Python web application for Windows and Linux platforms at the same time? | 662,762 | <p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p>
<p>CGI? Maybe something new? WSGI | FastCGI ? </p>
| 3 | 2009-03-19T15:52:10Z | 662,789 | <p>Yes you can. But you can also use apache on windows. If you go the IIS way there's only CGI and it's pretty hard to set up. You can also use python based server like CherryPy which is pretty good and will work on all platforms with python.</p>
<p>Some frameworks like django support both CGI and WSGI, so you don't h... | 7 | 2009-03-19T15:55:57Z | [
"python",
"cgi",
"fastcgi",
"wsgi"
] |
Can I write Python web application for Windows and Linux platforms at the same time? | 662,762 | <p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p>
<p>CGI? Maybe something new? WSGI | FastCGI ? </p>
| 3 | 2009-03-19T15:52:10Z | 662,791 | <p>Yes, if you use CGI, FastCGI or depending on your framework, even a self-contained web server (so IIS and Apache would be a reverse-proxy) then that would all work.</p>
<p>The difference will be the configuration of the OS-specific servers, and also your Python environment on each OS. So you may find yourself doin... | 2 | 2009-03-19T15:56:14Z | [
"python",
"cgi",
"fastcgi",
"wsgi"
] |
Can I write Python web application for Windows and Linux platforms at the same time? | 662,762 | <p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p>
<p>CGI? Maybe something new? WSGI | FastCGI ? </p>
| 3 | 2009-03-19T15:52:10Z | 662,826 | <p>A rather big Python based web framework is <a href="http://www.zope.org/" rel="nofollow">ZOPE</a>.</p>
<blockquote>
<p>Zope is an open source application server for building content management systems, intranets, portals, and custom applications. The Zope community consists of hundreds of companies and thousands ... | 2 | 2009-03-19T16:03:33Z | [
"python",
"cgi",
"fastcgi",
"wsgi"
] |
Can I write Python web application for Windows and Linux platforms at the same time? | 662,762 | <p>Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?</p>
<p>CGI? Maybe something new? WSGI | FastCGI ? </p>
| 3 | 2009-03-19T15:52:10Z | 663,304 | <p>consider also the possibility of using web2Py, or XML-RPC implementation, or Twisted...</p>
| 0 | 2009-03-19T17:56:23Z | [
"python",
"cgi",
"fastcgi",
"wsgi"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.