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
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
844,828
<p>I ended up adding a method to the model in question, and that method can be accessed like an attribute in the template.</p> <p>Still, i think it would be great if a built in tag allowed you to dynamically lookup an attribute, since this is a problem a lot of us constantly have in our templates. </p>
2
2009-05-10T06:32:43Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
1,112,236
<p>I also had to <a href="http://snipt.net/Fotinakis/django-template-tag-for-dynamic-attribute-lookups/">write this code</a> as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a <strong>getitem</strong> lookup...
48
2009-07-10T22:09:44Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
9,778,611
<p>Keeping the distinction between get and getattr, </p> <pre><code>@register.filter(name='get') def get(o, index): try: return o[index] except: return settings.TEMPLATE_STRING_IF_INVALID @register.filter(name='getattr') def getattrfilter(o, attr): try: return getattr(o, attr) ...
2
2012-03-19T22:01:55Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
27,964,123
<p>That snippet saved my day but i needed it to span it over relations so I changed it to split the arg by "." and recursively get the value. It could be done in one line: <code>return getattribute(getattribute(value,str(arg).split(".")[0]),".".join(str(arg).split(".")[1:]))</code> but I left it in 4 for readability. I...
0
2015-01-15T13:03:27Z
[ "python", "django", "django-templates" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For...
1
2009-05-10T07:44:22Z
844,907
<p>It is possible to map string operations to numbers:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; ops = {1:string.split, 2:string.replace} &gt;&gt;&gt; my = "a,b,c" &gt;&gt;&gt; ops[1](",", my) [','] &gt;&gt;&gt; ops[1](my, ",") ['a', 'b', 'c'] &gt;&gt;&gt; ops[2](my, ",", "-") 'a-b-c' &gt;&gt;&gt; </code>...
2
2009-05-10T08:02:55Z
[ "python" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For...
1
2009-05-10T07:44:22Z
844,923
<p>If you insist on numbers, you can't do much better than a dict (as gimel suggests) or list of functions (with indices zero and up). With names, though, you don't necessarily need an auxiliary data structure (such as gimel's suggested dict), since you can simply use getattr to retrieve the method to call from the ob...
2
2009-05-10T08:18:04Z
[ "python" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For...
1
2009-05-10T07:44:22Z
845,041
<p>First of all, many string functions – including strip and replace – are <a href="http://docs.python.org/library/string.html#deprecated-string-functions" rel="nofollow" title="Deprecated string functions">deprecated</a>. The following answer uses string methods instead. (Instead of <code>string.strip(" Hello ")</...
2
2009-05-10T10:04:52Z
[ "python" ]
Defining dynamic functions to a string
844,886
<p>I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For...
1
2009-05-10T07:44:22Z
845,875
<p>To map names (or numbers) to different string operations, I'd do something like</p> <pre><code>OPERATIONS = dict( strip = str.strip, lower = str.lower, removespaces = lambda s: s.replace(' ', ''), maketitle = lamdba s: s.title().center(80, '-'), # etc ) def process(myfile, ops): for line in...
0
2009-05-10T18:57:59Z
[ "python" ]
"x Days ago' template filter in Django?
845,009
<p>I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?</p>
7
2009-05-10T09:35:55Z
845,014
<p>Have a look at the <a href="http://docs.djangoproject.com/en/1.0/ref/templates/builtins/#timesince">timesince</a> template filter. It's builtin.</p> <p>The following returns a humanized diff between now and <code>comment_date</code> (e.g. <code>'8 hours'</code>):</p> <pre><code>{{ comment_date|timesince }} </code>...
21
2009-05-10T09:43:02Z
[ "python", "django" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,069
<p>You could execute a subprocess and run <code>wc -l filename</code></p> <pre><code>import subprocess def file_len(fname): p = subprocess.Popen(['wc', '-l', fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, err = p.communicate() if p.returncode...
49
2009-05-10T10:28:29Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,075
<pre><code>def file_len(full_path): """ Count number of lines in a file.""" f = open(full_path) nr_of_lines = sum(1 for line in f) f.close() return nr_of_lines </code></pre>
5
2009-05-10T10:33:41Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,081
<p>You can't get any better than that.</p> <p>After all, any solution will have to read the entire file, figure out how many <code>\n</code> you have, and return that result.</p> <p>Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you...
157
2009-05-10T10:37:42Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,151
<p>As for me this variant will be the fastest:</p> <pre><code>#!/usr/bin/env python def main(): f = open('filename') lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(b...
3
2009-05-10T11:29:12Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,157
<p>the result of opening a file is an iterator, which can be converted to a sequence, which has a length:</p> <pre><code>with open(filename) as f: return len(list(f)) </code></pre> <p>this is more concise than your explicit loop, and avoids the <code>enumerate</code>.</p>
3
2009-05-10T11:35:26Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,802
<p>What about this</p> <pre><code>def file_len(fname): counts = itertools.count() with open(fname) as f: for _ in f: counts.next() return counts.next() </code></pre>
3
2009-05-10T18:20:28Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
845,836
<p>Why not read the first 100 and the last 100 lines and estimate the average line length, then divide the total file size through that numbers? If you don't need a exact value this could work.</p>
0
2009-05-10T18:36:20Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
850,962
<p>I believe that a memory mapped file will be the fastest solution. I tried four functions: the function posted by the OP (<code>opcount</code>); a simple iteration over the lines in the file (<code>simplecount</code>); readline with a memory-mapped filed (mmap) (<code>mapcount</code>); and the buffer read solution of...
139
2009-05-12T02:49:04Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
1,019,572
<p>One line, probably pretty fast:</p> <pre><code>num_lines = sum(1 for line in open('myfile.txt')) </code></pre>
308
2009-06-19T19:07:06Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
2,772,853
<p>Just to complete the above methods I tried a variant with the fileinput module:</p> <pre><code>import fileinput as fi def filecount(fname): for line in fi.input(fname): pass return fi.lineno() </code></pre> <p>And passed a 60mil lines file to all the above stated methods:</p> <pre><...
4
2010-05-05T11:48:21Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
3,119,185
<p>what about this?</p> <pre><code>import sys sys.stdin=open('fname','r') data=sys.stdin.readlines() print "counted",len(data),"lines" </code></pre>
0
2010-06-25T15:17:32Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
4,359,897
<p>Why wouldn't the following work?</p> <pre><code>import sys # input comes from STDIN file = sys.stdin data = file.readlines() # get total number of lines in file lines = len(data) print lines </code></pre> <p>In this case, the len function uses the input lines as a means of determining the length.</p>
0
2010-12-05T16:45:54Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
5,278,398
<p><code>count = max(enumerate(open(filename)))[0]</code></p>
3
2011-03-11T21:09:52Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
6,750,195
<p>How about this?</p> <pre><code>import fileinput import sys counter=0 for line in fileinput.input([sys.argv[1]]): counter+=1 fileinput.close() print counter </code></pre>
0
2011-07-19T15:55:39Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
6,826,326
<p>Here is a python program to use the multiprocessing library to distribute the line counting across machines/cores. My test improves counting a 20million line file from 26 seconds to 7 seconds using an 8 core windows 64 server. Note: not using memory mapping makes things much slower.</p> <pre><code>import multipro...
23
2011-07-26T06:51:01Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
8,270,828
<p>I have modified the buffer case like this:</p> <pre><code>def CountLines(filename): f = open(filename) try: lines = 1 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) # Empty file if not buf: return 0 whil...
2
2011-11-25T14:55:52Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
15,074,925
<p>I got a small (4-8%) improvement with this version which re-uses a constant buffer so it should avoid any memory or GC overhead:</p> <pre><code>lines = 0 buffer = bytearray(2048) with open(filename) as f: while f.readinto(buffer) &gt; 0: lines += buffer.count('\n') </code></pre> <p>You can play around with...
5
2013-02-25T19:31:53Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
18,638,592
<p>Similarly:</p> <pre><code>lines = 0 with open(path) as f: for line in f: lines += 1 </code></pre>
0
2013-09-05T14:08:16Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
19,149,178
<p>How about this one-liner:</p> <pre><code>file_length = len(open('myfile.txt','r').read().split('\n')) </code></pre> <p>Takes 0.003 sec using this method to time it on a 3900 line file</p> <pre><code>def c(): import time s = time.time() file_length = len(open('myfile.txt','r').read().split('\n')) print tim...
-1
2013-10-03T00:55:36Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
19,248,109
<p>I would use Python's file object method <code>readlines</code>, as follows:</p> <pre><code>with open(input_file) as foo: lines = len(foo.readlines()) </code></pre> <p>This opens the file, creates a list of lines in the file, counts the length of the list, saves that to a variable and closes the file again.</p>...
8
2013-10-08T12:46:12Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
22,551,496
<pre><code>print open('file.txt', 'r').read().count("\n") + 1 </code></pre>
5
2014-03-21T06:10:30Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
24,003,811
<pre><code>def line_count(path): count = 0 with open(path) as lines: for count, l in enumerate(lines, start=1): pass return count </code></pre>
1
2014-06-02T21:45:10Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
25,544,973
<p>If one wants to get the line count cheaply in Python in Linux, I recommend this method:</p> <pre><code>import os print os.popen("wc -l file_path").readline().split()[0] </code></pre> <p>file_path can be both abstract file path or relative path. Hope this may help.</p>
0
2014-08-28T09:09:45Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
26,375,032
<p><a href="http://stackoverflow.com/a/1019572/2698552">Kyle's answer</a> </p> <pre><code>num_lines = sum(1 for line in open('my_file.txt')) </code></pre> <p>is probably best, an alternative for this is</p> <pre><code>num_lines = len(open('my_file.txt').read().splitlines()) </code></pre> <p>Here is the comparision...
3
2014-10-15T05:22:12Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
26,695,897
<p>You can use the <code>os.path</code> module in the following way:</p> <pre><code>import os import subprocess Number_lines = int( (subprocess.Popen( 'wc -l {0}'.format( Filename ), shell=True, stdout=subprocess.PIPE).stdout).readlines()[0].split()[0] ) </code></pre> <p>, where <code>Filename</code> is the absolute ...
0
2014-11-02T03:58:48Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
27,518,377
<p>I had to post this on a similar question until my reputation score jumped a bit (thanks to whoever bumped me!). </p> <p>All of these solutions ignore one way to make this run considerably faster, namely by using the unbuffered (raw) interface, using bytearrays, and doing your own buffering. (This only applies in Py...
26
2014-12-17T04:32:25Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
28,165,046
<p>Another possibility: </p> <pre><code>import subprocess def num_lines_in_file(fpath): return int(subprocess.check_output('wc -l %s' % fpath, shell=True).strip().split()[0]) </code></pre>
1
2015-01-27T07:08:00Z
[ "python", "text-files", "line-count" ]
How to get line count cheaply in Python?
845,058
<p>I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?</p> <p>At the moment I do:</p> <pre><code>def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 </code></pr...
470
2009-05-10T10:22:05Z
28,680,922
<p>This code is shorter and clearer. It's probably the best way:</p> <pre><code>num_lines = open('yourfile.ext').read().count('\n') </code></pre>
2
2015-02-23T18:38:13Z
[ "python", "text-files", "line-count" ]
VIM: Use python 2.5 with vim 7.2
845,068
<p>How can use Python2.5 with to write scripts in vim? I'm using vim 7.2 and have Python 2.5. Vim 7.2 seem to be linked with Python 2.4 Do I have to compile from source?</p>
1
2009-05-10T10:27:57Z
845,070
<p><a href="http://www.gooli.org/blog/gvim-72-with-python-2526-support-windows-binaries/" rel="nofollow">Here</a> is a link to VIM 7.2 builds with Python 2.5/2.6 support.</p>
3
2009-05-10T10:30:19Z
[ "python", "vim" ]
Problem when using MemoryDC
845,071
<p>Why does my code print the lines gray instead of black?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.panel=wx.Panel(self,-1,size=(1000,1000)) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.E...
1
2009-05-10T10:30:26Z
846,700
<p>Ok I tested with newer version of wx(2.8.9.2) </p> <p>and Now I wonder why it is even working on your side. you are trying to paint Panel but overriding the paint event of Frame</p> <p>instead do this</p> <pre><code>self.panel.Bind(wx.EVT_PAINT, self.on_paint) </code></pre> <p>and all will be fine</p>
0
2009-05-11T04:15:50Z
[ "python", "graphics", "wxpython" ]
Problem when using MemoryDC
845,071
<p>Why does my code print the lines gray instead of black?</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.panel=wx.Panel(self,-1,size=(1000,1000)) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.E...
1
2009-05-10T10:30:26Z
855,159
<p>Beside the frame/panel paint problem already pointed out the color problem is due to the alpha channel of the 32 bit bitmap.</p> <p>I remember having read to use <code>wx.GCDC</code> instead of <code>wx.DC</code>.</p>
1
2009-05-12T22:20:01Z
[ "python", "graphics", "wxpython" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
845,133
<p>I can't figure out any other <em>pythonic</em> option. But personally I'd prefer the more <em>OO</em> way.</p> <pre><code>class TheData(object): def clone(self): """return the cloned""" def f(data): #do stuff def caller(): d = TheData() f(d.clone()) </code></pre>
2
2009-05-10T11:16:43Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
845,194
<p>You can make a decorator and put the cloning behaviour in that. </p> <pre><code>&gt;&gt;&gt; def passbyval(func): def new(*args): cargs = [deepcopy(arg) for arg in args] return func(*cargs) return new &gt;&gt;&gt; @passbyval def myfunc(a): print a &gt;&gt;&gt; myfunc(20) 20 </code></pre> <p>This is not the...
24
2009-05-10T11:57:47Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
845,691
<p>There is no pythonic way of doing this. </p> <p>Python provides very few facilities for <em>enforcing</em> things such as private or read-only data. The pythonic philosophy is that "we're all consenting adults": in this case this means that "the function shouldn't change the data" is part of the spec but not enforc...
22
2009-05-10T17:16:08Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
1,082,129
<p>usually when passing data to an external API, you can assure the integrity of your data by passing it as an immutable object, for example wrap your data into a tuple. This cannot be modified, if that is what you tried to prevent by your code.</p>
3
2009-07-04T12:30:47Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
1,082,972
<p>Though i'm sure there's no really pythonic way to do this, i expect the <code>pickle</code> module will give you copies of everything you have any business treating as a value. </p> <pre><code>import pickle def f(data): data = pickle.loads(pickle.dumps((data))) #do stuff </code></pre>
1
2009-07-04T21:11:20Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
9,762,918
<p>There are only a couple of builtin typs that work as references, like <code>list</code>, for example.</p> <p>So, for me the pythonic way for doing a pass-by-value, for list, in this example, would be:</p> <pre><code>list1 = [0,1,2,3,4] list2 = list1[:] </code></pre> <p><code>list1[:]</code> creates a new instance...
8
2012-03-18T22:32:10Z
[ "python", "pass-by-value" ]
Emulating pass-by-value behaviour in python
845,110
<p>I would like to emulate the pass-by-value behaviour in python. In other words, I would like to make absolutely sure that the function I write do not modify user supplied data. </p> <p>One possible way is to use deep copy:</p> <pre><code>from copy import deepcopy def f(data): data = deepcopy(data) #do stuff...
33
2009-05-10T11:05:50Z
28,108,885
<p>Further to <em>user695800's</em> answer, pass by value for lists possible with the [:] operator</p> <pre><code>def listCopy(l): l[1] = 5 for i in l: print i </code></pre> <p>called with </p> <pre><code>In [12]: list1 = [1,2,3,4] In [13]: listCopy(list1[:]) 1 5 3 4 list1 Out[14]: [1, 2, 3, 4] </c...
0
2015-01-23T11:25:36Z
[ "python", "pass-by-value" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,116
<p>You could create a function that gets the size of the array, loops through it and creating a return array which it returns.</p>
1
2009-05-10T11:07:15Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,120
<p>How about this:</p> <pre><code>a = [x+y for x,y in zip(a,b)] </code></pre>
9
2009-05-10T11:09:52Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,123
<p>[a[x] + b[x] for x in range(0,len(a))]</p>
3
2009-05-10T11:11:33Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,139
<p>If you need efficient vector arithmetic, try <a href="http://numpy.scipy.org/">Numpy</a>.</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a=numpy.array([0,1,2]) &gt;&gt;&gt; b=numpy.array([3,4,5]) &gt;&gt;&gt; a+b array([3, 5, 7]) &gt;&gt;&gt; </code></pre> <p>Or (thanks, Andrew Jaffe), </p> <pre><code>&gt;...
27
2009-05-10T11:21:09Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,141
<p>Or, if you're willing to use an external library (and fixed-length arrays), use <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a>, which has "+=" and related operations for in-place operations.</p> <pre><code>import numpy as np a = np.array([0, 1, 2]) b = np.array([3, 4, 5]) a += b </code></pre>
4
2009-05-10T11:21:22Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,314
<p>While Numeric is excellent, and list-comprehension solutions OK if you actually wanted to create a new list, I'm surprised nobody suggested the "one obvious way to do it" -- a simple <code>for</code> loop! Best:</p> <pre><code>for i, bi in enumerate(b): a[i] += bi </code></pre> <p>Also OK, kinda sorta:</p> <pre>...
27
2009-05-10T13:15:23Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,736
<p>An improvement (less memory consumption) of the comprehension list </p> <p>import itertools a = [x+y for x,y in itertools.izip(a,b)]</p> <p>Actually if you are not sure that a will be consume then I would even go with generator expression:</p> <p>(x+y for x,y in itertools.izip(a,b))</p>
0
2009-05-10T17:43:01Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
845,758
<p>If you think Numpy is overkill, this should be really fast, because this code runs in pure C (<code>map()</code> and <code>__add__()</code> are both directly implemented in C):</p> <pre><code>a = [1.0,2.0,3.0] b = [4.0,5.0,6.0] c = map(float.__add__, a, b) </code></pre> <p>Or alternatively, if you don't know the...
12
2009-05-10T17:58:53Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
846,274
<p>I don't think you will find a faster solution than the 3 sums proposed in the question. The advantages of numpy are visible with larger vectors, and also if you need other operators. numpy is specially useful with matrixes, witch are trick to do with python lists.</p> <p>Still, yet another way to do it :D</p> <pr...
20
2009-05-10T22:54:47Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
24,070,053
<p>If you're after concise, try...</p> <pre><code>vectors = [[0.0, 1.0, 2.0],[3.0, 4.0, 5.0]] [sum(col) for col in zip(*vectors)] </code></pre> <p>Though I can't speak for the performance of this.</p>
0
2014-06-05T20:52:01Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
29,979,654
<pre><code>list(map(lambda x:x[0]+x[1], zip(a,b))) </code></pre>
0
2015-04-30T23:50:00Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
32,358,629
<p>For the general case of having a list of lists you could do something like this:</p> <pre><code>In [2]: import numpy as np In [3]: a = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3],[4, 5, 6]]) In [4]: [sum(a[:,i]) for i in xrange(len(a[0]))] Out[4]: [10, 11, 12] </code></pre>
1
2015-09-02T16:41:23Z
[ "python" ]
Concise vector adding in Python?
845,112
<p>I often do vector addition of Python lists.</p> <p>Example: I have two lists like these:</p> <pre><code>a = [0.0, 1.0, 2.0] b = [3.0, 4.0, 5.0] </code></pre> <p>I now want to add b to a to get the result <code>a = [3.0, 5.0, 7.0]</code>.</p> <p>Usually I end up doing like this:</p> <pre><code>a[0] += b[0] a[1] ...
21
2009-05-10T11:05:59Z
38,861,127
<pre><code>a = map(lambda x, y: x + y, a, b) </code></pre>
0
2016-08-09T22:01:32Z
[ "python" ]
Converting a java System.currentTimeMillis() to date in python
845,153
<p>I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.</p> <p>How should I do that ?</p> <p>The following give <strong>ValueError: timestamp out of range for platform time_t</strong> on Linux 32bit</p> <pr...
6
2009-05-10T11:33:43Z
845,166
<p>It's in milliseconds divided the timestamp by 1000 to become in seconds.</p> <pre><code>date.fromtimestamp(1241711346274/1000) </code></pre>
1
2009-05-10T11:40:00Z
[ "java", "python", "date", "formatting", "timestamp" ]
Converting a java System.currentTimeMillis() to date in python
845,153
<p>I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.</p> <p>How should I do that ?</p> <p>The following give <strong>ValueError: timestamp out of range for platform time_t</strong> on Linux 32bit</p> <pr...
6
2009-05-10T11:33:43Z
845,167
<p>Python expects seconds, so divide it by 1000.0 first:</p> <pre><code>&gt;&gt;&gt; print date.fromtimestamp(1241711346274/1000.0) 2009-05-07 </code></pre>
15
2009-05-10T11:40:38Z
[ "java", "python", "date", "formatting", "timestamp" ]
Converting a java System.currentTimeMillis() to date in python
845,153
<p>I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.</p> <p>How should I do that ?</p> <p>The following give <strong>ValueError: timestamp out of range for platform time_t</strong> on Linux 32bit</p> <pr...
6
2009-05-10T11:33:43Z
845,303
<p>You can preserve the precision, because in Python the timestamp is a float. Here's an example:</p> <pre><code>import datetime java_timestamp = 1241959948938 seconds = java_timestamp / 1000 sub_seconds = (java_timestamp % 1000.0) / 1000.0 date = datetime.datetime.fromtimestamp(seconds + sub_seconds) </code></pre> ...
3
2009-05-10T13:07:12Z
[ "java", "python", "date", "formatting", "timestamp" ]
How to print the comparison of two multiline strings in unified diff format?
845,276
<p>Do you know any library that will help doing that?</p> <p>I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:</p> <pre><code>def print_differences(string1, string2): """ Prints the comparison of string1 to string2 as unified di...
7
2009-05-10T12:51:12Z
845,284
<p>Did you have a look at the built-in python module <a href="http://docs.python.org/library/difflib.html">difflib</a>? Have a look that this <a href="http://docs.python.org/library/difflib.html#differ-example">example</a></p>
17
2009-05-10T12:54:51Z
[ "python", "diff", "unified-diff" ]
How to print the comparison of two multiline strings in unified diff format?
845,276
<p>Do you know any library that will help doing that?</p> <p>I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:</p> <pre><code>def print_differences(string1, string2): """ Prints the comparison of string1 to string2 as unified di...
7
2009-05-10T12:51:12Z
845,432
<p>This is how I solved:</p> <pre><code>def _unidiff_output(expected, actual): """ Helper function. Returns a string containing the unified diff of two multiline strings. """ import difflib expected=expected.splitlines(1) actual=actual.splitlines(1) diff=difflib.unified_diff(expected, act...
11
2009-05-10T14:25:22Z
[ "python", "diff", "unified-diff" ]
Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on
845,408
<p>It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open and operate on), a URL(which it will download and operate on), or data(which it will operate on).</p> <p>Here's <a href...
2
2009-05-10T14:11:21Z
845,424
<p>Ultimately, any module implementing this behaviour is going to parse the string. And act according to the result. In feedparser for example they are parsing the url:</p> <pre><code>if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'): # do something with the url else: # This is a f...
7
2009-05-10T14:18:51Z
[ "python" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,506
<p>Yes, by hosting IronPython.</p>
7
2009-05-10T15:14:10Z
[ "c#", "python", "ironpython" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,511
<p>In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its hard to take advantage of the dynamic features of IronPython since C# is a very statically typed language</p> <p>If you're speaking of IronPython thoug...
5
2009-05-10T15:16:31Z
[ "c#", "python", "ironpython" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,515
<p>You may take a look at this <a href="http://stackoverflow.com/questions/736443/ironpython-and-c-script-access-to-c-objects">post</a>.</p>
1
2009-05-10T15:18:24Z
[ "c#", "python", "ironpython" ]
using Python objects in C#
845,502
<p>Is there an easy way to call Python objects from C#, that is without any COM mess?</p>
4
2009-05-10T15:11:45Z
845,516
<p>I know of 3 ways:</p> <p>1) Use Iron Python, and your Python projects can interact freely with projects written in C#.</p> <p>2) Expose your Python functions to COM. You would do this if you need to use Python libraries that you don't want to or can't convert to Iron Python (EG, if you just have a DLL.) The "COM ...
4
2009-05-10T15:18:32Z
[ "c#", "python", "ironpython" ]
Background process in GAE
845,620
<p>I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)</p> <p>A major part of my program has to run in the background and change local data and also post to a remote URL</p> <p>Can someone suggest an effective way of doing this?</p>
3
2009-05-10T16:37:19Z
845,624
<p>Without using a third-party system, I think currently your only option is to use the <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">cron functionality</a>.</p> <p>You'd still be bound by the usual GAE script-execution-time limitations, but it wouldn't happen on a page load.</...
2
2009-05-10T16:41:32Z
[ "python", "django", "google-app-engine", "backgroundworker" ]
Background process in GAE
845,620
<p>I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)</p> <p>A major part of my program has to run in the background and change local data and also post to a remote URL</p> <p>Can someone suggest an effective way of doing this?</p>
3
2009-05-10T16:37:19Z
845,684
<p>I second dbr's recommendation of <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">http://code.google.com/appengine/docs/python/config/cron.html</a> (and hopes for better future approaches, such as the promised "task queues").</p> <p>Nevertheless I suspect that if you do indeed ...
2
2009-05-10T17:12:46Z
[ "python", "django", "google-app-engine", "backgroundworker" ]
Background process in GAE
845,620
<p>I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)</p> <p>A major part of my program has to run in the background and change local data and also post to a remote URL</p> <p>Can someone suggest an effective way of doing this?</p>
3
2009-05-10T16:37:19Z
1,030,406
<p>Check out <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">The Task Queue Python API</a>.</p>
5
2009-06-23T02:39:40Z
[ "python", "django", "google-app-engine", "backgroundworker" ]
Unable to make an iterable decimal function in Python
845,787
<p>I want to calculate the sum of </p> <pre><code>1/1 + 1/2 + 1/3 + ... + 1/30 </code></pre> <p>I run the code unsuccessfully</p> <pre><code>import decimal import math var=decimal.Decimal(1/i) for i in range(1,31): print(sum(var)) </code></pre> <p>I get the error</p> <pre><code>'Decimal' object is not iterable...
0
2009-05-10T18:16:02Z
845,800
<p>What you want is this:</p> <pre><code>print(sum(decimal.Decimal(1) / i for i in range(1, 31))) </code></pre> <p>The reason your code doesn't work, is that you try to iterate over <em>one</em> <code>Decimal</code> instance (through the use of <code>sum</code>). Furthermore, your definition of <code>var</code> is in...
11
2009-05-10T18:19:59Z
[ "python", "iteration", "sum" ]
Unable to make an iterable decimal function in Python
845,787
<p>I want to calculate the sum of </p> <pre><code>1/1 + 1/2 + 1/3 + ... + 1/30 </code></pre> <p>I run the code unsuccessfully</p> <pre><code>import decimal import math var=decimal.Decimal(1/i) for i in range(1,31): print(sum(var)) </code></pre> <p>I get the error</p> <pre><code>'Decimal' object is not iterable...
0
2009-05-10T18:16:02Z
845,807
<p>You write:</p> <pre><code>var=decimal.Decimal(1/i) </code></pre> <p>which is weird since 'i' is not defined at that point. How about:</p> <pre><code>one = decimal.Decimal( "1" ) total = decimal.Decimal( "0" ) for i in range( 1, 31 ): total += one / decimal.Decimal( "%d" % i ) </code></pre>
3
2009-05-10T18:22:50Z
[ "python", "iteration", "sum" ]
Unable to make an iterable decimal function in Python
845,787
<p>I want to calculate the sum of </p> <pre><code>1/1 + 1/2 + 1/3 + ... + 1/30 </code></pre> <p>I run the code unsuccessfully</p> <pre><code>import decimal import math var=decimal.Decimal(1/i) for i in range(1,31): print(sum(var)) </code></pre> <p>I get the error</p> <pre><code>'Decimal' object is not iterable...
0
2009-05-10T18:16:02Z
845,826
<p>Your mistake is, that <code>decimal.Decimal(4)</code> isn't a function, but an object.</p> <p><hr /></p> <p>BTW: It looks like the <a href="http://docs.python.org/library/fractions.html" rel="nofollow">Fractions</a> (Python 2.6) module is what you really need.</p>
2
2009-05-10T18:31:57Z
[ "python", "iteration", "sum" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've...
2
2009-05-10T19:06:44Z
845,907
<p>If you auto-generate the tests:</p> <ul> <li><p>You might find it faster to then read all the tests (to inspect them for correctness) that it would have been to write them all by hand.</p></li> <li><p>They might also be more maintainable (easier to edit, if you want to edit them later).</p></li> </ul>
1
2009-05-10T19:16:39Z
[ "python", "unit-testing", "code-generation" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've...
2
2009-05-10T19:06:44Z
845,908
<p>You're right to identify the weakness of automatically generating test cases. The usefulness of a test comes from taking two different paths (your code, and your own mental reasoning) to come up with what should be the same answer -- if you use the same path both times, nothing is being tested.</p> <p>In summary: ...
1
2009-05-10T19:17:28Z
[ "python", "unit-testing", "code-generation" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've...
2
2009-05-10T19:06:44Z
845,962
<p>I would say the best approach is to unit test the generation, and as part of the unit test, you might take a sample generated result (only enough to where the test tests something that you would consider significantly different over the other scenarios) and put that under a unit test to make sure that the generation...
1
2009-05-10T19:36:04Z
[ "python", "unit-testing", "code-generation" ]
Unit tests for automatically generated code: automatic or manual?
845,887
<p>I know <a href="http://stackoverflow.com/questions/32899/how-to-generate-dynamic-unit-tests-in-python">similar questions</a> have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.</p> <p>I've...
2
2009-05-10T19:06:44Z
846,171
<p>Write only just enough tests to make sure that your code generation works right (just enough to drive the design of the imperative code). Declarative code rarely breaks. You should only test things that can break. Mistakes in declarative code (such as your case and for example user interface layouts) are better foun...
1
2009-05-10T21:38:31Z
[ "python", "unit-testing", "code-generation" ]
Rename invalid filename in XP via Python
845,926
<p>My problem is similar to <a href="http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames">http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames</a></p> <p>however, I don't know the original encoding of the filename I need to rename (unlike the other pos...
4
2009-05-10T19:22:09Z
847,793
<p>Try passing a unicode string:</p> <pre><code>os.rename(blah[0], u'dont be them.mp3') </code></pre>
0
2009-05-11T12:04:20Z
[ "python", "unicode", "windows-xp" ]
Rename invalid filename in XP via Python
845,926
<p>My problem is similar to <a href="http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames">http://stackoverflow.com/questions/497233/pythons-os-path-choking-on-hebrew-filenames</a></p> <p>however, I don't know the original encoding of the filename I need to rename (unlike the other pos...
4
2009-05-10T19:22:09Z
848,611
<p><strong>'?'</strong> is not valid character for filenames. That is the reason while your approach failed. You may try to use DOS short filenames:</p> <pre><code>import win32api filelist = win32api.FindFiles(r'F:/recovery/My Music/*.*') # this will extract "short names" from WIN32_FIND_DATA structure filelist = [i[...
2
2009-05-11T15:21:55Z
[ "python", "unicode", "windows-xp" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler ...
15
2009-05-10T19:38:22Z
845,984
<p>We follow the following principles when designing classes:</p> <ul> <li><a href="http://www.google.co.za/url?sa=t&amp;source=web&amp;ct=res&amp;cd=2&amp;url=http%3A%2F%2Fwww.objectmentor.com%2Fresources%2Farticles%2Fsrp.pdf&amp;ei=1C4HSu3uEODJtgfs8uWeBw&amp;usg=AFQjCNHQQ1Aw-2yCciEbERpJn3VdHBCmQw&amp;sig2=Pf7Z4GNwRn...
28
2009-05-10T19:47:10Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler ...
15
2009-05-10T19:38:22Z
845,986
<p>It's often not possible to say whats 'correct' or 'wrong' when it comes to class design. There are many guidelines, patterns, recommendation etc. about this topic, but at the end of the day, imho, it's a lot about experience with past projects. My experience is that it's best to not worry to much about it, and gradu...
3
2009-05-10T19:48:30Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler ...
15
2009-05-10T19:38:22Z
845,988
<p><a href="http://en.wikipedia.org/wiki/Design%5Fpattern%5F%28computer%5Fscience%29" rel="nofollow">Design Patterns</a> has become the defacto standard for good class design. Generally, each pattern has a particular use case, or scenario, which it applies to. If you can identify this in your code, you can use the pa...
1
2009-05-10T19:49:04Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler ...
15
2009-05-10T19:38:22Z
845,991
<p>Try making each method easily unit-testable. I find this always drives my designs towards more readability/understandability. There are numerous OOAD rules -- <a href="http://stackoverflow.com/questions/399656/are-there-any-rules-for-oop">SRP, DRY, etc.</a> Try to keep those in mind as you refactor.</p>
0
2009-05-10T19:52:05Z
[ "python", "language-agnostic", "oop" ]
OOP: good class design
845,966
<p>My question is related to this one: <a href="http://stackoverflow.com/questions/798389/python-tool-that-builds-a-dependency-diagram-for-methods-of-a-class">Python tool that builds a dependency diagram for methods of a class</a>.</p> <p>After not finding any tools I wrote a quick hack myself: I've used the compiler ...
15
2009-05-10T19:38:22Z
848,671
<p>I recommend the book "Refactoring" by Martin Fowler for tons of practical examples of iteratively converting poor design to good design.</p>
0
2009-05-11T15:34:06Z
[ "python", "language-agnostic", "oop" ]
How do I represent a void pointer in a PyObjC selector?
845,970
<p>I'm wanting to use an NSOpenPanel for an application I'm designing. Here's what I have so far:</p> <pre><code>@objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPan...
3
2009-05-10T19:39:38Z
872,792
<p>I think you don't need to use <code>objc.selector</code> at all; try this instead:</p> <pre><code>@objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPanel') self...
1
2009-05-16T16:50:17Z
[ "python", "objective-c", "osx", "pyobjc", "void-pointers" ]
How do I represent a void pointer in a PyObjC selector?
845,970
<p>I'm wanting to use an NSOpenPanel for an application I'm designing. Here's what I have so far:</p> <pre><code>@objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPan...
3
2009-05-10T19:39:38Z
903,319
<p>The right way to open the panel is:</p> <pre><code>@objc.IBAction def showOpenPanel_(self, sender): panel = NSOpenPanel.openPanel() panel.setCanChooseFiles_(False) panel.setCanChooseDirectories_(True) NSLog(u'Starting openPanel') panel.beginForDirectory_file_types_modelessDelegate_didEndSelector...
1
2009-05-24T08:16:35Z
[ "python", "objective-c", "osx", "pyobjc", "void-pointers" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
846,045
<p>You can use the <a href="http://docs.python.org/library/struct.html">struct</a> module:</p> <pre><code>import struct print struct.pack('&gt;I', your_int) </code></pre> <p><code>'&gt;I'</code> is a format string. <code>&gt;</code> means big endian and <code>I</code> means unsigned int. Check the documentation for m...
32
2009-05-10T20:27:59Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
846,063
<p>Probably the best way is via the built-in <a href="http://docs.python.org/library/struct.html">struct module</a>:</p> <pre><code>&gt;&gt;&gt; import struct &gt;&gt;&gt; x = 1245427 &gt;&gt;&gt; struct.pack('&gt;BH', x &gt;&gt; 16, x &amp; 0xFFFF) '\x13\x00\xf3' &gt;&gt;&gt; struct.pack('&gt;L', x)[1:] # could do i...
7
2009-05-10T20:42:47Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
846,064
<pre><code>def tost(i): result = [] while i: result.append(chr(i&amp;0xFF)) i &gt;&gt;= 8 result.reverse() return ''.join(result) </code></pre>
4
2009-05-10T20:43:23Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
846,067
<p>This is fast and works for small and (arbitrary) large ints:</p> <pre><code>def Dump(n): s = '%x' % n if len(s) &amp; 1: s = '0' + s return s.decode('hex') print repr(Dump(1245427)) #: '\x13\x00\xf3' </code></pre>
12
2009-05-10T20:44:32Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
1,776,698
<p>Using the <a href="http://code.google.com/p/python-bitstring/" rel="nofollow">bitstring</a> module:</p> <pre><code>&gt;&gt;&gt; bitstring.BitArray(uint=1245427, length=24).bytes '\x13\x00\xf3' </code></pre> <p>Note though that for this method you need to specify the length in bits of the bitstring you are creating...
3
2009-11-21T20:37:12Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
9,356,262
<p>The shortest way, I think, is the following:</p> <pre><code>import struct val = 0x11223344 val = struct.unpack("&lt;I", struct.pack("&gt;I", val))[0] print "%08x" % val </code></pre> <p>This converts an integer to a byte-swapped integer.</p>
3
2012-02-20T04:39:56Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
12,859,903
<p>In Python 3.2+, you can use <a href="http://docs.python.org/py3k/library/stdtypes.html#int.to_bytes">int.to_bytes</a>:</p> <h2>If you don't want to specify the size</h2> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; n = 1245427 &gt;&gt;&gt; n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0' b...
23
2012-10-12T13:15:51Z
[ "python" ]
Convert a Python int into a big-endian string of bytes
846,038
<p>I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3.</p> <p>My ints are on the scale of 35 ...
41
2009-05-10T20:24:01Z
28,524,760
<p>Single-source Python 2/3 compatible version based on <a href="http://stackoverflow.com/a/846067/4279">@pts' answer</a>:</p> <pre><code>#!/usr/bin/env python import binascii def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n &amp; 1))) print(in...
5
2015-02-15T09:33:07Z
[ "python" ]
What's the quickest way for a Ruby programmer to pick up Python?
846,139
<p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical lan...
10
2009-05-10T21:25:18Z
846,151
<p>A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, <a href="http://projecteuler.net/index.php?section=problems">lots of it</a>. Your experience in Ruby will make it easy to pick up python's dynami...
9
2009-05-10T21:30:45Z
[ "python", "ruby" ]
What's the quickest way for a Ruby programmer to pick up Python?
846,139
<p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical lan...
10
2009-05-10T21:25:18Z
846,152
<p>I started learning from the <a href="http://docs.python.org/tutorial/" rel="nofollow">python tutorial</a>. It is well written and easy to follow. Then I started to solve problems in <a href="http://www.pythonchallenge.com/" rel="nofollow">python challenge</a>. It was a really fun way to start :) </p>
2
2009-05-10T21:31:11Z
[ "python", "ruby" ]
What's the quickest way for a Ruby programmer to pick up Python?
846,139
<p>I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical lan...
10
2009-05-10T21:25:18Z
846,154
<p>I suggest just diving into Python, it's similar to Ruby so you should have no problems:</p> <p><a href="http://www.diveintopython.net/" rel="nofollow">http://www.diveintopython.net/</a></p>
3
2009-05-10T21:31:38Z
[ "python", "ruby" ]