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
Shell: insert a blank/new line two lines above pattern
757,532
<p>To add a blank line above every line that matches your regexp, you can use:</p> <pre><code>sed '/regexp/{x;p;x;}' </code></pre> <p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p> <p>The pattern I'll be matching is a postal code in the...
6
2009-04-16T18:48:13Z
757,554
<p>I tried</p> <pre><code>sed '/regexp/a\\n' </code></pre> <p>but it inserted two newlines. If that does not bother you, take it.</p> <blockquote> <p>echo -e "a\nb\nc" | sed '/^a$/a\n'<br /> a </p> <p>b<br /> c </p> </blockquote> <p><strong>Edit:</strong> Now that you state that you need to insert two ...
0
2009-04-16T18:55:30Z
[ "python", "perl", "text", "sed", "awk" ]
Shell: insert a blank/new line two lines above pattern
757,532
<p>To add a blank line above every line that matches your regexp, you can use:</p> <pre><code>sed '/regexp/{x;p;x;}' </code></pre> <p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p> <p>The pattern I'll be matching is a postal code in the...
6
2009-04-16T18:48:13Z
757,943
<p>Here's an approach that works for Python.</p> <pre><code>import sys def address_change( aFile ): address= [] for line in aFile: if regex.match( line ): # end of the address print address[0] print print address[1:] print line ad...
1
2009-04-16T20:36:18Z
[ "python", "perl", "text", "sed", "awk" ]
Shell: insert a blank/new line two lines above pattern
757,532
<p>To add a blank line above every line that matches your regexp, you can use:</p> <pre><code>sed '/regexp/{x;p;x;}' </code></pre> <p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p> <p>The pattern I'll be matching is a postal code in the...
6
2009-04-16T18:48:13Z
757,988
<pre><code>perl -ne 'END{print @x} push@x,$_; if(@x&gt;2){splice @x,1,0,"\n" if /[[:alpha:]]\d[[:alpha:]]\s?\d[[:alpha:]]\d/;print splice @x,0,-2}' </code></pre> <p>If I cat your file into this, I get what you want... it's ugly, but you wanted shell (i.e., one-liner) :-) If I were to do this in full perl, I'd be able...
2
2009-04-16T20:47:56Z
[ "python", "perl", "text", "sed", "awk" ]
Shell: insert a blank/new line two lines above pattern
757,532
<p>To add a blank line above every line that matches your regexp, you can use:</p> <pre><code>sed '/regexp/{x;p;x;}' </code></pre> <p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p> <p>The pattern I'll be matching is a postal code in the...
6
2009-04-16T18:48:13Z
758,010
<p>More readable Perl, and handles multiple files sanely.</p> <pre><code>#!/usr/bin/env perl use constant LINES =&gt; 2; my @buffer = (); while (&lt;&gt;) { /pattern/ and unshift @buffer, "\n"; push @buffer, $_; print splice @buffer, 0, -LINES; } continue { if (eof(ARGV)) { print @buffer; ...
7
2009-04-16T20:55:45Z
[ "python", "perl", "text", "sed", "awk" ]
Shell: insert a blank/new line two lines above pattern
757,532
<p>To add a blank line above every line that matches your regexp, you can use:</p> <pre><code>sed '/regexp/{x;p;x;}' </code></pre> <p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p> <p>The pattern I'll be matching is a postal code in the...
6
2009-04-16T18:48:13Z
758,101
<p>Something a bit like your original approach in sed:</p> <pre><code>sed '/regexp/i\ $H x' </code></pre> <p>The basic idea is to print everything delayed by one line (<strong>x</strong>change the hold and pattern spaces - printing is implicit). That needs to be done because until we check whether the next line matc...
5
2009-04-16T21:18:18Z
[ "python", "perl", "text", "sed", "awk" ]
Shell: insert a blank/new line two lines above pattern
757,532
<p>To add a blank line above every line that matches your regexp, you can use:</p> <pre><code>sed '/regexp/{x;p;x;}' </code></pre> <p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p> <p>The pattern I'll be matching is a postal code in the...
6
2009-04-16T18:48:13Z
759,945
<p>Simple:</p> <pre><code>sed '1{x;d};$H;/regexp/{x;s/^/\n/;b};x' </code></pre> <p>Describe it</p> <pre><code>#!/bin/sed # trick is juggling previous and current line in hold and pattern space 1 { # at firs line x # place first line to hold space d # skip to end and avoid printing } $H ...
3
2009-04-17T10:41:04Z
[ "python", "perl", "text", "sed", "awk" ]
django-paypal setup
757,809
<p>Has anyone setup django-paypal? Here is the link to it <a href="https://github.com/johnboxall/django-paypal">here</a>? </p> <p>I have "myproject" setup, and my folder sturecture looks like this:</p> <p>myproject > paypal > (stdandard and pro folders)</p> <p>to my settins.py file I added</p> <pre><code>INSTALLED_...
14
2009-04-16T19:57:51Z
757,820
<p>In your code...</p> <pre><code> 'payment_form_cls': 'payment_form_cls', # form class to use for payment </code></pre> <p>This must be a Form object that's used for validation.</p> <pre><code> 'payment_form_cls': MyValidationForm, # form class to use for payment </code></pre> <p><hr /></p> <p><strong>Edit</...
6
2009-04-16T20:01:16Z
[ "python", "django", "paypal" ]
django-paypal setup
757,809
<p>Has anyone setup django-paypal? Here is the link to it <a href="https://github.com/johnboxall/django-paypal">here</a>? </p> <p>I have "myproject" setup, and my folder sturecture looks like this:</p> <p>myproject > paypal > (stdandard and pro folders)</p> <p>to my settins.py file I added</p> <pre><code>INSTALLED_...
14
2009-04-16T19:57:51Z
760,105
<p><a href="http://uswaretech.com/blog/2008/11/using-paypal-with-django/" rel="nofollow">PayPal django Integration</a> post should help you.</p>
1
2009-04-17T11:49:19Z
[ "python", "django", "paypal" ]
Whats the easiest and fastest way to measure HD performance using Python?
757,816
<p>I need to measure the performance of a hard disk using python. What is the best/fastest/shortest/easiest approach to do it? It doesn't have to be overly accurate, just a ballpark value.</p> <p>My actual goal is to write a small utility which will adjust the postgres settings to the best configuration for the given ...
1
2009-04-16T20:00:35Z
757,826
<p>Start here: <a href="http://www.acnc.com/benchmarks.html" rel="nofollow">http://www.acnc.com/benchmarks.html</a></p> <p>Get the source for one you like write something like it in Python.</p>
1
2009-04-16T20:03:19Z
[ "python", "performance", "postgresql" ]
Whats the easiest and fastest way to measure HD performance using Python?
757,816
<p>I need to measure the performance of a hard disk using python. What is the best/fastest/shortest/easiest approach to do it? It doesn't have to be overly accurate, just a ballpark value.</p> <p>My actual goal is to write a small utility which will adjust the postgres settings to the best configuration for the given ...
1
2009-04-16T20:00:35Z
758,057
<p>I would think your best bet would be using an external tool, Bonnie++ for example, and parse the program output. Even if you're not that concerned with precision there's no reason to reinvent the wheel. Why rewrite what's already there?</p>
2
2009-04-16T21:07:54Z
[ "python", "performance", "postgresql" ]
Why doesn't the regex match when I add groups?
757,949
<p>I have this regex code in python :</p> <pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) </code></pre> <p><code>text</code> is <code>{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file ...
3
2009-04-16T20:38:14Z
757,973
<p>I think your conditional is looking for "\fad" or "fade", I think you need to move a \ outside the grouping if you want to look for "\fad" or "\fade".</p>
1
2009-04-16T20:43:41Z
[ "python", "regex" ]
Why doesn't the regex match when I add groups?
757,949
<p>I have this regex code in python :</p> <pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) </code></pre> <p><code>text</code> is <code>{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file ...
3
2009-04-16T20:38:14Z
757,980
<p>Try this:</p> <pre><code>r"\{\\fade?\(\d{1,4},\d{1,4}\)\}" </code></pre>
2
2009-04-16T20:45:28Z
[ "python", "regex" ]
Why doesn't the regex match when I add groups?
757,949
<p>I have this regex code in python :</p> <pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) </code></pre> <p><code>text</code> is <code>{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file ...
3
2009-04-16T20:38:14Z
757,981
<p>The bracket is part of the or branch starting with fade, so it's looking for either "{fad" or "fade(...". You need to group the fad|fade part together. Try:</p> <pre><code>r"\{\\(?:fad|fade)\(\d{1,4},\d{1,4}\)\}" </code></pre> <p><strong>[Edit]</strong> The reason you do get into the if block is because the rege...
4
2009-04-16T20:45:48Z
[ "python", "regex" ]
Why doesn't the regex match when I add groups?
757,949
<p>I have this regex code in python :</p> <pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) </code></pre> <p><code>text</code> is <code>{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file ...
3
2009-04-16T20:38:14Z
757,982
<p>Put extra parens around the choice: <code>re.search(r"{(?:\\fad|fade)\((\d{1,4}),(\d{1,4})\)}", text).groups()</code></p> <p>Also, escaping <code>{}</code> braces isn't necessary, it just needlessly clutters your regexp.</p>
6
2009-04-16T20:45:57Z
[ "python", "regex" ]
Why doesn't the regex match when I add groups?
757,949
<p>I have this regex code in python :</p> <pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) </code></pre> <p><code>text</code> is <code>{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file ...
3
2009-04-16T20:38:14Z
757,985
<p>I don't know the python dialect of regular expressions, but wouldn't you need to 'group' the "fad|fade" somehow to make sure it isn't trying to find "fad OR fade(etc..."?</p>
0
2009-04-16T20:47:22Z
[ "python", "regex" ]
Why doesn't the regex match when I add groups?
757,949
<p>I have this regex code in python :</p> <pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) </code></pre> <p><code>text</code> is <code>{\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file ...
3
2009-04-16T20:38:14Z
757,989
<p>Try this instead:</p> <pre><code>r"\{\\fade?\((\d{1,4}),(\d{1,4})\)\}" </code></pre> <p>The <code>e?</code> is an optional <code>e</code>. The way you have it now matches <code>{\fad</code> or <code>fade(0000,0000)}</code></p>
1
2009-04-16T20:47:57Z
[ "python", "regex" ]
Problem with Python modules
758,187
<p>I'm uploading my first Django app to my Dreamhost server. My app uses <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> package and since I can't install it in the default location ( /usr/lib/python2.3/site-packages/xlwt ), I installed it on another location by:</p> <pre><code>python setup.py insta...
3
2009-04-16T21:48:49Z
758,195
<p>PYTHONPATH may only be set when you run from the shell, you can set path programatically from python using</p> <pre><code>import sys sys.path.append('/home/myuser/lib/python') </code></pre>
5
2009-04-16T21:52:40Z
[ "python", "django", "dreamhost" ]
Make function definition in a python file order independent
758,188
<p>I use Python CGI. I cannot call a function before it is defined.</p> <p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p> <p>Is there such a trick in Python as well?</p> <p>example:</p> <pre><code>def do_something(...
22
2009-04-16T21:48:53Z
758,197
<p>All functions must be defined before any are used. </p> <p>However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.</p> <p>You don't need "forward declaration" because all declarations are completely independent of each other. As long as all decla...
31
2009-04-16T21:53:03Z
[ "python" ]
Make function definition in a python file order independent
758,188
<p>I use Python CGI. I cannot call a function before it is defined.</p> <p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p> <p>Is there such a trick in Python as well?</p> <p>example:</p> <pre><code>def do_something(...
22
2009-04-16T21:48:53Z
758,315
<p>Assuming you have some code snippet that calls your function main after it's been defined, then your example works as written. Because of how Python is interpreted, any functions that are called by the body of <code>do_something</code> do not need to be defined when the do_something function is defined.</p> <p>The...
2
2009-04-16T22:35:51Z
[ "python" ]
Make function definition in a python file order independent
758,188
<p>I use Python CGI. I cannot call a function before it is defined.</p> <p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p> <p>Is there such a trick in Python as well?</p> <p>example:</p> <pre><code>def do_something(...
22
2009-04-16T21:48:53Z
758,590
<p>I've never come across a case where "forward-function-definition" is necessary.. Can you not simply move <code>print_something()</code> to inside your main function..?</p> <pre><code>def do_something(ds_parameter): helper_function(ds_parameter) .... def print_something(): do_something(my_value) d...
2
2009-04-17T00:29:44Z
[ "python" ]
Make function definition in a python file order independent
758,188
<p>I use Python CGI. I cannot call a function before it is defined.</p> <p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p> <p>Is there such a trick in Python as well?</p> <p>example:</p> <pre><code>def do_something(...
22
2009-04-16T21:48:53Z
11,898,838
<p>An even better illustration of your point would be:</p> <pre><code>def main(): print_something() .... def do_something(ds_parameter): helper_function(ds_parameter) .... def print_something(): do_something(my_value) def helper_function(hf_parameter): .... main() </code></pre> <p...
9
2012-08-10T09:26:29Z
[ "python" ]
Make function definition in a python file order independent
758,188
<p>I use Python CGI. I cannot call a function before it is defined.</p> <p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p> <p>Is there such a trick in Python as well?</p> <p>example:</p> <pre><code>def do_something(...
22
2009-04-16T21:48:53Z
32,847,180
<pre><code>def funB(d,c): return funA(d,c) print funB(2,3) def funA(x,y): return x+y </code></pre> <p>The above code will return Error. But, the following code is fine ... </p> <pre><code> def funB(d,c): return funA(d,c) def funA(x,y): return x+y print funB(2,3) </code></pre> <p>So, even thoug...
0
2015-09-29T14:51:31Z
[ "python" ]
how to use pycurl if requested data is sometimes gzipped, sometimes not?
758,243
<p>I'm doing this to fetch some data:</p> <pre><code>c = pycurl.Curl() c.setopt(pycurl.ENCODING, 'gzip') c.setopt(pycurl.URL, url) c.setopt(pycurl.TIMEOUT, 10) c.setopt(pycurl.FOLLOWLOCATION, True) xml = StringIO() c.setopt(pycurl.WRITEFUNCTION, xml.write ) c.perform() c.close() </code></pre> <p>My urls are ty...
2
2009-04-16T22:11:52Z
758,271
<p>If worst comes to worst, you could omit the ENCODING 'gzip', set HTTPHEADER to {'Accept-Encoding' : 'gzip'}, <a href="http://stackoverflow.com/questions/472179/how-to-read-the-header-with-pycurl">check the response headers</a> for "Content-Encoding: gzip" and if it's present, gunzip the response yourself.</p>
4
2009-04-16T22:20:21Z
[ "python", "http", "gzip", "libcurl", "pycurl" ]
PyQt4 Minimize to Tray
758,256
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
20
2009-04-16T22:16:37Z
758,352
<p>It's pretty straightforward once you remember that there's no way to actually minimize to the <a href="http://blogs.msdn.com/oldnewthing/archive/2003/09/10/54831.aspx">system tray</a>. </p> <p>Instead, you fake it by doing this:</p> <ol> <li>Catch the minimize event on your window</li> <li>In the minimize event h...
26
2009-04-16T22:53:20Z
[ "python", "pyqt4", "system-tray", "minimize" ]
PyQt4 Minimize to Tray
758,256
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
20
2009-04-16T22:16:37Z
758,422
<p>Code helps, so here's something I wrote for an application, except for the closeEvent instead of the minimize event.</p> <p>Notes:</p> <p>"closeEvent(event)" is an overridden Qt event, so it must be put in the class that implements the window you want to hide.</p> <p>"okayToClose()" is a function you might consid...
10
2009-04-16T23:17:59Z
[ "python", "pyqt4", "system-tray", "minimize" ]
PyQt4 Minimize to Tray
758,256
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
20
2009-04-16T22:16:37Z
1,737,709
<p>Just to add to the example by Chris:</p> <p>It is crucial that you use the Qt notation when declaring the signal, ie</p> <p><strong>correct</strong>:</p> <pre><code>self.connect(self.icon, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.iconClicked) </code></pre> <p>and not the PyQt one</p> <p><str...
6
2009-11-15T14:49:31Z
[ "python", "pyqt4", "system-tray", "minimize" ]
PyQt4 Minimize to Tray
758,256
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
20
2009-04-16T22:16:37Z
4,676,943
<p>Here's working code..Thanks <strong>Matze</strong> for <strong>Crucial</strong>, the SIGNAL took me more hours of curiosity.. but doing other things. so ta for a #! moment :-)</p> <pre><code>def create_sys_tray(self): self.sysTray = QtGui.QSystemTrayIcon(self) self.sysTray.setIcon( QtGui.QIcon('../images/co...
4
2011-01-13T05:01:05Z
[ "python", "pyqt4", "system-tray", "minimize" ]
PyQt4 Minimize to Tray
758,256
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
20
2009-04-16T22:16:37Z
8,027,187
<p>This is the code and it does help i believe in show me the code </p> <pre><code>import sys from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout, QSystemTrayIcon class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init_...
1
2011-11-06T13:11:45Z
[ "python", "pyqt4", "system-tray", "minimize" ]
PyQt4 Minimize to Tray
758,256
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
20
2009-04-16T22:16:37Z
30,021,530
<p>This was an edit of vzades response, but it was rejected on a number of grounds. It does the exact same thing as their code but will also obey the minimize event (and run without syntax errors/missing icons).</p> <pre><code>import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__...
2
2015-05-04T01:56:58Z
[ "python", "pyqt4", "system-tray", "minimize" ]
Program Control-Flow in Python
758,465
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p> <pre><code>. . . 007 A000000 Y 007 B000000 5 007 C010100 1 007 C020100 ACORN FUND 007 C030100 N 007 C010200 2 007 C020200 ACORN INTERNATIONAL 007 C030200 N 007 C010300 3 007 C020300 ACORN USA 007 C030300 N 007 C01...
1
2009-04-16T23:41:03Z
758,518
<p>You could read the data into a dictionary. Assuming you are reading from a file-like object <code>infile</code>:</p> <pre><code>from collections import defaultdict data = defaultdict(list) for line in infile: elements = line.strip().split() data[elements[0]].append(tuple(elements[1:])) </code></pre> <p>No...
2
2009-04-17T00:00:22Z
[ "python", "list", "enumerate" ]
Program Control-Flow in Python
758,465
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p> <pre><code>. . . 007 A000000 Y 007 B000000 5 007 C010100 1 007 C020100 ACORN FUND 007 C030100 N 007 C010200 2 007 C020200 ACORN INTERNATIONAL 007 C030200 N 007 C010300 3 007 C020300 ACORN USA 007 C030300 N 007 C01...
1
2009-04-16T23:41:03Z
758,534
<p>The only difficulty with using all the data in a dictionary is that a really big dictionary can become troublesome. (It's what we used to call the "Big Ole Matrix" approach.)</p> <p>A solution to this is to construct an <em>index</em> in the Dictionary, creating a mapping of key->offset, using the <code>tell</code...
2
2009-04-17T00:06:13Z
[ "python", "list", "enumerate" ]
Program Control-Flow in Python
758,465
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p> <pre><code>. . . 007 A000000 Y 007 B000000 5 007 C010100 1 007 C020100 ACORN FUND 007 C030100 N 007 C010200 2 007 C020200 ACORN INTERNATIONAL 007 C030200 N 007 C010300 3 007 C020300 ACORN USA 007 C030300 N 007 C01...
1
2009-04-16T23:41:03Z
758,689
<p>You can use <code>itertools.groupby()</code> to segment your sequence into multiple sub-sequences. </p> <pre><code>import itertools for key, subseq in itertools.groupby(tempans, lambda s: s.partition(' ')[0]): if key == '007': for dataLine in subseq: if dataLine.startswith('007 B'): numberOfS...
3
2009-04-17T01:35:02Z
[ "python", "list", "enumerate" ]
Program Control-Flow in Python
758,465
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p> <pre><code>. . . 007 A000000 Y 007 B000000 5 007 C010100 1 007 C020100 ACORN FUND 007 C030100 N 007 C010200 2 007 C020200 ACORN INTERNATIONAL 007 C030200 N 007 C010300 3 007 C020300 ACORN USA 007 C030300 N 007 C01...
1
2009-04-16T23:41:03Z
761,798
<p>Okay-while I was Googling to make sure I had covered my bases I came across a solution:</p> <p>I find that I forget to think in Lists and Dictionaries even though I use them. Python has some powerful tools to work with these types to speed your ability to manipulate them.<br /> I need a slice so the slice referenc...
0
2009-04-17T19:14:06Z
[ "python", "list", "enumerate" ]
Program Control-Flow in Python
758,465
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p> <pre><code>. . . 007 A000000 Y 007 B000000 5 007 C010100 1 007 C020100 ACORN FUND 007 C030100 N 007 C010200 2 007 C020200 ACORN INTERNATIONAL 007 C030200 N 007 C010300 3 007 C020300 ACORN USA 007 C030300 N 007 C01...
1
2009-04-16T23:41:03Z
761,859
<p>You said you wanted to do this:</p> <pre><code>if dataLine.find(''007 A000000 Y')==0: READ THE NEXT LINE RIGHT HERE </code></pre> <p>Presumably this is within a "for dataLine in data" loop.</p> <p>Alternatively, you could use an iterator directly instead of in a for loop:</p> <pre><code>&gt;&gt;&gt; i = iter...
0
2009-04-17T19:33:11Z
[ "python", "list", "enumerate" ]
suggestions for a daemon that accepts zip files for processing
758,466
<p>im looking to write a daemon that:</p> <ul> <li>reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file</li> <li>updates a record in the database saying something like "this job is processing"</li> <li>reads the aforementioned archive's contents and inserts a row into a database ...
2
2009-04-16T23:41:04Z
758,498
<p>I've used <a href="http://xph.us/software/beanstalkd/" rel="nofollow">Beanstalkd</a> as a queueing daemon to very good effect (some near-time processing and image resizing - over 2 million so far in the last few weeks). Throw a message into the queue with the zip filename (maybe from a specific directory) [I seriali...
1
2009-04-16T23:53:28Z
[ "python", "django", "zip", "daemon" ]
suggestions for a daemon that accepts zip files for processing
758,466
<p>im looking to write a daemon that:</p> <ul> <li>reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file</li> <li>updates a record in the database saying something like "this job is processing"</li> <li>reads the aforementioned archive's contents and inserts a row into a database ...
2
2009-04-16T23:41:04Z
758,631
<p>I would avoid doing anything multi-threaded and instead use the queue and the database to synchronize as many worker processes as you care to start up.</p> <p>For this application I think twisted or any framework for creating server applications is going to be overkill. </p> <p>Keep it simple. Python script starts...
1
2009-04-17T00:53:54Z
[ "python", "django", "zip", "daemon" ]
suggestions for a daemon that accepts zip files for processing
758,466
<p>im looking to write a daemon that:</p> <ul> <li>reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file</li> <li>updates a record in the database saying something like "this job is processing"</li> <li>reads the aforementioned archive's contents and inserts a row into a database ...
2
2009-04-16T23:41:04Z
1,799,405
<p>i opted to use a combination of celery (<a href="http://ask.github.com/celery/introduction.html" rel="nofollow">http://ask.github.com/celery/introduction.html</a>), rabbitmq, and a simple django view to handle uploads. the workflow looks like this:</p> <ol> <li>django view accepts, stores upload</li> <li>a celery <...
1
2009-11-25T19:28:50Z
[ "python", "django", "zip", "daemon" ]
Using sphinx/miktex to generate pdf files that displays UTF8 Japanese (CJK) text in windows
758,693
<p>I have documentation in ReSt (UTF8) and I'm using <a href="http://sphinx.pocoo.org/" rel="nofollow">sphinx</a> to generate HTML and latex files. (No issues with html conversion)</p> <p>I then want to convert the resulting latex file to PDf. Currently I'm using <a href="http://miktex.org/" rel="nofollow">MiKTeX</a>...
1
2009-04-17T01:37:32Z
984,015
<p>I would use xelatex (available in MikTeX since 2.7) instead of pdflatex and an OpenType Kanji font. The file text.tex consisting of</p> <pre> \documentclass{article} \usepackage{fontspec} \setmainfont{Sazanami Gothic} \begin{document} こんにちは 世界 \end{document} </pre> <p>compiles with "xelatex text" to...
3
2009-06-11T22:08:26Z
[ "python", "windows", "pdflatex", "python-sphinx", "miktex" ]
Python Sort Collections.DefaultDict in Descending order
758,792
<p>I have this bit of code:</p> <pre><code> visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 </code></pre> <p>I looked at some examples online that used the sorted method like so:</p> <p><code>sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True)</code></p> <p...
8
2009-04-17T02:41:58Z
758,803
<p>iteritems is a method. You need parenthesis to call it: <code>visits.iteritems()</code>.</p> <p>As it stands now, you are passing the iteritems method itself to <code>sorted</code> which is why it is complaining that it can't iterate over a function or method. </p>
12
2009-04-17T02:49:30Z
[ "python" ]
Python Sort Collections.DefaultDict in Descending order
758,792
<p>I have this bit of code:</p> <pre><code> visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 </code></pre> <p>I looked at some examples online that used the sorted method like so:</p> <p><code>sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True)</code></p> <p...
8
2009-04-17T02:41:58Z
758,847
<p>Personally I think one of these forms is a little more succinct as the first argument only needs to be an iterable not an iterator.</p> <pre><code>sorted_keys = sorted(visits.keys(), reverse=True) sorted_keys = visits.keys().sort(reverse=True) </code></pre>
1
2009-04-17T03:08:28Z
[ "python" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
758,843
<p>Maybe try adding the keyword parameter <code>unix_socket = None</code> to <code>connect()</code>?</p>
-1
2009-04-17T03:07:36Z
[ "python", "mysql", "connection" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
758,881
<p>Make sure that the mysql server is listening for tcp connections, which you can do with netstat -nlp (in *nix). This is the type of connection you are attempting to make, and db's normally don't listen on the network by default for security reasons. Also, try specifying --host=localhost when using the mysql command,...
3
2009-04-17T03:19:03Z
[ "python", "mysql", "connection" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
834,431
<p>add <code>unix_socket='path_to_socket'</code> where <code>path_to_socket</code> should be the path of the MySQL socket, e.g. <code>/var/run/mysqld/mysqld2.sock</code></p>
8
2009-05-07T12:41:01Z
[ "python", "mysql", "connection" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
1,376,464
<p>As far as I can tell, the python connector can ONLY connect to mysql through a internet socket: unix sockets (the default for the command line client) is not supported.</p> <p>In the CLI client, when you say "-h localhost", it actually interprets localhost as "Oh, localhost? I'll just connect to the unix socket ins...
-1
2009-09-03T23:19:53Z
[ "python", "mysql", "connection" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
3,251,205
<p>I had this issue where the unix socket file was some place else, python was trying to connect to a non-existing socket. Once this was corrected using the unix_socket option, it worked.</p>
3
2010-07-14T22:58:58Z
[ "python", "mysql", "connection" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
4,789,108
<p>Mysql uses sockets when the host is 'localhost' and tcp/ip when the host is anything else. By default Mysql will listen to both - you can disable either sockets or networking in you my.cnf file (see mysql.com for details).</p> <p>In your case forget about the port=3000 the mysql client lib is not paying any attent...
1
2011-01-25T01:26:52Z
[ "python", "mysql", "connection" ]
Python: MySQLdb Connection Problems
758,819
<p>I'm having trouble with the MySQLdb module.</p> <pre><code>db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>(I'm using a custom port)</p> <p>the error I get is:</p> <pre>Error 2002: Can't connect to local MySQL server throu...
10
2009-04-17T02:55:57Z
6,482,408
<p>Changing <code>localhost</code> to <code>127.0.0.1</code> solved my problem using <code>MySQLdb</code>:</p> <pre><code>db = MySQLdb.connect( host = '127.0.0.1', user = 'root', passwd = '', db = 'testdb', port = 3000) </code></pre> <p>Using <code>127.0.0.1</code> forces the client to use TCP...
36
2011-06-26T05:57:38Z
[ "python", "mysql", "connection" ]
Matplotlib suddenly crashes after reinstalling Xcode?
758,980
<p>I was happy in my world of python and matplotlib with a good level of familiarity. I notied Xcode on my Mac wasn't working so I installed the latest version from Apple and it somehow broke my install of matplotlib (or numpy?)! I'm now getting </p> <pre><code>... /sw/lib/python2.5/site-packages/matplotlib-0.91.1-py2...
1
2009-04-17T04:08:36Z
758,998
<p>You're using Python from Fink, so Xcode doesn't have anything to do with it. <code>from numpy.core.ma import *</code> works fine with Apple's bundled Python and NumPy too.</p>
3
2009-04-17T04:13:54Z
[ "python", "xcode", "numpy", "matplotlib" ]
How can I remove a temporary file (image) that is being displayed by CGI?
759,271
<p>I've written a python CGI script that converts files into .jpgs and displays them in a simple HTML page. I don't want to clutter up the folders with these .jpg files, so I used tempfile.NamedTemporaryFile to create a file to store the converted .jpg output. Everything works great, but i want to remove this file af...
2
2009-04-17T06:37:22Z
759,547
<p>You can't remove the file from your cgi script. Because the html page is send to the user only after your script finishes to run. And then the users browser parse the html and fetch the jpg file.</p> <p>The simplest option is to write the temporary files to a sub directory and periodically clean that directory (liv...
3
2009-04-17T08:33:55Z
[ "python", "image", "cgi" ]
Child process detecting the parent process' death in Python
759,443
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
7
2009-04-17T07:56:42Z
759,455
<p>You might get away with reading your parent process' ID very early in your process, and then checking, but of course that is prone to race conditions. The parent that did the spawn might have died immediately, and even before your process got to execute its first instruction.</p> <p>Unless you have a way of verifyi...
1
2009-04-17T08:01:56Z
[ "python", "subprocess" ]
Child process detecting the parent process' death in Python
759,443
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
7
2009-04-17T07:56:42Z
759,458
<p>If your Python process is running under Linux, and the <code>prctl()</code> system call is exposed, you can use the answer <a href="http://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits">here</a>.</p> <p>This can cause a signal to be sent to the child when the parent process die...
3
2009-04-17T08:02:38Z
[ "python", "subprocess" ]
Child process detecting the parent process' death in Python
759,443
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
7
2009-04-17T07:56:42Z
1,519,310
<p>The only reliable way I know of is to create a pipe specifically for this purpose. The child will have to repeatedly attempt to read from the pipe, preferably in a non-blocking fashion, or using select. It will get an error when the pipe does not exist anymore (presumably because of the parent's death).</p>
1
2009-10-05T10:32:39Z
[ "python", "subprocess" ]
Child process detecting the parent process' death in Python
759,443
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
7
2009-04-17T07:56:42Z
4,229,302
<p>Assuming the parent is alive when you start to do this, you can check whether it is still alive in a busy loop as such, by using <a href="http://code.google.com/p/psutil" rel="nofollow">psutil</a>:</p> <pre><code>import psutil, os, time me = psutil.Process(os.getpid()) while 1: if me.parent is not None: ...
1
2010-11-19T20:58:53Z
[ "python", "subprocess" ]
How do I make text wrapping match current indentation level in vim?
759,577
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p> <p>For instance, if I set my settings so that the line:</p> <pre><code>print 'Proce...
12
2009-04-17T08:41:31Z
759,583
<p>I think set textwidth=80 should do it.</p>
-1
2009-04-17T08:44:05Z
[ "python", "vim", "textwrapping" ]
How do I make text wrapping match current indentation level in vim?
759,577
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p> <p>For instance, if I set my settings so that the line:</p> <pre><code>print 'Proce...
12
2009-04-17T08:41:31Z
760,930
<p>You're looking for <code>breakindent</code></p> <p>You may want to also refer to <a href="http://newsgroups.derkeiler.com/Archive/Comp/comp.editors/2005-07/msg00056.html" rel="nofollow">this thread</a>.</p>
2
2009-04-17T15:38:33Z
[ "python", "vim", "textwrapping" ]
How do I make text wrapping match current indentation level in vim?
759,577
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p> <p>For instance, if I set my settings so that the line:</p> <pre><code>print 'Proce...
12
2009-04-17T08:41:31Z
763,031
<p>I recommend this vimscript:</p> <p><a href="http://www.vim.org/scripts/script.php?script_id=974" rel="nofollow">http://www.vim.org/scripts/script.php?script_id=974</a></p> <p>"This indentation script for python tries to match more closely what is suggested in PEP 8 (<a href="http://www.python.org/peps/pep-0008.htm...
1
2009-04-18T06:37:56Z
[ "python", "vim", "textwrapping" ]
How do I make text wrapping match current indentation level in vim?
759,577
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p> <p>For instance, if I set my settings so that the line:</p> <pre><code>print 'Proce...
12
2009-04-17T08:41:31Z
763,079
<p>For controlling the indentation of Python code, see <code>:h ft-python-indent</code>. This for example will make Vim indent two times the <code>shiftwidth</code> if you do a newline while there's an unclosed paren:</p> <pre><code>let g:pyindent_open_paren = '&amp;sw * 2' </code></pre> <p>However <code>&amp;sw * 2...
-1
2009-04-18T07:16:01Z
[ "python", "vim", "textwrapping" ]
How do I make text wrapping match current indentation level in vim?
759,577
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p> <p>For instance, if I set my settings so that the line:</p> <pre><code>print 'Proce...
12
2009-04-17T08:41:31Z
1,772,003
<p>I asked the <a href="http://superuser.com/questions/72714/vim-line-wrap-with-indent">same question on SuperUser</a>, eventually found this question, found the patch, and <a href="https://retracile.net/blog/2009/11/20/12.00" rel="nofollow">updated the patch</a> to work with Vim 7.2.148 from Fedora 11.</p> <p>You can...
6
2009-11-20T17:21:46Z
[ "python", "vim", "textwrapping" ]
How to use cherrypy as a web server for static files?
759,627
<p>Is it any easy way to use CherryPy as an web server that will display <code>.html</code> files in some folder? All CherryPy introductory documentation states that content is dynamically generated:</p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.e...
13
2009-04-17T08:54:26Z
759,666
<p>Here is some information on serving static content with CherryPy: <a href="http://docs.cherrypy.org/stable/progguide/files/static.html" rel="nofollow">http://docs.cherrypy.org/stable/progguide/files/static.html</a></p> <p>BTW, here is a simple way to share the current directory over HTTP with python:</p> <pre> $ p...
6
2009-04-17T09:06:31Z
[ "python", "cherrypy" ]
How to use cherrypy as a web server for static files?
759,627
<p>Is it any easy way to use CherryPy as an web server that will display <code>.html</code> files in some folder? All CherryPy introductory documentation states that content is dynamically generated:</p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.e...
13
2009-04-17T08:54:26Z
760,100
<pre><code># encode: utf-8 import cherrypy WEB_ROOT = "c:\\webserver\\root\\" class CServer( object ) : @cherrypy.expose def do_contact(self, **params): pass cherrypy.server.socket_port = 80 # INADDR_ANY: listen on all interfaces cherrypy.server.socket_host = '0.0.0.0' conf = { '/': { 'tools.static...
-1
2009-04-17T11:48:02Z
[ "python", "cherrypy" ]
How to use cherrypy as a web server for static files?
759,627
<p>Is it any easy way to use CherryPy as an web server that will display <code>.html</code> files in some folder? All CherryPy introductory documentation states that content is dynamically generated:</p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.e...
13
2009-04-17T08:54:26Z
760,115
<p>This simple code will serve files on current directory.</p> <pre><code>import os import cherrypy PATH = os.path.abspath(os.path.dirname(__file__)) class Root(object): pass cherrypy.tree.mount(Root(), '/', config={ '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': PA...
29
2009-04-17T11:53:00Z
[ "python", "cherrypy" ]
Performance Considerations Using Multiple Layers of Generators in Python?
759,729
<p>Are there any performance considerations for using a lot of generators chained together, as opposed to just a single generator.</p> <p>For example:</p> <pre><code>def A(self, items): for item in self.AB(items): if object.A(): yield item def AB(self, items): for object in self.ABC(objec...
3
2009-04-17T09:27:20Z
760,007
<p>There is nothing wrong with chaining generators, but in this example there is no reason for A to call self.AB, it can just loop over items to get the same result.</p> <p>You should write your code as clearly as you can and if it's slow then use a profiler to determine where the bottleneck is. Contrived examples suc...
2
2009-04-17T11:04:33Z
[ "python", "performance", "generator" ]
Unexpected result from sys.getrefcount
759,740
<p>When I typed:</p> <pre><code>&gt;&gt;&gt; astrd = 123 &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getrefcount(astrd) 3 &gt;&gt;&gt; </code></pre> <p>I am not getting where is <code>astrd</code> used 3 times ?</p>
5
2009-04-17T09:29:39Z
759,763
<p>From the <a href="http://docs.python.org/2/library/sys.html#sys.getrefcount" rel="nofollow">getrefcount docstring</a>:</p> <blockquote> <p>... The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to <code>getrefcount()</code>.</p> </bloc...
6
2009-04-17T09:37:41Z
[ "python", "garbage-collection" ]
Unexpected result from sys.getrefcount
759,740
<p>When I typed:</p> <pre><code>&gt;&gt;&gt; astrd = 123 &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getrefcount(astrd) 3 &gt;&gt;&gt; </code></pre> <p>I am not getting where is <code>astrd</code> used 3 times ?</p>
5
2009-04-17T09:29:39Z
759,777
<p>I think it counts the references to 123, try other examples, like</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; astrd = 1 &gt;&gt;&gt; sys.getrefcount(astrd) 177 &gt;&gt;&gt; astrd = 9802374987193847 &gt;&gt;&gt; sys.getrefcount(astrd) 2 &gt;&gt;&gt; </code></pre> <p>The refcount for 9802374987193847 fits co...
6
2009-04-17T09:42:22Z
[ "python", "garbage-collection" ]
Unexpected result from sys.getrefcount
759,740
<p>When I typed:</p> <pre><code>&gt;&gt;&gt; astrd = 123 &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getrefcount(astrd) 3 &gt;&gt;&gt; </code></pre> <p>I am not getting where is <code>astrd</code> used 3 times ?</p>
5
2009-04-17T09:29:39Z
759,780
<p>ints are implemented in a special way, they are cached and shared, that why you don't get 1.</p> <p>And python, uses reference counted objects. astrd is itself a reference, so you actually get the number of references to the int '123'. Try with another (user-defined) type and you'll get 1.</p>
4
2009-04-17T09:45:05Z
[ "python", "garbage-collection" ]
Unexpected result from sys.getrefcount
759,740
<p>When I typed:</p> <pre><code>&gt;&gt;&gt; astrd = 123 &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getrefcount(astrd) 3 &gt;&gt;&gt; </code></pre> <p>I am not getting where is <code>astrd</code> used 3 times ?</p>
5
2009-04-17T09:29:39Z
759,782
<p>It's not <code>astrd</code> that is referenced three times, but the value <code>123</code>. <code>astrd</code> is simply a name for the (immutable) number 123, which can be referenced however many times. Additionally to that, small integers are usually shared:</p> <pre><code>&gt;&gt;&gt; astrd = 123 &gt;&gt;&gt; sy...
7
2009-04-17T09:45:43Z
[ "python", "garbage-collection" ]
How to retrieve google appengine entities using their numerical id?
759,771
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how? I tried using:</p> <p>key = Key.from_path("ModelName", numericalId) m = ModelName.get(key)</p> <p>but the key generated wasnt correct.</p>
3
2009-04-17T09:39:55Z
759,801
<p><a href="http://code.google.com/intl/nl-NL/appengine/docs/python/datastore/creatinggettinganddeletingdata.html#Getting%5Fan%5FEntity%5FUsing%5Fa%5FKey" rel="nofollow">Getting an Entity Using a Key</a></p>
0
2009-04-17T09:55:13Z
[ "python", "google-app-engine" ]
How to retrieve google appengine entities using their numerical id?
759,771
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how? I tried using:</p> <p>key = Key.from_path("ModelName", numericalId) m = ModelName.get(key)</p> <p>but the key generated wasnt correct.</p>
3
2009-04-17T09:39:55Z
760,060
<p>Turns out I needed to do </p> <p>key = Key.from_path( Application_ModelName, numeric_id )</p> <p>wasn't clear till i looked at the dict() of an entity</p>
0
2009-04-17T11:27:23Z
[ "python", "google-app-engine" ]
How to retrieve google appengine entities using their numerical id?
759,771
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how? I tried using:</p> <p>key = Key.from_path("ModelName", numericalId) m = ModelName.get(key)</p> <p>but the key generated wasnt correct.</p>
3
2009-04-17T09:39:55Z
770,848
<p>You are looking for this: <a href="http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_id" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_id</a></p>
1
2009-04-21T02:38:15Z
[ "python", "google-app-engine" ]
How to retrieve google appengine entities using their numerical id?
759,771
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how? I tried using:</p> <p>key = Key.from_path("ModelName", numericalId) m = ModelName.get(key)</p> <p>but the key generated wasnt correct.</p>
3
2009-04-17T09:39:55Z
21,352,573
<p>Other answers refer to the old DB API. New applications will by default use the NDB datastore, which has a slightly different API. You can still do Model.get_by_id(id, parent) to retrieve an entity by id, but the NDB also supports options to specify the app and namespace. See <a href="https://developers.google.com/a...
0
2014-01-25T15:40:21Z
[ "python", "google-app-engine" ]
Map raw SQL to multiple related Django models
759,797
<p>Due to performance reasons I can't use the ORM query methods of Django and I have to use raw SQL for some complex questions. I want to find a way to map the results of a SQL query to several models.</p> <p>I know I can use the following statement to map the query results to one model, but I can't figure how to use ...
2
2009-04-17T09:52:49Z
760,118
<p>First, can you prove the ORM is stopping your performance? Sometimes performance problems are simply poor database design, or improper indexes. Usually this comes from trying to force-fit Django's ORM onto a legacy database design. Stored procedures and triggers can have adverse impact on performance -- especiall...
1
2009-04-17T11:54:36Z
[ "python", "sql", "mysql", "django", "django-models" ]
add request to django model method?
759,850
<p>I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this?</p> <p>One idea: Adding the request to a models method would do the trick. Is that possible?</p> <...
6
2009-04-17T10:11:04Z
759,894
<p>Yes, you can add a method to your model with a request paramater:</p> <pre><code>class MyModel(models.Model): fields.... def update_status(self, request): make something with the request... </code></pre>
0
2009-04-17T10:24:58Z
[ "python", "django", "django-models" ]
add request to django model method?
759,850
<p>I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this?</p> <p>One idea: Adding the request to a models method would do the trick. Is that possible?</p> <...
6
2009-04-17T10:11:04Z
760,077
<p>If your status is a value that changes, you have to break this into two separate parts.</p> <ol> <li><p>Updating the status. This must be called in a view function. The real work, however, belongs in the model. The view function calls the model method and does the save.</p></li> <li><p>Displaying the status. Th...
2
2009-04-17T11:38:56Z
[ "python", "django", "django-models" ]
python ctypes and sysctl
759,892
<p>I have following code</p> <pre><code>import sys from ctypes import * from ctypes.util import find_library libc = cdll.LoadLibrary(find_library("c")) CTL_KERN = 1 KERN_SHMMAX = 34 sysctl_names = { 'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX), } def posix_sysctl_long(name): _mem = c_uint64(0) _...
2
2009-04-17T10:24:38Z
760,276
<p>You are not providing the correct values to the sysctl function. Detailed information on the arguments of sysctl() can be found <a href="http://www.linuxjournal.com/article/2365">here</a>.</p> <p>Here are your errors:</p> <ul> <li>You have forgotten the <em>nlen</em> argument (second argument)</li> <li>The <em>old...
6
2009-04-17T12:49:11Z
[ "python", "c", "linux", "ctypes" ]
sys.getrefcount continuation
759,906
<p><a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">link text</a></p> <p>I got the concept of reference count</p> <p>So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?</p> <p>This is the sample codes.These codes I developed after my yesterday's...
0
2009-04-17T10:28:15Z
759,917
<p>It gets a <strong>chance</strong> to get collected on the next GC collection run.</p> <p>See: <a href="http://docs.python.org/library/gc.html" rel="nofollow">http://docs.python.org/library/gc.html</a></p>
1
2009-04-17T10:32:41Z
[ "python", "del" ]
sys.getrefcount continuation
759,906
<p><a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">link text</a></p> <p>I got the concept of reference count</p> <p>So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?</p> <p>This is the sample codes.These codes I developed after my yesterday's...
0
2009-04-17T10:28:15Z
759,970
<p>I believe that memory is automatically freed the moment the refcount reaches zero. The GC is not involved.</p> <p>The python GC is optional, and is only used when there are unreachable objects that has reference cycles. In fact, you can call <code>gc.disable()</code> if you are sure your program does not create ref...
5
2009-04-17T10:50:02Z
[ "python", "del" ]
sys.getrefcount continuation
759,906
<p><a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">link text</a></p> <p>I got the concept of reference count</p> <p>So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?</p> <p>This is the sample codes.These codes I developed after my yesterday's...
0
2009-04-17T10:28:15Z
761,032
<p>Could you give some background as to what you are doing? There's rarely any reason for explicitly using <code>del</code> on variables other than to clean up a namespace of things you don't want to expose. I'm not sure why you are calling <code>del file_name</code> or running <code>gc.collect()</code>. (<code>del s...
0
2009-04-17T16:04:25Z
[ "python", "del" ]
Investigating python process to see what's eating CPU
760,039
<p>I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc?</p> <p><strong>Update:</strong></...
6
2009-04-17T11:17:34Z
760,048
<p><a href="http://docs.python.org/library/profile.html#instant-user-s-manual">Profiling</a> might help you learn a bit of what it's doing. If your sort the output by "time" you will see which functions are chowing up cpu time, which should give you some good hints.</p>
7
2009-04-17T11:22:27Z
[ "python", "multithreading", "debugging", "monitoring", "pylons" ]
Investigating python process to see what's eating CPU
760,039
<p>I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc?</p> <p><strong>Update:</strong></...
6
2009-04-17T11:17:34Z
784,432
<p>As you noted, in --reload mode, Paste sweeps the filesystem every second to see if any of the files loaded have changed. If they have, then Paste reloads the process. You can also manually tell Paste to monitor non-Python code modules for changes if desired.</p> <p>You can change the reload interval with the --relo...
5
2009-04-24T03:45:38Z
[ "python", "multithreading", "debugging", "monitoring", "pylons" ]
How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label
760,310
<p>I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. </p> <p>Are there any properties I can modify about a device that will not cause it to behave/look differently to the user?</p> <p>Running Ubuntu Jaunty.</p>
1
2009-04-17T12:58:48Z
760,744
<p>You cannot modify this property, but the tuple (vendor_id, product_id, serial_number) is unique to each device, so you can use this as mark that is already there. You can enumerate the devices on the USB bus using lsusb or usblib.</p>
1
2009-04-17T14:59:41Z
[ "python", "hardware", "mount", "dbus", "hal" ]
How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label
760,310
<p>I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. </p> <p>Are there any properties I can modify about a device that will not cause it to behave/look differently to the user?</p> <p>Running Ubuntu Jaunty.</p>
1
2009-04-17T12:58:48Z
760,814
<p>Changing the VID/PID might make your device non-usable without custom drivers. HAL isn't supposed to auto-mount your flash drives for you. </p> <p>That being said, you could always sneak something into the boot sector and/or the beginning part of the drive. There are a lot of spare bytes in there that can be used f...
0
2009-04-17T15:12:10Z
[ "python", "hardware", "mount", "dbus", "hal" ]
Self updating py2exe/py2app application
760,383
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p> <p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p> <p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</...
12
2009-04-17T13:22:58Z
760,490
<p>I don't know about patches, but on OS X the "standard" for this with cocoa apps is <a href="http://sparkle.andymatuschak.org/" rel="nofollow">Sparkle</a>. Basically it does "appcasting". It downloads the full app each time. It might be worth looking at it for inspiration.</p> <p>I imagine on OS X you can probabl...
3
2009-04-17T13:47:47Z
[ "python", "deployment", "patch", "py2exe" ]
Self updating py2exe/py2app application
760,383
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p> <p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p> <p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</...
12
2009-04-17T13:22:58Z
760,494
<p>I don't believe py2exe supports patched updates. However, if you do not bundle the entire package into a single EXE (<a href="http://www.py2exe.org/index.cgi/SingleFileExecutable" rel="nofollow">py2exe website example</a> - bottom of page), <strong>you can get away with smaller updates by just replacing certain file...
4
2009-04-17T13:48:34Z
[ "python", "deployment", "patch", "py2exe" ]
Self updating py2exe/py2app application
760,383
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p> <p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p> <p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</...
12
2009-04-17T13:22:58Z
760,788
<p>Since py2exe puts all of the compiled modules of your app into a ZIP file, you could try to update this file by creating a script that updates it from a given set of files. Then replace the remaining files that have changed (which should be few, if any).</p>
1
2009-04-17T15:06:33Z
[ "python", "deployment", "patch", "py2exe" ]
Self updating py2exe/py2app application
760,383
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p> <p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p> <p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</...
12
2009-04-17T13:22:58Z
17,540,301
<p>This is 4 years old now, but what about <a href="https://pypi.python.org/pypi/esky" rel="nofollow">Esky</a>?</p>
2
2013-07-09T05:02:48Z
[ "python", "deployment", "patch", "py2exe" ]
Generator function getting executed twice?
760,647
<p>I'm using a python generator function to provide me with a list of images in the current directory. However I see the function is giving out the entire list twice instead of one time and I have no idea why. I'm using the Python PIL library to create batch thumbnails.</p> <p>Can anyone point me in the right directio...
1
2009-04-17T14:35:51Z
760,680
<p>Your thumbnails are in a subdirectory of <code>self.image_path</code> and have the same name as the original image. Can you check if walk finds the thumnails as you create them? Just print the path of the image together with the name.</p>
0
2009-04-17T14:46:26Z
[ "python", "generator" ]
Generator function getting executed twice?
760,647
<p>I'm using a python generator function to provide me with a list of images in the current directory. However I see the function is giving out the entire list twice instead of one time and I have no idea why. I'm using the Python PIL library to create batch thumbnails.</p> <p>Can anyone point me in the right directio...
1
2009-04-17T14:35:51Z
760,709
<p>In your debugging, print the full path. I think you're walking the <code>thumbs</code> subdirectory after you walk the <code>.</code> directory.</p> <p>Also. </p> <pre><code>class ThumbnailGenerator( object ): </code></pre> <p>Usually works out better in the long run.</p> <p>Please do NOT use <code>__</code> in...
3
2009-04-17T14:51:34Z
[ "python", "generator" ]
Use value of variable in lambda expression
760,688
<pre><code>a = [] a.append(lambda x:x**0) a.append(lambda x:x**1) a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ... b=[] for i in range(4) b.append(lambda x:x**i) b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ... </code></pre> <p>In the for loop, the i is being passed to lambda as a variable, so when I cal...
3
2009-04-17T14:47:48Z
760,732
<p>Ugly, but one way:</p> <pre><code>for i in range(4) b.append(lambda x, copy=i: x**copy) </code></pre> <p>You might prefer</p> <pre><code>def raiser(power): return lambda x: x**power for i in range(4) b.append(raiser(i)) </code></pre> <p>(All code untested.)</p>
5
2009-04-17T14:56:57Z
[ "python", "lambda" ]
Use value of variable in lambda expression
760,688
<pre><code>a = [] a.append(lambda x:x**0) a.append(lambda x:x**1) a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ... b=[] for i in range(4) b.append(lambda x:x**i) b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ... </code></pre> <p>In the for loop, the i is being passed to lambda as a variable, so when I cal...
3
2009-04-17T14:47:48Z
760,750
<pre><code>b=[] f=(lambda p:(lambda x:x**p)) for i in range(4): b.append(f(i)) for g in b: print g(2) </code></pre>
2
2009-04-17T15:00:27Z
[ "python", "lambda" ]
Use value of variable in lambda expression
760,688
<pre><code>a = [] a.append(lambda x:x**0) a.append(lambda x:x**1) a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ... b=[] for i in range(4) b.append(lambda x:x**i) b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ... </code></pre> <p>In the for loop, the i is being passed to lambda as a variable, so when I cal...
3
2009-04-17T14:47:48Z
760,878
<p>Define a factory</p> <pre><code>def power_function_factory(value): def new_power_function(base): return base ** value return new_power_function b = [] for i in range(4): b.append(power_function_factory(i)) </code></pre> <p>or </p> <pre><code>b = [power_function_factory(i) for i in range(4)] <...
2
2009-04-17T15:26:41Z
[ "python", "lambda" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
760,828
<p>One solution, although I challenge someone to do better ;-)</p> <pre><code>a = 'abcdef' b = [[a[i-1], a[i]] for i in range(1, len(a), 2)] for x, y in b: print "%s%s\n" % (x, y) </code></pre>
0
2009-04-17T15:13:39Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
760,829
<p>I am sure someone is going to come up with some more "Pythonic" but how about:</p> <pre><code>for y in range(0, len(x), 2): print "%s%s" % (x[y], x[y+1]) </code></pre> <p>Note that this would only work if you know that <code>len(x) % 2 == 0;</code></p>
7
2009-04-17T15:13:44Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
760,830
<p>you can create the following generator</p> <pre><code>def chunks(seq, size): a = range(0, len(seq), size) b = range(size, len(seq) + 1, size) for i, j in zip(a, b): yield seq[i:j] </code></pre> <p>and use it like this:</p> <pre><code>for i in chunks('abcdef', 2): print(i) </code></pre>
3
2009-04-17T15:14:36Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
760,857
<p>A generator function would be neat:</p> <pre><code>def batch_gen(data, batch_size): for i in range(0, len(data), batch_size): yield data[i:i+batch_size] </code></pre> <p>Example use:</p> <pre><code>a = "abcdef" for i in batch_gen(a, 2): print i </code></pre> <p>prints:</p> <pre><code>ab cd ef </...
39
2009-04-17T15:20:36Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
760,887
<p>Don't forget about the zip() function:</p> <pre><code>a = 'abcdef' for x,y in zip(a[::2], a[1::2]): print '%s%s' % (x,y) </code></pre>
10
2009-04-17T15:28:48Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
760,899
<p>but the more general way would be (inspired by <a href="http://stackoverflow.com/questions/756550/multiple-tuple-to-two-pair-tuple-in-python/756602#756602">this answer</a>):</p> <pre><code>for i in zip(*(seq[i::size] for i in range(size))): print(i) # tuple of individual values </code...
6
2009-04-17T15:30:53Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
761,125
<p>I've got an alternative approach, that works for iterables that don't have a known length. </p> <pre><code> def groupsgen(seq, size): it = iter(seq) while True: values = () for n in xrange(size): values += (it.next(),) yield values </code></pre> <p...
13
2009-04-17T16:24:48Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
782,173
<p>How about itertools?</p> <pre><code>from itertools import islice, groupby def chunks_islice(seq, size): while True: aux = list(islice(seq, 0, size)) if not aux: break yield "".join(aux) def chunks_groupby(seq, size): for k, chunk in groupby(enumerate(seq), lambda x: x[0] / size): ...
0
2009-04-23T15:10:44Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
782,321
<pre><code>&gt;&gt;&gt; a = "abcdef" &gt;&gt;&gt; size = 2 &gt;&gt;&gt; [a[x:x+size] for x in range(0, len(a), size)] ['ab', 'cd', 'ef'] </code></pre> <p>..or, not as a list comprehension:</p> <pre><code>a = "abcdef" size = 2 output = [] for x in range(0, len(a), size): output.append(a[x:x+size]) </code></pre> <...
4
2009-04-23T15:41:37Z
[ "iteration", "python" ]
Iterate over a python sequence in multiples of n?
760,753
<p>How do I process the elements of a sequence in batches, idiomatically?</p> <p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p> <pre><code>for x, y in "abcdef": print "%s%s\n" % (x, y) ab cd ef </code></pre> <p>Of course, this doesn't work beca...
17
2009-04-17T15:01:35Z
787,130
<p>And then there's always the <a href="http://docs.python.org/library/itertools.html">documentation</a>.</p> <pre><code>def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) try: b.next() except StopIteration: pass return izip(a, b) def grouper(n, ...
6
2009-04-24T18:59:15Z
[ "iteration", "python" ]