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
ImportError: DLL load failed : - when trying to import psycopg2 library
1,306,367
<pre> >>> import psycopg2 Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: DLL load failed: The application has failed to start because its si de-by-side confi...
12
2009-08-20T13:54:40Z
1,306,396
<p>According to this <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/e1b628f0f75896f0">thread</a> you need to install an earlier version since there were problems with the latest build.</p> <blockquote> <p>Simply install an earlier version, (2.0.10 works great), even with PostgreSQL 8....
11
2009-08-20T14:00:08Z
[ "python", "django", "postgresql", "psycopg2" ]
ImportError: DLL load failed : - when trying to import psycopg2 library
1,306,367
<pre> >>> import psycopg2 Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: DLL load failed: The application has failed to start because its si de-by-side confi...
12
2009-08-20T13:54:40Z
5,789,963
<p>You can also try installing win-psycopg from <a href="http://www.stickpeople.com/projects/python/win-psycopg/">here</a></p>
7
2011-04-26T11:59:55Z
[ "python", "django", "postgresql", "psycopg2" ]
ImportError: DLL load failed : - when trying to import psycopg2 library
1,306,367
<pre> >>> import psycopg2 Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: DLL load failed: The application has failed to start because its si de-by-side confi...
12
2009-08-20T13:54:40Z
20,821,686
<p>On Windows, make sure your path includes the Postgres bin directory. In my machine it's c:\Programs\PostgreSQL\9.3\bin.</p>
11
2013-12-29T02:58:20Z
[ "python", "django", "postgresql", "psycopg2" ]
Calculating a SHA hash with a string + secret key in python
1,306,550
<p>Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.</p> <p>The step I get hung up on is this one:</p> <p>"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more inform...
26
2009-08-20T14:23:36Z
1,306,571
<p>From <a href="http://docs.python.org/library/hashlib.html#module-hashlib" rel="nofollow">http://docs.python.org/library/hashlib.html#module-hashlib</a> (modified a bit):</p> <pre><code>import hashlib secretKey = "1234567890" m = hashlib.sha256() # Get string and put into givenString. m.update(givenString + secret...
3
2009-08-20T14:27:23Z
[ "python", "hash", "sha256" ]
Calculating a SHA hash with a string + secret key in python
1,306,550
<p>Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.</p> <p>The step I get hung up on is this one:</p> <p>"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more inform...
26
2009-08-20T14:23:36Z
1,306,575
<pre><code>import hmac import hashlib import base64 dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest() base64.b64encode(dig).decode() # py3k-mode 'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg=' </code></pre>
54
2009-08-20T14:27:33Z
[ "python", "hash", "sha256" ]
Calculating a SHA hash with a string + secret key in python
1,306,550
<p>Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.</p> <p>The step I get hung up on is this one:</p> <p>"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more inform...
26
2009-08-20T14:23:36Z
1,307,439
<pre><code>&gt;&gt;&gt; import hmac &gt;&gt;&gt; import hashlib &gt;&gt;&gt; import base64 &gt;&gt;&gt; s = """GET ... webservices.amazon.com ... /onca/xml ... AWSAccessKeyId=00000000000000000000&amp;ItemId=0679722769&amp;Operation=ItemLookup&amp;ResponseGroup=ItemAttributes%2COffers%2CImages%2CReviews&amp;Service=AWSE...
9
2009-08-20T16:41:26Z
[ "python", "hash", "sha256" ]
Calculating a SHA hash with a string + secret key in python
1,306,550
<p>Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.</p> <p>The step I get hung up on is this one:</p> <p>"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more inform...
26
2009-08-20T14:23:36Z
12,165,954
<pre><code>import hmac import hashlib import base64 digest = hmac.new(secret, msg=thing_to_hash, digestmod=hashlib.sha256).digest() signature = base64.b64encode(digest).decode() </code></pre> <p>I know this sounds silly, but make sure you don't have a trailing space on your secret by accident.</p>
3
2012-08-28T19:13:36Z
[ "python", "hash", "sha256" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
1,306,653
<p>You can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.</p> <p>You can however add tuples to the set, because you cannot change the contents of a tuple:</p> <pre><code>&gt;&gt;&gt; a.add(('f', 'g')) &gt;&gt;&gt; print a set(['a', 'c'...
100
2009-08-20T14:39:51Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
1,306,663
<pre><code>&gt;&gt;&gt; a = set('abcde') &gt;&gt;&gt; l = ['f', 'g'] &gt;&gt;&gt; a |= set(l) &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd', 'g', 'f']) </code></pre> <p>The union operator is much faster than add anyway.</p> <p>edit: If you want the list itself and not its members, then you must use a tuple, unfortunate...
246
2009-08-20T14:41:46Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
1,306,673
<p><strong>list objects are unhashable</strong>. you might want to turn them in to tuples though.</p>
7
2009-08-20T14:43:17Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
1,306,677
<p>You'll want to use tuples, which are hashable (you can't hash a mutable object like a list).</p> <pre><code>&gt;&gt;&gt; a = set("abcde") &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; t = ('f', 'g') &gt;&gt;&gt; a.add(t) &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd', ('f', 'g')]) </code></pre>
3
2009-08-20T14:45:08Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
1,306,692
<p>You want to add a tuple, not a list:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; t = tuple(l) &gt;&gt;&gt; t ('f', 'g') &gt;&gt;&gt; a.add(t) &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd', ('f', 'g')]) </code>...
4
2009-08-20T14:47:02Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
1,306,696
<p>Sets can't have mutable (changeable) elements/members. A list, being mutable, cannot be a member of a set.</p> <p>As sets are mutable, you cannot have a set of sets! You can have a set of frozensets though.</p> <p>(The same kind of "mutability requirement" applies to the keys of a dict.)</p> <p>Other answers have...
3
2009-08-20T14:47:53Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
5,409,309
<p>I found I needed to do something similar today. The algorithm knew when it was creating a new list that needed to added to the set, but not when it would have finished operating on the list.</p> <p>Anyway, the behaviour I wanted was for set to use <code>id</code> rather than <code>hash</code>. As such I found <code...
2
2011-03-23T17:33:48Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
10,461,650
<p>Please notice the function <code>set.update()</code>. The documentation says:</p> <blockquote> <p>Update a set with the union of itself and others.</p> </blockquote>
7
2012-05-05T12:01:53Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
18,399,318
<p>Hopefully this helps:</p> <pre><code>&gt;&gt;&gt; seta = set('1234') &gt;&gt;&gt; listb = ['a','b','c'] &gt;&gt;&gt; seta.union(listb) set(['a', 'c', 'b', '1', '3', '2', '4']) &gt;&gt;&gt; seta set(['1', '3', '2', '4']) &gt;&gt;&gt; seta = seta.union(listb) &gt;&gt;&gt; seta set(['a', 'c', 'b', '1', '3', '2', '4'])...
25
2013-08-23T09:24:30Z
[ "python", "list", "set" ]
Python: Add list to set?
1,306,631
<p>Tested on Python 2.6 interpreter:</p> <pre><code>&gt;&gt;&gt; a=set('abcde') &gt;&gt;&gt; a set(['a', 'c', 'b', 'e', 'd']) &gt;&gt;&gt; l=['f','g'] &gt;&gt;&gt; l ['f', 'g'] &gt;&gt;&gt; a.add(l) Traceback (most recent call last): File "&lt;pyshell#35&gt;", line 1, in &lt;module&gt; a.add(l) TypeError: list o...
99
2009-08-20T14:35:42Z
21,873,769
<p>Here is how I usually do it:</p> <pre><code>def add_list_to_set(my_list, my_set): [my_set.add(each) for each in my_list] return my_set </code></pre>
2
2014-02-19T07:26:42Z
[ "python", "list", "set" ]
Mapping a nested list with List Comprehension in Python?
1,306,670
<p>I have the following code which I use to map a nested list in Python to produce a list with the same structure. </p> <pre><code>&gt;&gt;&gt; nested_list = [['Hello', 'World'], ['Goodbye', 'World']] &gt;&gt;&gt; [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] </code></pre> <p>Can...
7
2009-08-20T14:42:39Z
1,306,682
<p>For nested lists you can use nested list comprehensions:</p> <pre><code>nested_list = [[s.upper() for s in xs] for xs in nested_list] </code></pre> <p>Personally I find <code>map</code> to be cleaner in this situation, even though I almost always prefer list comprehensions. So it's really your call, since either ...
7
2009-08-20T14:45:39Z
[ "python", "list", "list-comprehension", "nested-lists", "map-function" ]
Mapping a nested list with List Comprehension in Python?
1,306,670
<p>I have the following code which I use to map a nested list in Python to produce a list with the same structure. </p> <pre><code>&gt;&gt;&gt; nested_list = [['Hello', 'World'], ['Goodbye', 'World']] &gt;&gt;&gt; [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] </code></pre> <p>Can...
7
2009-08-20T14:42:39Z
1,306,693
<p>Map is certainly a much cleaner way of doing what you want. You can nest the list comprehensions though, maybe that's what you're after?</p> <pre><code>[[ix.upper() for ix in x] for x in nested_list] </code></pre>
1
2009-08-20T14:47:07Z
[ "python", "list", "list-comprehension", "nested-lists", "map-function" ]
Mapping a nested list with List Comprehension in Python?
1,306,670
<p>I have the following code which I use to map a nested list in Python to produce a list with the same structure. </p> <pre><code>&gt;&gt;&gt; nested_list = [['Hello', 'World'], ['Goodbye', 'World']] &gt;&gt;&gt; [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] </code></pre> <p>Can...
7
2009-08-20T14:42:39Z
1,309,044
<p>Other posters have given the answer, but whenever I'm having trouble wrapping my head around a functional construct, I swallow my pride and spell it out longhand with explicitly non-optimal methods and/or objects. You said you wanted to end up with a generator, so:</p> <pre><code>for xs in n_l: def doUpper(l):...
1
2009-08-20T21:50:24Z
[ "python", "list", "list-comprehension", "nested-lists", "map-function" ]
Mapping a nested list with List Comprehension in Python?
1,306,670
<p>I have the following code which I use to map a nested list in Python to produce a list with the same structure. </p> <pre><code>&gt;&gt;&gt; nested_list = [['Hello', 'World'], ['Goodbye', 'World']] &gt;&gt;&gt; [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] </code></pre> <p>Can...
7
2009-08-20T14:42:39Z
15,419,254
<p>Remember the Zen of Python:</p> <blockquote> <p>There is generally more than one -- and probably <em>several</em> -- obvious ways to do it.**</p> </blockquote> <p>** Note: Edited for accuracy.</p> <p>Anyway, I prefer map.</p> <pre><code>from functools import partial nested_list = map( partial(map, str.upper), ...
1
2013-03-14T20:12:07Z
[ "python", "list", "list-comprehension", "nested-lists", "map-function" ]
Mapping a nested list with List Comprehension in Python?
1,306,670
<p>I have the following code which I use to map a nested list in Python to produce a list with the same structure. </p> <pre><code>&gt;&gt;&gt; nested_list = [['Hello', 'World'], ['Goodbye', 'World']] &gt;&gt;&gt; [map(str.upper, x) for x in nested_list] [['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']] </code></pre> <p>Can...
7
2009-08-20T14:42:39Z
26,133,679
<p>Here is solution for <strong><em>nested list that has arbitrary depth</em></strong>:</p> <pre><code>def map_nlist(nlist=nlist,fun=lambda x: x*2): new_list=[] for i in range(len(nlist)): if isinstance(nlist[i],list): new_list += [map_nlist(nlist[i],fun)] else: new_list...
1
2014-10-01T03:31:47Z
[ "python", "list", "list-comprehension", "nested-lists", "map-function" ]
Python __str__ versus __unicode__
1,307,014
<p>Is there a python convention for when you should implement <code>__str__()</code> versus <code>__unicode__()</code>. I've seen classes override <code>__unicode__()</code> more frequently than <code>__str__()</code> but it doesn't appear to be consistent. Are there specific rules when it is better to implement one ...
148
2009-08-20T15:34:07Z
1,307,177
<p>With the world getting smaller, chances are that any string you encounter will contain Unicode eventually. So for any new apps, you should at least provide <code>__unicode__()</code>. Whether you also override <code>__str__()</code> is then just a matter of taste.</p>
8
2009-08-20T16:00:08Z
[ "python", "string", "unicode", "conventions" ]
Python __str__ versus __unicode__
1,307,014
<p>Is there a python convention for when you should implement <code>__str__()</code> versus <code>__unicode__()</code>. I've seen classes override <code>__unicode__()</code> more frequently than <code>__str__()</code> but it doesn't appear to be consistent. Are there specific rules when it is better to implement one ...
148
2009-08-20T15:34:07Z
1,307,209
<p>If I didn't especially care about micro-optimizing stringification for a given class I'd always implement <code>__unicode__</code> only, as it's more general. When I do care about such minute performance issues (which is the exception, not the rule), having <code>__str__</code> only (when I can prove there never wil...
14
2009-08-20T16:04:22Z
[ "python", "string", "unicode", "conventions" ]
Python __str__ versus __unicode__
1,307,014
<p>Is there a python convention for when you should implement <code>__str__()</code> versus <code>__unicode__()</code>. I've seen classes override <code>__unicode__()</code> more frequently than <code>__str__()</code> but it doesn't appear to be consistent. Are there specific rules when it is better to implement one ...
148
2009-08-20T15:34:07Z
1,307,210
<p><code>__str__()</code> is the old method -- it returns bytes. <code>__unicode__()</code> is the new, preferred method -- it returns characters. The names are a bit confusing, but in 2.x we're stuck with them for compatibility reasons. Generally, you should put all your string formatting in <code>__unicode__()</code>...
186
2009-08-20T16:04:34Z
[ "python", "string", "unicode", "conventions" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,307,102
<p>If the inputs to any of your math functions are fairly constrained, you can use a lookup table instead of the math function. This can earn you some performance (speed) at the cost of extra memory to store the table.</p>
0
2009-08-20T15:47:28Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,307,113
<p>I'm not sure if this holds in Python. But calculating the sqrt is a processor intensive calculation.</p> <p>You might go for a fast approximation <a href="http://en.wikipedia.org/wiki/Methods%5Fof%5Fcomputing%5Fsquare%5Froots" rel="nofollow">newton</a></p>
0
2009-08-20T15:49:11Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,307,161
<p>The real speed increase would be gained by moving to numpy or scipy. Short of that, there are microoptimizations: e.g. <code>x*x</code> is faster than <code>pow(x,2)</code>; you could extract the values at the same time as the keys by doing, instead of:</p> <pre><code>si = [val for val in v1 if val in v2] </code></...
4
2009-08-20T15:57:29Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,307,233
<p>I'd suggest changing:</p> <pre><code>[val for val in v1 if val in v2] </code></pre> <p>to</p> <pre><code>set(v1) &amp; set(v2) </code></pre> <p>do</p> <pre><code>if not n: return 0.0 # and similar for den </code></pre> <p>instead of</p> <pre><code>if n == 0: return 0.0 </code></pre> <p>and it's worth repl...
1
2009-08-20T16:08:11Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,309,956
<p>Since it looks like you're doing quite a bit of numeric computation you should give <strong><a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a></strong> a shot. It's a JIT compiler that analyzes running code and optimizes certain operations. Install it, then at the top of your file put:</p> <pre><code...
1
2009-08-21T03:24:43Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,312,266
<p>I'll post what I've got so far as an answer to differentiate it from the question. This is a combination of some techniques described above that seem to have given the best improvement s far.</p> <pre><code>def pearson(v1,v2): vs = [(v1[val],v2[val]) for val in v1 if val in v2] n = len(vs) if n==0: re...
0
2009-08-21T14:23:36Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
1,313,774
<p>If you can use scipy, you could use the pearson function: <a href="http://www.scipy.org/doc/api%5Fdocs/SciPy.stats.stats.html#pearsonr" rel="nofollow">http://www.scipy.org/doc/api%5Fdocs/SciPy.stats.stats.html#pearsonr</a></p> <p>Or you could copy/paste the code (it has a liberal license) from <a href="http://svn.s...
2
2009-08-21T19:19:26Z
[ "python", "optimization", "similarity", "pearson" ]
Pearson Similarity Score, how can I optimise this further?
1,307,016
<p>I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise.</p> <p>Even the slightest optimisation could have a big impact on my code, so I...
2
2009-08-20T15:34:27Z
2,280,469
<p>Scipy is the fastest!</p> <p>I have don some tests with the code above and also with a version I found on my comp, see below for results and the code:</p> <pre> pearson 14.7597990757 sim_pearson 15.6806837987 scipy:pearsonr 0.451986019188 </pre> <pre> try: import psyco psyco.full() except ImportError: ...
2
2010-02-17T12:22:13Z
[ "python", "optimization", "similarity", "pearson" ]
Dynamic list slicing
1,307,019
<p>Good day code knights,</p> <p>I have a tricky problem that I cannot see a simple solution for. And the history of the humankind states that there is a simple solution for everything (excluding buying presents)</p> <p>Here is the problem:</p> <p>I need an algorithm that takes multidimensional lists and a filter di...
0
2009-08-20T15:34:45Z
1,307,112
<p>Something like the following should work:</p> <pre><code>def doit(nam, filters): alldims = [] for dimname in getDimNames(nam): filt = filters.get(dimname, ()) howmany = len(filt) if howmany == 0: sliciflt = slice() elif howmany == 1: sliciflt = filt[0] elif howm...
2
2009-08-20T15:48:57Z
[ "python", "algorithm", "list", "multidimensional-array" ]
Dynamic list slicing
1,307,019
<p>Good day code knights,</p> <p>I have a tricky problem that I cannot see a simple solution for. And the history of the humankind states that there is a simple solution for everything (excluding buying presents)</p> <p>Here is the problem:</p> <p>I need an algorithm that takes multidimensional lists and a filter di...
0
2009-08-20T15:34:45Z
1,307,117
<p>I'm not sure I understood your question. But I think the <code>slice</code> object is what you are looking for:</p> <p>First instead of an empty tuple use None to include all values in time</p> <pre><code>filters= {'x':(0,20), 'y':(3), 'z':(1,2), 'time':None} </code></pre> <p>Then build a slice dictionary like t...
3
2009-08-20T15:50:34Z
[ "python", "algorithm", "list", "multidimensional-array" ]
How do I programatically pull lists/arrays of (itunes urls to) apps in the iphone app store?
1,307,322
<p>I'd like to know how to pragmatically pull lists of apps from the iphone app store. I'd code this in python (via the google app engine) or in an iphone app. My goal would be to select maybe 5 of them and present them to the user. (for instance a top 5 kind of thing, or advanced filtering or queries)</p>
0
2009-08-20T16:21:38Z
1,307,656
<p>Unfortunately the only API that seems to be around for Apple's app store is a commercial offering from ABTO; nobody seems to have developed a free one. I'm afraid you'll have to resort to "screen scraping" -- urlget things, use beautifulsoup or the like for interpreting the HTML you get, and be ready to fix breakage...
1
2009-08-20T17:21:58Z
[ "python", "iphone", "arrays", "google-app-engine", "app-store" ]
Python test framework with support of non-fatal failures
1,307,367
<p>I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing ...
4
2009-08-20T16:28:38Z
1,307,443
<p>nose will only abort on the first failure if you pass the <code>-x</code> option at the command line.</p> <p>test.py:</p> <pre><code>def test1(): assert False def test2(): assert False </code></pre> <p>without -x option:</p> <pre> C:\temp\py>C:\Python26\Scripts\nosetests.exe test.py FF =================...
-1
2009-08-20T16:41:49Z
[ "python", "testing", "assert", "nose" ]
Python test framework with support of non-fatal failures
1,307,367
<p>I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing ...
4
2009-08-20T16:28:38Z
1,307,672
<p>I was wanting something similar for functional testing that I'm doing using nose. I eventually came up with this:</p> <pre><code>def raw_print(str, *args): out_str = str % args sys.stdout.write(out_str) class DeferredAsserter(object): def __init__(self): self.broken = False def assert_equa...
2
2009-08-20T17:25:31Z
[ "python", "testing", "assert", "nose" ]
Python test framework with support of non-fatal failures
1,307,367
<p>I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing ...
4
2009-08-20T16:28:38Z
1,307,693
<p>You asked for suggestions so I'll suggest <a href="http://code.google.com/p/robotframework/" rel="nofollow">robot framework</a>. </p>
1
2009-08-20T17:28:36Z
[ "python", "testing", "assert", "nose" ]
Python test framework with support of non-fatal failures
1,307,367
<p>I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing ...
4
2009-08-20T16:28:38Z
1,308,837
<p>Oddly enough it sounds like you're looking for something like my <a href="http://bitbucket.org/jimd/claft/" rel="nofollow"><code>claft</code></a> (command line and filter tester). Something like it but far more mature.</p> <p><code>claft</code> is (so far) just a toy I wrote to help students with programming exerc...
1
2009-08-20T21:10:09Z
[ "python", "testing", "assert", "nose" ]
Python test framework with support of non-fatal failures
1,307,367
<p>I'm evaluating "test frameworks" for automated system tests; so far I'm looking for a python framework. In py.test or nose I can't see something like the EXPECT macros I know from google testing framework. I'd like to make several assertions in one test while not aborting the test at the first failure. Am I missing ...
4
2009-08-20T16:28:38Z
1,314,470
<p>Why not (in <code>unittest</code>, but this should work in any framework):</p> <pre><code>class multiTests(MyTestCase): def testMulti(self, tests): tests( a == b ) tests( frobnicate()) ... </code></pre> <p>assuming your implemented MyTestCase so that a function is wrapped into</p> <pre...
0
2009-08-21T22:26:04Z
[ "python", "testing", "assert", "nose" ]
Python question regarding a server listener
1,307,371
<p>I wrote a plug-in for the jetbrains tool teamcity. It is pretty much just a server listener that listens for a build being triggered and outputs some text files with information about different builds like what triggered it, how many changes there where etc etc. After I finished that I wrote a python script that cou...
0
2009-08-20T16:29:03Z
1,307,578
<p>Python actually has a <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading system</a> that is fairly similar to Java, so you should be able to use that without much trouble.</p> <p>But if all you need to do is wait for some predetermined amount of time, use</p> <pre><code>import time ti...
0
2009-08-20T17:06:40Z
[ "python", "plugins", "multithreading", "teamcity", "sleep" ]
Python question regarding a server listener
1,307,371
<p>I wrote a plug-in for the jetbrains tool teamcity. It is pretty much just a server listener that listens for a build being triggered and outputs some text files with information about different builds like what triggered it, how many changes there where etc etc. After I finished that I wrote a python script that cou...
0
2009-08-20T16:29:03Z
1,307,783
<p>Unless you get get notified by having the build server contact <em>you</em>, the only way to do it is to poll. You can either spawn a thread as indicated in other comments, you just have your main script sleep and poll.</p> <p>Something like:</p> <pre><code>wait=True while wait: url=urllib.urlopen('http://'+us...
2
2009-08-20T17:47:37Z
[ "python", "plugins", "multithreading", "teamcity", "sleep" ]
Python MYSQL update statement
1,307,378
<p>I'm trying to get this Python MYSQL update statement correct(With Variables):</p> <pre><code>cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID) </code></pre> <p>Any ideas where I'm going wrong?</p>
19
2009-08-20T16:30:31Z
1,307,400
<p>It <a href="http://mysql-python.sourceforge.net/MySQLdb.html">should be</a>:</p> <pre><code>cursor.execute (""" UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server=%s """, (Year, Month, Day, Hour, Minute, ServerID)) </code></pre> <p>You can <strong>also</strong> do it with b...
41
2009-08-20T16:33:46Z
[ "python", "mysql", "mysql-python", "sql-parametrized-query" ]
Python MYSQL update statement
1,307,378
<p>I'm trying to get this Python MYSQL update statement correct(With Variables):</p> <pre><code>cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID) </code></pre> <p>Any ideas where I'm going wrong?</p>
19
2009-08-20T16:30:31Z
1,307,413
<p>You've got the syntax all wrong:</p> <pre><code>cursor.execute (""" UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server=%s """, (Year, Month, Day, Hour, Minute, ServerID)) </code></pre> <p>For more, <a href="http://mysql-python.sourceforge.net/MySQLdb.html">read the document...
32
2009-08-20T16:35:46Z
[ "python", "mysql", "mysql-python", "sql-parametrized-query" ]
Python MYSQL update statement
1,307,378
<p>I'm trying to get this Python MYSQL update statement correct(With Variables):</p> <pre><code>cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID) </code></pre> <p>Any ideas where I'm going wrong?</p>
19
2009-08-20T16:30:31Z
38,802,132
<p>This is the right way:</p> <pre><code>import MySQLdb if __name__ == '__main__': connect = MySQLdb.connect(host="localhost", port=3306, user="xxx", passwd="xxx", db='xxx', charset='utf8') cursor = connect.cursor() cursor.execute(""" UPDATE tblTableName SET...
1
2016-08-06T08:20:53Z
[ "python", "mysql", "mysql-python", "sql-parametrized-query" ]
Python MYSQL update statement
1,307,378
<p>I'm trying to get this Python MYSQL update statement correct(With Variables):</p> <pre><code>cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID) </code></pre> <p>Any ideas where I'm going wrong?</p>
19
2009-08-20T16:30:31Z
39,004,054
<p>Neither of them worked for me for some reason.</p> <p>I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.</p> <p>And finally this worked for me.</p> <pre><code> cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4")) cursor.co...
0
2016-08-17T18:40:34Z
[ "python", "mysql", "mysql-python", "sql-parametrized-query" ]
Django many-to-many relations, and through
1,307,548
<p>I want to store which user invited another user to a group... but django is telling me this is ambigous and against the rules (which makes sense). </p> <blockquote> <p>groups.group: Intermediary model Group_to_Member has more than one foreign key to User, which is ambiguous and is not permitted.</p> </block...
10
2009-08-20T17:01:55Z
1,307,689
<p>You have to manage it yourself:</p> <pre><code>class MyGroup(models.Model): name = models.CharField(max_length=100) class Membership(models.Model): group = models.ForeignKey(MyGroup) member = models.ForeignKey(User) invited_by = models.ForeignKey(User, related_name='invited_set') </code></pre> <p...
8
2009-08-20T17:27:49Z
[ "python", "django", "foreign-keys", "many-to-many" ]
Django many-to-many relations, and through
1,307,548
<p>I want to store which user invited another user to a group... but django is telling me this is ambigous and against the rules (which makes sense). </p> <blockquote> <p>groups.group: Intermediary model Group_to_Member has more than one foreign key to User, which is ambiguous and is not permitted.</p> </block...
10
2009-08-20T17:01:55Z
22,821,162
<p>It is possible if you are using Django 1.7. </p> <p>From the docs: <a href="https://docs.djangoproject.com/en/1.7/topics/db/models/#extra-fields-on-many-to-many-relationships" rel="nofollow">https://docs.djangoproject.com/en/1.7/topics/db/models/#extra-fields-on-many-to-many-relationships</a></p> <blockquote> <p...
0
2014-04-02T19:27:52Z
[ "python", "django", "foreign-keys", "many-to-many" ]
Python - MYSQL - Select leading zeros
1,308,038
<p>When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed.</p> <p>Is there any way to pull all of the number i.e. including the leading zero?</p>
0
2009-08-20T18:36:39Z
1,308,060
<p>There's almost certainly something in either your query, your table definition, or an ORM you're using that thinks the column is numeric and is converting the results to integers. You'll have to define the column as a string (everywhere!) if you want to preserve leading zeroes.</p> <p>Edit: <code>ZEROFILL</code> o...
3
2009-08-20T18:40:11Z
[ "python", "mysql" ]
Python - MYSQL - Select leading zeros
1,308,038
<p>When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed.</p> <p>Is there any way to pull all of the number i.e. including the leading zero?</p>
0
2009-08-20T18:36:39Z
1,308,068
<p>What data type is the column? If you want to preserve leading zeros, you should probably use a non-numeric column type such as <code>VARCHAR</code>.</p> <p>To format numbers with leading zeros in Python, use a format specifier:</p> <pre><code>&gt;&gt;&gt; print "%02d" % (1,) 01 </code></pre>
0
2009-08-20T18:41:01Z
[ "python", "mysql" ]
Python - MYSQL - Select leading zeros
1,308,038
<p>When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed.</p> <p>Is there any way to pull all of the number i.e. including the leading zero?</p>
0
2009-08-20T18:36:39Z
1,308,102
<p>MySQL supports this in the column definition:</p> <pre><code>CREATE TABLE MyTable ( i TINYINT(2) ZEROFILL ); INSERT INTO MyTable (i) VALUES (9); SELECT * FROM MyTable; +------+ | i | +------+ | 09 | +------+ </code></pre>
3
2009-08-20T18:47:26Z
[ "python", "mysql" ]
Python - MYSQL - Select leading zeros
1,308,038
<p>When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed.</p> <p>Is there any way to pull all of the number i.e. including the leading zero?</p>
0
2009-08-20T18:36:39Z
1,308,477
<p>You could run each query on that column through a function such as:</p> <pre><code>if len(str(number)) == 1: number = "0" + str(number) </code></pre> <p>This would cast the number to a string but as far as I know, Python doesn't allow leading zeroes in its number datatypes. Someone correct me if I'm wrong.</p> <p...
0
2009-08-20T20:01:09Z
[ "python", "mysql" ]
Python - MYSQL - Select leading zeros
1,308,038
<p>When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed.</p> <p>Is there any way to pull all of the number i.e. including the leading zero?</p>
0
2009-08-20T18:36:39Z
12,950,072
<p>Best option will be using <code>CAST</code> as suggested by <code>Eevee</code> but you have to use <code>CAST ( ur_field AS CHAR(2) )</code> as casting to <code>varchar</code> has this problem as given in this post</p> <p><a href="http://stackoverflow.com/questions/1873085/how-to-convert-from-varbinary-to-char-var...
1
2012-10-18T08:18:00Z
[ "python", "mysql" ]
Calling Python from Objective-C
1,308,079
<p>I'm developing a Python/ObjC application and I need to call some methods in my Python classes from ObjC. I've tried several stuffs with no success. </p> <ul> <li>How can I call a Python method from Objective-C?</li> <li>My Python classes are being instantiated in Interface Builder. How can I call a method from that...
8
2009-08-20T18:42:48Z
1,308,469
<p>Use PyObjC.</p> <p>It is included with Leopard &amp; later.</p> <pre><code>&gt;&gt;&gt; from Foundation import * &gt;&gt;&gt; a = NSArray.arrayWithObjects_("a", "b", "c", None) &gt;&gt;&gt; a ( a, b, c ) &gt;&gt;&gt; a[1] 'b' &gt;&gt;&gt; a.objectAtIndex_(1) 'b' &gt;&gt;&gt; type(a) &lt;objective...
17
2009-08-20T19:58:17Z
[ "python", "objective-c", "cocoa" ]
In Django how to show a list of objects by year
1,308,169
<p>I have theses models:</p> <pre><code>class Year(models.Model): name = models.CharField(max_length=15) date = models.DateField() class Period(models.Model): name = models.CharField(max_length=15) date = models.DateField() class Notice(models.Model): year = models.ForeignKey(Year) period = m...
1
2009-08-20T18:59:43Z
1,308,261
<p>Luckily Django has some built-in template tags that will help you. Probably the main one you want is <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup" rel="nofollow">regroup</a>:</p> <pre><code>{% regroup notices by year as year_list %} {% for year in year_list %} &lt;h2&gt;{{ year....
2
2009-08-20T19:14:18Z
[ "python", "django" ]
In Django how to show a list of objects by year
1,308,169
<p>I have theses models:</p> <pre><code>class Year(models.Model): name = models.CharField(max_length=15) date = models.DateField() class Period(models.Model): name = models.CharField(max_length=15) date = models.DateField() class Notice(models.Model): year = models.ForeignKey(Year) period = m...
1
2009-08-20T18:59:43Z
1,308,291
<p>Your problem would not actually be that hard if not for the unfortunate denormalization you have going on. I'm going to answer your question ignoring the <code>Year</code> class, because I don't understand how that logic relates to the period logic.</p> <p>Most simply, in the template, put:</p> <pre><code>{% for ...
1
2009-08-20T19:19:48Z
[ "python", "django" ]
Do any Python ORMs (SQLAlchemy?) work with Google App Engine?
1,308,376
<p>I'd like to use the Python version of App Engine but rather than write my code specifically for the Google Data Store, I'd like to create my models with a generic Python ORM that could be attached to Big Table, or, if I prefer, a regular database at some later time. Is there any Python ORM such as SQLAlchemy that wo...
10
2009-08-20T19:39:35Z
1,309,598
<p>Technically this wouldn't be called an ORM (Object Relational Mapper) but a DAL (Database Abstraction Layer). The ORM part is not really interesting for AppEngine as the API already takes care of the object mapping and does some simple relational mapping (see RelationProperty).</p> <p>Also realize that a DAL will n...
7
2009-08-21T00:55:34Z
[ "python", "google-app-engine", "sqlalchemy", "orm" ]
Do any Python ORMs (SQLAlchemy?) work with Google App Engine?
1,308,376
<p>I'd like to use the Python version of App Engine but rather than write my code specifically for the Google Data Store, I'd like to create my models with a generic Python ORM that could be attached to Big Table, or, if I prefer, a regular database at some later time. Is there any Python ORM such as SQLAlchemy that wo...
10
2009-08-20T19:39:35Z
11,325,656
<p>Nowadays they do since Google has launched Cloud SQL</p>
3
2012-07-04T08:53:46Z
[ "python", "google-app-engine", "sqlalchemy", "orm" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
1,309,172
<p>This is might not be the answer you are looking for. but you can use charfield to store the path of the file instead of ImageFile. In that way you can programmatically associate uploaded image to field without recreating the file.</p>
1
2009-08-20T22:26:14Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
1,309,682
<p>I have some code that fetches an image off the web and stores it in a model. The important bits are:</p> <pre><code>from django.core.files import File # you need this somewhere import urllib # The following actually resides in a method of my model result = urllib.urlretrieve(image_url) # image_url is a URL to ...
121
2009-08-21T01:32:50Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
3,323,465
<p>Just a little remark. tvon answer works but, if you're working on windows, you probably want to open() the file with 'rb'. Like this:</p> <pre><code>class CachedImage(models.Model): url = models.CharField(max_length=255, unique=True) photo = models.ImageField(upload_to=photo_path, blank=True) def cache...
30
2010-07-24T01:37:20Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
4,230,210
<p>What I did was to create my own storage that will just not save the file to the disk:</p> <pre><code>from django.core.files.storage import FileSystemStorage class CustomStorage(FileSystemStorage): def _open(self, name, mode='rb'): return File(open(self.path(name), mode)) def _save(self, name, con...
8
2010-11-19T23:08:23Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
5,256,094
<p>If you want to just "set" the actual filename, without incurring the overhead of loading and re-saving the file (!!), or resorting to using a charfield (!!!), you might want to try something like this --</p> <pre><code>model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myf...
6
2011-03-10T06:06:30Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
5,772,151
<p>You can try:</p> <pre><code>model.ImageField.path = os.path.join('/Upload', generated_image_path) </code></pre>
0
2011-04-24T17:44:09Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
6,566,011
<p>Here is a method that works well and allows you to convert the file to a certain format as well (to avoid "cannot write mode P as JPEG" error): </p> <pre><code>import urllib2 from django.core.files.base import ContentFile from StringIO import StringIO def download_image(name, image, url): input_file = StringIO...
10
2011-07-03T22:47:20Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
12,917,845
<p>Super easy if model hasn't been created yet:</p> <p><strong>First</strong>, copy your image file to the upload path (assumed = <strong>'path/'</strong> in following snippet).</p> <p><strong>Second</strong>, use something like:</p> <pre><code>class Layout(models.Model): image = models.ImageField('img', upload_...
47
2012-10-16T15:11:28Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
14,306,661
<pre><code>class tweet_photos(models.Model): upload_path='absolute path' image=models.ImageField(upload_to=upload_path) image_url = models.URLField(null=True, blank=True) def save(self, *args, **kwargs): if self.image_url: import urllib, os from urlparse import urlparse file_save_dir = self....
0
2013-01-13T18:22:31Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
19,037,233
<p>Ok, If all you need to do is associate the already existing image file path with the ImageField, then this solution may be helpfull:</p> <pre><code>from django.core.files.base import ContentFile with open('/path/to/already/existing/file') as f: data = f.read() # obj.image is the ImageField obj.image.save('imgfi...
4
2013-09-26T19:41:29Z
[ "python", "django", "django-models" ]
Programmatically saving image to Django ImageField
1,308,386
<p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the Im...
139
2009-08-20T19:42:39Z
39,525,265
<pre><code>class Pin(models.Model): """Pin Class""" image_link = models.CharField(max_length=255, null=True, blank=True) image = models.ImageField(upload_to='images/', blank=True) title = models.CharField(max_length=255, null=True, blank=True) source_name = models.CharField(max_length=255, null=True...
0
2016-09-16T06:45:15Z
[ "python", "django", "django-models" ]
How to catch 404 error in urllib.urlretrieve
1,308,542
<p>Background: I am using <a href="http://docs.activestate.com/activepython/2.6/python/library/urllib.html"><code>urllib.urlretrieve</code></a>, as opposed to any other function in the <code>urllib*</code> modules, because of the hook function support (see <code>reporthook</code> below) .. which is used to display a te...
21
2009-08-20T20:14:39Z
1,308,846
<p>Check out <code>urllib.urlretrieve</code>'s complete code:</p> <pre><code>def urlretrieve(url, filename=None, reporthook=None, data=None): global _urlopener if not _urlopener: _urlopener = FancyURLopener() return _urlopener.retrieve(url, filename, reporthook, data) </code></pre> <p>In other words, you ca...
27
2009-08-20T21:11:37Z
[ "python", "http", "url", "urllib" ]
How to catch 404 error in urllib.urlretrieve
1,308,542
<p>Background: I am using <a href="http://docs.activestate.com/activepython/2.6/python/library/urllib.html"><code>urllib.urlretrieve</code></a>, as opposed to any other function in the <code>urllib*</code> modules, because of the hook function support (see <code>reporthook</code> below) .. which is used to display a te...
21
2009-08-20T20:14:39Z
1,308,858
<p>The URL Opener object's "retreive" method supports the reporthook and throws an exception on 404.</p> <p><a href="http://docs.python.org/library/urllib.html#url-opener-objects" rel="nofollow">http://docs.python.org/library/urllib.html#url-opener-objects</a></p>
2
2009-08-20T21:13:46Z
[ "python", "http", "url", "urllib" ]
How to catch 404 error in urllib.urlretrieve
1,308,542
<p>Background: I am using <a href="http://docs.activestate.com/activepython/2.6/python/library/urllib.html"><code>urllib.urlretrieve</code></a>, as opposed to any other function in the <code>urllib*</code> modules, because of the hook function support (see <code>reporthook</code> below) .. which is used to display a te...
21
2009-08-20T20:14:39Z
2,202,866
<p>You should use:</p> <pre><code>import urllib2 try: resp = urllib2.urlopen("http://www.google.com/this-gives-a-404/") except urllib2.URLError, e: if not hasattr(e, "code"): raise resp = e print "Gave", resp.code, resp.msg print "=" * 80 print resp.read(80) </code></pre> <p><em>Edit:</em> The r...
14
2010-02-04T20:17:57Z
[ "python", "http", "url", "urllib" ]
Embedding Windows Python in Cygwin/GCC C++ program
1,308,558
<p>I am currently working on a Cygwin/GCC application written in C++. The application requires embedding of python to run plug-ins, I've successfully embedded using the Cygwin python libraries and was able to run simple python files as part of the program. However, the python files now require the use of a windows GUI ...
1
2009-08-20T20:17:15Z
1,308,764
<p>Not a direct answer, but you could split the system into 2 processes - the Cygwin one (Python &amp; C++, no wxPython) and the win32 one (Python &amp; wxPython) and communicate between them with <a href="http://rpyc.wikidot.com/" rel="nofollow">RPyC</a>, XML-RPC, etc.</p>
0
2009-08-20T20:57:03Z
[ "c++", "python", "windows", "cygwin", "embedding" ]
Embedding Windows Python in Cygwin/GCC C++ program
1,308,558
<p>I am currently working on a Cygwin/GCC application written in C++. The application requires embedding of python to run plug-ins, I've successfully embedded using the Cygwin python libraries and was able to run simple python files as part of the program. However, the python files now require the use of a windows GUI ...
1
2009-08-20T20:17:15Z
5,630,081
<p>It looks like you have a 32 bit / 64 bit mismatch. </p> <p>You are running code on a 64bit machine (because there is a SysWow64 folder), but my guess is that your python25.dll is 32 bit. What is confusing is that "system32" contains 64 bit DLLs.</p> <p>+I don't think debug is on, you only see the public symbols.</...
0
2011-04-12T03:28:12Z
[ "c++", "python", "windows", "cygwin", "embedding" ]
Is it possible to peek at the data in a urllib2 response?
1,308,584
<p>I need to detect character encoding in HTTP responses. To do this I look at the headers, then if it's not set in the content-type header I have to peek at the response and look for a "<code>&lt;meta http-equiv='content-type'&gt;</code>" header. I'd like to be able to write a function that looks and works something...
1
2009-08-20T20:20:30Z
1,308,636
<ol> <li>If it's in the HTTP headers (not the document itself) you could use <code>response.info()</code> to detect the encoding</li> <li><p>If you want to parse the HTML, save the response data:</p> <pre><code>page_text = response.read() encoding = detect_html_encoding(response, page_text) </code></pre></li> </ol>
0
2009-08-20T20:30:44Z
[ "python", "html", "http", "encoding", "urllib2" ]
Is it possible to peek at the data in a urllib2 response?
1,308,584
<p>I need to detect character encoding in HTTP responses. To do this I look at the headers, then if it's not set in the content-type header I have to peek at the response and look for a "<code>&lt;meta http-equiv='content-type'&gt;</code>" header. I'd like to be able to write a function that looks and works something...
1
2009-08-20T20:20:30Z
1,309,764
<pre><code>def detectit(response): # try headers &amp;c, then, worst case...: content = response.read() response.read = lambda: content # now detect based on content </code></pre> <p>The trick of course is ensuring that <code>response.read()</code> WILL return the same thing again if needed... that's why w...
4
2009-08-21T02:05:26Z
[ "python", "html", "http", "encoding", "urllib2" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
1,308,621
<p>You can attach a message to an <code>assert</code>:</p> <pre><code>assert 6-(3*2), "always fails" </code></pre> <p>The message can also be built dynamically:</p> <pre><code>assert x != 0, "x is not equal to zero (%d)" % x </code></pre> <p>See <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-asse...
5
2009-08-20T20:28:04Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
1,308,629
<p>Add a message to your assertion, which will be displayed if the assertion fails:</p> <pre><code>$ python -c "assert 6-(3*2), '6-(3*2)'" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; AssertionError: 6-(3*2) </code></pre> <p>The only way I can think of to provide this automati...
0
2009-08-20T20:29:13Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
1,308,835
<p><a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/plugins/failuredetail.html">The nose testing suite applies introspection to asserts</a>. </p> <p>However, AFAICT, you have to call <em>their</em> asserts to get the introspection:</p> <pre><code>import nose def test1(): nose.tools.assert_equal(6...
4
2009-08-20T21:09:49Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
1,309,039
<p>As <a href="http://stackoverflow.com/questions/1308607/python-assert-improved-introspection-of-failure/1308835#1308835">@Mark Rushakoff said</a> <code>nose</code> can evaluate failed asserts. It works on the standard <code>assert</code> too.</p> <pre><code># test_error_reporting.py def test(): a,b,c = 6, 2, 3 ...
7
2009-08-20T21:49:36Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
1,309,812
<p>Install your of function as <code>sys.excepthook</code> -- see <a href="http://docs.python.org/library/sys.html#sys.excepthook">the docs</a>. Your function, if the second argument is <code>AssertionError</code>, can introspect to your heart's contents; in particular, through the third argument, the traceback, it can...
10
2009-08-21T02:25:37Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
1,314,458
<p>It sounds like what you really want to do is to set up a debugger breakpoint just before the <code>assert</code> and inspect from your favorite debugger as much as you like.</p>
0
2009-08-21T22:21:06Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
Python assert -- improved introspection of failure?
1,308,607
<p>This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names): </p> <pre><code>$ python -c "assert 6-(3*2)" [...] AssertionError </code></pre> <p>Is there a better <code>assert</code> implementation in Python that is more fancy?...
10
2009-08-20T20:25:23Z
35,864,193
<p>I coded a replacement for <code>sys.excepthook</code> (which is called for any unhandled exception) which is a bit more fancy than the standard one. It will analyze the line where the exception occured and print all variables which are referred to in this line (it does not print all local variables because that migh...
0
2016-03-08T09:57:37Z
[ "python", "debugging", "assert", "syntactic-sugar" ]
How I can add a Widget or a Region to an Status Icon in PyGTK
1,308,679
<p>This is my first question in StackOverflow, so I would try to explain my self the best I can.</p> <p>I made an small app trying to emularte the windows Procastination Killer Application, using pygtk and pygame for the sound alerts.</p> <p>Here is a video of my little app running <a href="http://www.youtube.com/wat...
0
2009-08-20T20:39:15Z
1,308,693
<p>GTK+ doesn't support arbitrary widgets in the notification area, because these don't work well in Windows. You probably want to write a panel applet instead -- <a href="http://www.pygtk.org/articles/applets%5Farturogf/" rel="nofollow">here's a tutorial for panel applets in PyGTK</a>.</p>
2
2009-08-20T20:42:49Z
[ "python", "gtk", "pygtk", "trayicon", "tray" ]
Transparency in PNGs with reportlab 2.3
1,308,710
<p>I have two PNGs that I am trying to combine into a PDF using ReportLab 2.3 on Python 2.5. When I use canvas.drawImage(ImageReader) to write either PNG onto the canvas and save, the transparency comes out black. If I use PIL (1.1.6) to generate a new Image, then paste() either PNG onto the PIL Image, it composits j...
15
2009-08-20T20:45:23Z
1,311,056
<p>ReportLab uses PIL for managing images. Currently, PIL trunk has patch applied to support transparent PNGs, but you will have to wait for a 1.1.6 release if you need stable package.</p>
0
2009-08-21T10:00:56Z
[ "python", "python-imaging-library", "reportlab" ]
Transparency in PNGs with reportlab 2.3
1,308,710
<p>I have two PNGs that I am trying to combine into a PDF using ReportLab 2.3 on Python 2.5. When I use canvas.drawImage(ImageReader) to write either PNG onto the canvas and save, the transparency comes out black. If I use PIL (1.1.6) to generate a new Image, then paste() either PNG onto the PIL Image, it composits j...
15
2009-08-20T20:45:23Z
1,625,350
<p>Passing the <strong>mask parameter</strong> with a value of 'auto' to <code>drawImage</code> fixes this for me.</p> <pre><code>drawImage(......., mask='auto') </code></pre> <p><a href="http://www.reportlab.com/apis/reportlab/dev/pdfgen.html#reportlab.pdfgen.canvas.Canvas.drawImage">More information on the drawImag...
36
2009-10-26T15:01:40Z
[ "python", "python-imaging-library", "reportlab" ]
Transparency in PNGs with reportlab 2.3
1,308,710
<p>I have two PNGs that I am trying to combine into a PDF using ReportLab 2.3 on Python 2.5. When I use canvas.drawImage(ImageReader) to write either PNG onto the canvas and save, the transparency comes out black. If I use PIL (1.1.6) to generate a new Image, then paste() either PNG onto the PIL Image, it composits j...
15
2009-08-20T20:45:23Z
28,385,327
<p>I've found that <code>mask='auto'</code> has stopped working for me with reportlab 3.1.8. In the docs it says to pass the values that you want masked out. So what works for me now is <code>mask=[0, 2, 0, 2, 0, 2, ]</code>. Basically it looks like this `mask=[red_start, red_end, green_start, green_end, blue_start, bl...
1
2015-02-07T17:43:38Z
[ "python", "python-imaging-library", "reportlab" ]
cURL: https through a proxy
1,308,760
<p>I need to make a cURL request to a https URL, but I have to go through a proxy as well. Is there some problem with doing this? I have been having so much trouble doing this with curl and php, that I tried doing it with urllib2 in Python, only to find that urllib2 cannot POST to https when going through a proxy. I...
1
2009-08-20T20:56:12Z
1,308,768
<p>No problem since the proxy server supports the CONNECT method.</p>
0
2009-08-20T20:58:08Z
[ "php", "python", "curl", "https", "urllib2" ]
cURL: https through a proxy
1,308,760
<p>I need to make a cURL request to a https URL, but I have to go through a proxy as well. Is there some problem with doing this? I have been having so much trouble doing this with curl and php, that I tried doing it with urllib2 in Python, only to find that urllib2 cannot POST to https when going through a proxy. I...
1
2009-08-20T20:56:12Z
1,314,698
<p>I find testing with command-line curl a big help before moving to PHP/cURL.</p> <p>For example, w/ command-line, unless you've configured certificates, you'll need <code>-k</code> switch. And to go through a proxy, it's the <code>-x &lt;proxyhost[:port]&gt;</code> switch.</p> <p>I believe the <code>-k</code> equiv...
2
2009-08-21T23:56:17Z
[ "php", "python", "curl", "https", "urllib2" ]
Simulate multiple IP addresses for testing
1,308,879
<p>I need to simulate multiple embedded server devices that are typically used for motor control. In real life, there can be multiple servers on the network and our desktop software acts as a client to all the motor servers simultaneously. We have a half-dozen of these motor control servers on hand for basic testing,...
4
2009-08-20T21:17:02Z
1,308,897
<p>Normally you just listen on 0.0.0.0. This is an alias for <em>all</em> IP addresses.</p>
2
2009-08-20T21:20:28Z
[ ".net", "python", "networking", "sockets" ]
Simulate multiple IP addresses for testing
1,308,879
<p>I need to simulate multiple embedded server devices that are typically used for motor control. In real life, there can be multiple servers on the network and our desktop software acts as a client to all the motor servers simultaneously. We have a half-dozen of these motor control servers on hand for basic testing,...
4
2009-08-20T21:17:02Z
1,308,972
<p>You should set up a virtual network adapter. They are called TAP/TUN devices. If you are using windows, you can easily setup some dummy addresses with somthing like this:</p> <p><a href="http://www.ntkernel.com/w&amp;p.php?id=32">http://www.ntkernel.com/w&amp;p.php?id=32</a></p> <p>Good luck!</p>
5
2009-08-20T21:33:30Z
[ ".net", "python", "networking", "sockets" ]
Simulate multiple IP addresses for testing
1,308,879
<p>I need to simulate multiple embedded server devices that are typically used for motor control. In real life, there can be multiple servers on the network and our desktop software acts as a client to all the motor servers simultaneously. We have a half-dozen of these motor control servers on hand for basic testing,...
4
2009-08-20T21:17:02Z
1,309,096
<p>A. consider using Bonjour (zeroconf) for service discovery</p> <p>B. You can assign 1 or more IP addresses the same NIC:</p> <p>On XP, Start -> Control Panel -> Network Connections and select properties on your NIC (usually 'Local Area Connection').</p> <p>Scroll down to Internet Protocol (TCP/IP), select it and ...
3
2009-08-20T22:03:32Z
[ ".net", "python", "networking", "sockets" ]
Running function 5 seconds after pygtk widget is shown
1,309,006
<p>How to run function 5 seconds after pygtk widget is shown?</p>
11
2009-08-20T21:39:46Z
1,309,257
<p>You can use <strong><a href="http://library.gnome.org/devel/pygobject/stable/glib-functions.html#function-glib--timeout-add">glib.timeout_add(<em>interval</em>, <em>callback</em>, <em>...</em>)</a></strong> to periodically call a function.</p> <p>If the function returns <em>True</em> then it will be called again af...
14
2009-08-20T22:49:06Z
[ "python", "function", "time", "pygtk" ]
Running function 5 seconds after pygtk widget is shown
1,309,006
<p>How to run function 5 seconds after pygtk widget is shown?</p>
11
2009-08-20T21:39:46Z
1,309,404
<p>If the time is not critical to be exact to the tenth of a second, use</p> <pre><code>glib.timeout_add_seconds(5, ..) </code></pre> <p>else as above.</p> <p>*timeout_add_seconds* allows the system to align timeouts to other events, in the long run reducing CPU wakeups (especially if the timeout is reocurring) and ...
9
2009-08-20T23:30:22Z
[ "python", "function", "time", "pygtk" ]
Fast string to integer conversion in Python
1,309,123
<p>A simple problem, really: you have one billion (1e+9) unsigned 32-bit integers stored as decimal ASCII strings in a TSV (tab-separated values) file. Conversion using <code>int()</code> is horribly slow compared to other tools working on the same dataset. Why? And more importantly: how to make it faster?</p> <p>Ther...
3
2009-08-20T22:11:33Z
1,309,132
<p>I might suggest that for raw speed, Python isn't the right tool for this task. A hand-coded C implementation will beat Python easily.</p>
5
2009-08-20T22:15:05Z
[ "python", "performance", "optimization" ]
Fast string to integer conversion in Python
1,309,123
<p>A simple problem, really: you have one billion (1e+9) unsigned 32-bit integers stored as decimal ASCII strings in a TSV (tab-separated values) file. Conversion using <code>int()</code> is horribly slow compared to other tools working on the same dataset. Why? And more importantly: how to make it faster?</p> <p>Ther...
3
2009-08-20T22:11:33Z
1,309,181
<p>Agree with Greg; Python, as an interpreted language, is generally slow. You could try compiling the source code on-the-fly with the <a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco library</a> or coding the app in a lower level language such C/C++.</p>
0
2009-08-20T22:30:12Z
[ "python", "performance", "optimization" ]
Fast string to integer conversion in Python
1,309,123
<p>A simple problem, really: you have one billion (1e+9) unsigned 32-bit integers stored as decimal ASCII strings in a TSV (tab-separated values) file. Conversion using <code>int()</code> is horribly slow compared to other tools working on the same dataset. Why? And more importantly: how to make it faster?</p> <p>Ther...
3
2009-08-20T22:11:33Z
1,309,572
<p>It may not be an option for you, but I would look real hard at using a binary file rather than text. Does it change often? If not, you could pre-process it.</p>
0
2009-08-21T00:46:17Z
[ "python", "performance", "optimization" ]
Fast string to integer conversion in Python
1,309,123
<p>A simple problem, really: you have one billion (1e+9) unsigned 32-bit integers stored as decimal ASCII strings in a TSV (tab-separated values) file. Conversion using <code>int()</code> is horribly slow compared to other tools working on the same dataset. Why? And more importantly: how to make it faster?</p> <p>Ther...
3
2009-08-20T22:11:33Z
1,310,262
<p>You will get some percentage of speed by ensuring only "local" variables are used in your tightest of loops. The <code>int</code> function is a global, so looking it up will be more expensive than a local.</p> <p>Do you really need all billion numbers in memory at all times. Consider using some iterators to give yo...
3
2009-08-21T05:53:31Z
[ "python", "performance", "optimization" ]
Fast string to integer conversion in Python
1,309,123
<p>A simple problem, really: you have one billion (1e+9) unsigned 32-bit integers stored as decimal ASCII strings in a TSV (tab-separated values) file. Conversion using <code>int()</code> is horribly slow compared to other tools working on the same dataset. Why? And more importantly: how to make it faster?</p> <p>Ther...
3
2009-08-20T22:11:33Z
1,310,375
<p>As others have said you could code up your own C module to do the parsing/conversion for you. Then you could simply import that and call on it. You might be able to use Pyrex or its Cython derivative to generate your C from your Python (by adding a few type constraining hints to the Python).</p> <p>You can read m...
1
2009-08-21T06:56:00Z
[ "python", "performance", "optimization" ]