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
appengine: cached reference property?
1,174,075
<p>How can I cache a Reference Property in Google App Engine?</p> <p>For example, let's say I have the following models:</p> <pre><code>class Many(db.Model): few = db.ReferenceProperty(Few) class Few(db.Model): year = db.IntegerProperty() </code></pre> <p>Then I create many <code>Many</code>'s that point to only one <code>Few</code>:</p> <pre><code>one_few = Few.get_or_insert(year=2009) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) </code></pre> <p>Now, if I want to iterate over all the <code>Many</code>'s, reading their <code>few</code> value, I would do this:</p> <pre><code>for many in Many.all().fetch(1000): print "%s" % many.few.year </code></pre> <p>The question is:</p> <ul> <li>Will each access to <code>many.few</code> trigger a database lookup?</li> <li>If yes, is it possible to cache somewhere, as only one lookup should be enough to bring the same entity every time?</li> </ul> <p><hr /></p> <p>As noted in one comment: I know about memcache, but I'm not sure how I can "inject it" when I'm calling the other entity through a reference. </p> <p>In any case memcache wouldn't be useful, as I need caching within an execution, not between them. Using memcache wouldn't help optimizing this call.</p>
2
2009-07-23T19:51:30Z
1,174,737
<p>The first time you dereference any reference property, the entity is fetched - even if you'd previously fetched the same entity associated with a different reference property. This involves a datastore get operation, which isn't as expensive as a query, but is still worth avoiding if you can.</p> <p>There's a good module that adds seamless caching of entities available <a href="http://code.google.com/p/entity-memcaching/">here</a>. It works at a lower level of the datastore, and will cache all datastore gets, not just dereferencing ReferenceProperties.</p> <p>If you want to resolve a bunch of reference properties at once, there's another way: You can retrieve all the keys and fetch the entities in a single round trip, like so:</p> <pre><code>keys = [MyModel.ref.get_value_for_datastore(x) for x in referers] referees = db.get(keys) </code></pre> <p>Finally, I've written a library that monkeypatches the db module to locally cache entities on a per-request basis (no memcache involved). It's available, <a href="http://gist.github.com/43429">here</a>. One warning, though: It's got unit tests, but it's not widely used, so it could be broken.</p>
7
2009-07-23T21:57:58Z
[ "python", "database", "performance", "google-app-engine", "gae-datastore" ]
django comments: how to prevent form errors from redirecting the user to the preview page?
1,174,140
<p>Currently, django.contrib.comments sends the user to the preview page if there is any error on the form. </p> <p>I am using comments in the context of a blog and I would much rather that the user stayed on the page they were on if something went wrong with the submission. As far as I can tell though, this is hard-coded in django.contrib.comments.views.comments.post_comment:</p> <pre><code># If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ "comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")), "comments/%s_preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment" : form.data.get("comment", ""), "form" : form, "next": next, }, RequestContext(request, {}) ) </code></pre> <p>Is there any way that I can change this behavior without changing the source code to django.contrib.comments?</p> <p>Any pointer would be appreciated...</p> <p>Thanks!</p>
7
2009-07-23T20:01:27Z
1,174,287
<p>Yes! There's now a way to <a href="http://docs.djangoproject.com/en/dev/ref/contrib/comments/custom/" rel="nofollow">customize the Comments app</a>. Good luck!</p>
0
2009-07-23T20:30:16Z
[ "python", "django", "django-contrib" ]
django comments: how to prevent form errors from redirecting the user to the preview page?
1,174,140
<p>Currently, django.contrib.comments sends the user to the preview page if there is any error on the form. </p> <p>I am using comments in the context of a blog and I would much rather that the user stayed on the page they were on if something went wrong with the submission. As far as I can tell though, this is hard-coded in django.contrib.comments.views.comments.post_comment:</p> <pre><code># If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ "comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")), "comments/%s_preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment" : form.data.get("comment", ""), "form" : form, "next": next, }, RequestContext(request, {}) ) </code></pre> <p>Is there any way that I can change this behavior without changing the source code to django.contrib.comments?</p> <p>Any pointer would be appreciated...</p> <p>Thanks!</p>
7
2009-07-23T20:01:27Z
1,174,307
<p>Looks like you have two real options:</p> <ul> <li>Write your own view. Possibly copy that view's code to get started.</li> <li>Patch that view to take an extra parameter, such as 'preview_on_errors' which defaults to True but can be overridden. Contribute the patch back to Django so other people can benefit from it.</li> </ul>
3
2009-07-23T20:34:28Z
[ "python", "django", "django-contrib" ]
To calculate the sum of numbers in a list by Python
1,174,435
<p>My data</p> <pre><code>466.67 465.56 464.44 463.33 462.22 461.11 460.00 458.89 ... </code></pre> <p>I run in Python</p> <pre><code>sum(/tmp/1,0) </code></pre> <p>I get an error.</p> <p><strong>How can you calculate the sum of the values by Python?</strong></p>
-2
2009-07-23T20:52:17Z
1,174,443
<pre><code>f=open('/tmp/1') print sum(map(float,f)) </code></pre>
13
2009-07-23T20:54:46Z
[ "python" ]
To calculate the sum of numbers in a list by Python
1,174,435
<p>My data</p> <pre><code>466.67 465.56 464.44 463.33 462.22 461.11 460.00 458.89 ... </code></pre> <p>I run in Python</p> <pre><code>sum(/tmp/1,0) </code></pre> <p>I get an error.</p> <p><strong>How can you calculate the sum of the values by Python?</strong></p>
-2
2009-07-23T20:52:17Z
1,174,483
<pre><code>sum(float(i) for i in open('/tmp/1.0')) </code></pre>
11
2009-07-23T21:05:10Z
[ "python" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,175,005
<p>You could look at the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Standard%5Fdeviation" rel="nofollow">Standard Deviation</a>, in particular the section about Rapid calculation methods.</p> <p>There's also an article I found that uses Python, you should be able to use the code in it without much change: <a href="http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/" rel="nofollow">Subliminal Messages - Running Standard Deviations</a>.</p>
2
2009-07-23T23:14:18Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,175,029
<p><a href="http://search.cpan.org/perldoc/Statistics::Descriptive">Statistics::Descriptive</a> is a very decent Perl module for these types of calculations:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use Statistics::Descriptive qw( :all ); my $data = [ [ 0.01, 0.01, 0.02, 0.04, 0.03 ], [ 0.00, 0.02, 0.02, 0.03, 0.02 ], [ 0.01, 0.02, 0.02, 0.03, 0.02 ], [ 0.01, 0.00, 0.01, 0.05, 0.03 ], ]; my $stat = Statistics::Descriptive::Full-&gt;new; # You also have the option of using sparse data structures for my $ref ( @$data ) { $stat-&gt;add_data( @$ref ); printf "Running mean: %f\n", $stat-&gt;mean; printf "Running stdev: %f\n", $stat-&gt;standard_deviation; } __END__ </code></pre> <p>Output:</p> <pre><code>C:\Temp&gt; g Running mean: 0.022000 Running stdev: 0.013038 Running mean: 0.020000 Running stdev: 0.011547 Running mean: 0.020000 Running stdev: 0.010000 Running mean: 0.020000 Running stdev: 0.012566 </code></pre>
7
2009-07-23T23:21:19Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,175,054
<p>I think this issue will help you. <a href="http://www.johndcook.com/standard%5Fdeviation.html" rel="nofollow">Standard deviation</a></p>
2
2009-07-23T23:31:14Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,175,065
<p>How big is your array? Unless it is zillions of elements long, don't worry about looping through it twice. The code is simple and easily tested.</p> <p>My preference would be to use the <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a> array maths extension to convert your array of arrays into a numpy 2D array and get the standard deviation directly:</p> <pre><code>&gt;&gt;&gt; x = [ [ 1, 2, 4, 3, 4, 5 ], [ 3, 4, 5, 6, 7, 8 ] ] * 10 &gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array(x) &gt;&gt;&gt; a.std(axis=0) array([ 1. , 1. , 0.5, 1.5, 1.5, 1.5]) &gt;&gt;&gt; a.mean(axis=0) array([ 2. , 3. , 4.5, 4.5, 5.5, 6.5]) </code></pre> <p>If that's not an option and you need a pure Python solution, keep reading...</p> <p>If your array is </p> <pre><code>x = [ [ 1, 2, 4, 3, 4, 5 ], [ 3, 4, 5, 6, 7, 8 ], .... ] </code></pre> <p>Then the standard deviation is:</p> <pre><code>d = len(x[0]) n = len(x) sum_x = [ sum(v[i] for v in x) for i in range(d) ] sum_x2 = [ sum(v[i]**2 for v in x) for i in range(d) ] std_dev = [ sqrt((sx2 - sx**2)/N) for sx, sx2 in zip(sum_x, sum_x2) ] </code></pre> <p>If you are determined to loop through your array only once, the running sums can be combined.</p> <pre><code>sum_x = [ 0 ] * d sum_x2 = [ 0 ] * d for v in x: for i, t in enumerate(v): sum_x[i] += t sum_x2[i] += t**2 </code></pre> <p>This isn't nearly as elegant as the list comprehension solution above.</p>
3
2009-07-23T23:35:54Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,175,084
<p>The basic answer is to accumulate the sum of both <em>x</em> (call it 'sum_x1') and <em>x</em><sup>2</sup> (call it 'sum_x2') as you go. The value of the standard deviation is then:</p> <pre><code>stdev = sqrt((sum_x2 / n) - (mean * mean)) </code></pre> <p>where</p> <pre><code>mean = sum_x / n </code></pre> <p>This is the sample standard deviation; you get the population standard deviation using 'n' instead of 'n - 1' as the divisor.</p> <p>You may need to worry about the numerical stability of taking the difference between two large numbers if you are dealing with large samples. Go to the external references in other answers (Wikipedia, etc) for more information.</p>
61
2009-07-23T23:39:33Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,175,491
<p>Perhaps not what you were asking, but ... If you use a numpy array, it will do the work for you, efficiently:</p> <pre><code>from numpy import array nums = array(((0.01, 0.01, 0.02, 0.04, 0.03), (0.00, 0.02, 0.02, 0.03, 0.02), (0.01, 0.02, 0.02, 0.03, 0.02), (0.01, 0.00, 0.01, 0.05, 0.03))) print nums.std(axis=1) # [ 0.0116619 0.00979796 0.00632456 0.01788854] print nums.mean(axis=1) # [ 0.022 0.018 0.02 0.02 ] </code></pre> <p>By the way, there's some interesting discussion in this blog post and comments on one-pass methods for computing means and variances:</p> <ul> <li><a href="http://lingpipe-blog.com/2009/03/19/computing-sample-mean-variance-online-one-pass/">http://lingpipe-blog.com/2009/03/19/computing-sample-mean-variance-online-one-pass/</a></li> </ul>
24
2009-07-24T02:32:58Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,179,049
<p>Have a look at <a href="http://search.cpan.org/dist/PDL/">PDL</a> (pronounced "piddle!"). </p> <p>This is the Perl Data Language which is designed for high precision mathematics and scientific computing.</p> <p>Here is an example using your figures....</p> <pre><code>use strict; use warnings; use PDL; my $figs = pdl [ [0.01, 0.01, 0.02, 0.04, 0.03], [0.00, 0.02, 0.02, 0.03, 0.02], [0.01, 0.02, 0.02, 0.03, 0.02], [0.01, 0.00, 0.01, 0.05, 0.03], ]; my ( $mean, $prms, $median, $min, $max, $adev, $rms ) = statsover( $figs ); say "Mean scores: ", $mean; say "Std dev? (adev): ", $adev; say "Std dev? (prms): ", $prms; say "Std dev? (rms): ", $rms; </code></pre> <p><br /> Which produces:</p> <pre><code>Mean scores: [0.022 0.018 0.02 0.02] Std dev? (adev): [0.0104 0.0072 0.004 0.016] Std dev? (prms): [0.013038405 0.010954451 0.0070710678 0.02] Std dev? (rms): [0.011661904 0.009797959 0.0063245553 0.017888544] </code></pre> <p><br /> Have a look at <a href="http://search.cpan.org/dist/PDL/Basic/Primitive/primitive.pd">PDL::Primitive</a> for more information on the <i>statsover</i> function. This seems to suggest that ADEV is the "standard deviation". </p> <p>However it maybe PRMS (which Sinan's Statistics::Descriptive example show) or RMS (which ars's NumPy example shows). I guess one of these three must be right ;-)</p> <p>For more PDL information have a look at:</p> <ul> <li><a href="http://pdl.perl.org">pdl.perl.org</a> (official PDL page).</li> <li><a href="http://www.perlmonks.org/?node%5Fid=587436">PDL quick reference guide on PerlMonks</a></li> <li><a href="http://www.ddj.com/184410442">Dr. Dobb's article on PDL</a></li> <li><a href="http://sourceforge.net/apps/mediawiki/pdl/index.php?title=Main%5FPage">PDL Wiki</a></li> <li><a href="http://en.wikipedia.org/wiki/Perl%5FData%5FLanguage">Wikipedia entry for PDL</a></li> <li><a href="http://sourceforge.net/projects/pdl/">Sourceforge project page for PDL</a></li> </ul> <p>/I3az/</p>
8
2009-07-24T17:34:54Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
1,348,615
<p>The answer is to use Welford's algorithm, which is very clearly defined after the "naive methods" in:</p> <ul> <li>Wikipedia: <a href="http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance">Algorithms for calculating variance</a> </ul> <p>It's more numerically stable than either the two-pass or online simple sum of squares collectors suggested in other responses. The stability only really matters when you have lots of values that are close to each other as they lead to what is known as "<a href="http://www.cs.princeton.edu/introcs/lectures/9scientific.pdf">catastrophic cancellation</a>" in the floating point literature.</p> <p>You might also want to brush up on the difference between dividing by the number of samples (N) and N-1 in the variance calculation (squared deviation). Dividing by N-1 leads to an unbiased estimate of variance from the sample, whereas dividing by N on average underestimates variance (because it doesn't take into account the variance between the sample mean and the true mean).</p> <p>I wrote two blog entries on the topic which go into more details, including how to delete previous values online:</p> <ul> <li><a href="http://lingpipe-blog.com/2009/03/19/computing-sample-mean-variance-online-one-pass/">Computing Sample Mean and Variance Online in One Pass</a> <li><a href="http://lingpipe-blog.com/2009/07/07/welford-s-algorithm-delete-online-mean-variance-deviation/">Deleting Values in Welford’s Algorithm for Online Mean and Variance</a> </ul> <p>You can also take a look at my Java implement; the javadoc, source, and unit tests are all online:</p> <ul> <li><a href="http://alias-i.com/lingpipe/docs/api/com/aliasi/stats/OnlineNormalEstimator.html">Javadoc: <code>stats.OnlineNormalEstimator</code></a> <li><a href="http://alias-i.com/lingpipe/src/com/aliasi/stats/OnlineNormalEstimator.java">Source: <code>stats.OnlineNormalEstimator.java</code></a> <li><a href="http://alias-i.com/lingpipe/src/com/aliasi/test/unit/stats/OnlineNormalEstimatorTest.java">JUnit Source: <code>test.unit.stats.OnlineNormalEstimatorTest.java</code></a> <li><a href="http://alias-i.com/lingpipe">LingPipe Home Page</a> </ul>
71
2009-08-28T18:24:27Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
16,247,411
<p>Here's a "one-liner", spread over multiple lines, in functional programming style:</p> <pre class="lang-py prettyprint-override"><code>def variance(data, opt=0): return (lambda (m2, i, _): m2 / (opt + i - 1))( reduce( lambda (m2, i, avg), x: ( m2 + (x - avg) ** 2 * i / (i + 1), i + 1, avg + (x - avg) / (i + 1) ), data, (0, 0, 0))) </code></pre>
0
2013-04-27T01:34:23Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
17,637,351
<p>Here is a literal pure Python translation of the Welford's algorithm implementation from <a href="http://www.johndcook.com/standard_deviation.html">http://www.johndcook.com/standard_deviation.html</a>:</p> <p><a href="https://github.com/liyanage/python-modules/blob/master/running_stats.py">https://github.com/liyanage/python-modules/blob/master/running_stats.py</a></p> <pre><code>class RunningStats: def __init__(self): self.n = 0 self.old_m = 0 self.new_m = 0 self.old_s = 0 self.new_s = 0 def clear(self): self.n = 0 def push(self, x): self.n += 1 if self.n == 1: self.old_m = self.new_m = x self.old_s = 0 else: self.new_m = self.old_m + (x - self.old_m) / self.n self.new_s = self.old_s + (x - self.old_m) * (x - self.new_m) self.old_m = self.new_m self.old_s = self.new_s def mean(self): return self.new_m if self.n else 0.0 def variance(self): return self.new_s / (self.n - 1) if self.n &gt; 1 else 0.0 def standard_deviation(self): return math.sqrt(self.variance()) </code></pre> <p>Usage:</p> <pre><code>rs = RunningStats() rs.push(17.0); rs.push(19.0); rs.push(24.0); mean = rs.mean(); variance = rs.variance(); stdev = rs.standard_deviation(); </code></pre>
6
2013-07-14T07:10:53Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
20,832,236
<p>The <a href="http://www.grantjenks.com/blog/portfolio-post/python-runstats-module/">Python runstats Module</a> is for just this sort of thing. <a href="https://pypi.python.org/pypi/runstats">Install runstats</a> from PyPI:</p> <pre><code>pip install runstats </code></pre> <p>Runstats summaries can produce the mean, variance, standard deviation, skewness, and kurtosis in a single pass of data. We can use this to create your "running" version.</p> <pre><code>from runstats import Statistics stats = [Statistics() for num in range(len(data[0]))] for row in data: for index, val in enumerate(row): stats[index].push(val) for index, stat in enumerate(stats): print 'Index', index, 'mean:', stat.mean() print 'Index', index, 'standard deviation:', stat.stddev() </code></pre> <p>Statistics summaries are based on the Knuth and Welford method for computing standard deviation in one pass as described in the Art of Computer Programming, Vol 2, p. 232, 3rd edition. The benefit of this is numerically stable and accurate results.</p> <p><strong>Disclaimer:</strong> I am the author the Python runstats module.</p>
6
2013-12-30T01:46:06Z
[ "python", "perl", "statistics" ]
How to efficiently calculate a running standard deviation?
1,174,984
<p>I have an array of lists of numbers, e.g.:</p> <pre><code>[0] (0.01, 0.01, 0.02, 0.04, 0.03) [1] (0.00, 0.02, 0.02, 0.03, 0.02) [2] (0.01, 0.02, 0.02, 0.03, 0.02) ... [n] (0.01, 0.00, 0.01, 0.05, 0.03) </code></pre> <p>What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.</p> <p>To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by <code>n</code>.</p> <p>To do the standard deviation, I loop through again, now that I have the mean calculated.</p> <p>I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean). </p> <p>Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.</p>
53
2009-07-23T23:09:05Z
26,716,417
<pre><code>n=int(raw_input("Enter no. of terms:")) L=[] for i in range (1,n+1): x=float(raw_input("Enter term:")) L.append(x) sum=0 for i in range(n): sum=sum+L[i] avg=sum/n sumdev=0 for j in range(n): sumdev=sumdev+(L[j]-avg)**2 dev=(sumdev/n)**0.5 print "Standard deviation is", dev </code></pre>
1
2014-11-03T14:38:21Z
[ "python", "perl", "statistics" ]
How to refactor this Python code?
1,175,043
<pre><code>class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class Gadget(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'gadget.xml') self.response.out.write(template.render(path, template_values)) </code></pre>
0
2009-07-23T23:26:11Z
1,175,274
<p>Refactor for what purposes? Are you getting errors, want to do something else, or...? Assuming the proper imports and url dispatching around this, I don't see anything here that has to be refactored for app engine -- so, don't keep us guessing!-)</p>
1
2009-07-24T00:44:23Z
[ "python", "google-app-engine", "refactoring" ]
How to refactor this Python code?
1,175,043
<pre><code>class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class Gadget(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'gadget.xml') self.response.out.write(template.render(path, template_values)) </code></pre>
0
2009-07-23T23:26:11Z
1,175,364
<p>Since both classes are identical except for one string ('index.html' vs 'gadget.xml') would it be possible to make one a subclass of the other and have that one string as a class constant in both?</p>
1
2009-07-24T01:20:01Z
[ "python", "google-app-engine", "refactoring" ]
How to refactor this Python code?
1,175,043
<pre><code>class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class Gadget(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'gadget.xml') self.response.out.write(template.render(path, template_values)) </code></pre>
0
2009-07-23T23:26:11Z
1,175,373
<p>Make it the same class, and use a GET or POST parameter to decide which template to render.</p>
1
2009-07-24T01:22:22Z
[ "python", "google-app-engine", "refactoring" ]
How to refactor this Python code?
1,175,043
<pre><code>class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class Gadget(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), 'gadget.xml') self.response.out.write(template.render(path, template_values)) </code></pre>
0
2009-07-23T23:26:11Z
1,175,410
<p>Really it depends on what you expect to be common between the two classes in future. The purpose of refactoring is to identify common abstractions, not to minimise the number of lines of code.</p> <p>That said, assuming the two requests are expected to differ only in the template:</p> <pre><code>class TaskListPage(webapp.RequestHandler): def get(self): user = users.get_current_user() tasks_query = Task.all() tasks = tasks_query.fetch(1000) if user: url = users.create_logout_url(self.request.uri) else: url = users.create_login_url(self.request.uri) template_values = { 'tasks': tasks, 'url': url } path = os.path.join(os.path.dirname(__file__), self.template_name()) self.response.out.write(template.render(path, template_values)) class MainPage(TaskListPage): def template_name(self): return 'index.html' class Gadget(TaskListPage): def template_name(self): return 'gadget.xml' </code></pre>
6
2009-07-24T01:40:09Z
[ "python", "google-app-engine", "refactoring" ]
Python classes for simple GTD app
1,175,110
<p>I'm trying to code a very rudimentary GTD app for myself, not only to get organized, but to get better at coding and get better at Python. I'm having a bit of trouble with the classes however. </p> <p>Here are the classes I have so far:</p> <pre><code>class Project: def __init__(self, name, actions=[]): self.name = name self.actions = actions def add(self, action): self.actions.append(action) class Action: def __init__(self, do='', context=''): self.do = do self.context = context </code></pre> <p>Each project has actions to it, however I want to make it so that projects can also consist of other projects. Say daily I wanted to print out a list of everything. I'm having trouble coming up with how I would construct a list that looked like this</p> <pre><code>&gt; Project A &gt; Actions for Project A &gt; Project B &gt; Sub project A &gt; Actions for Sub project A &gt; Sub project B &gt; Actions for Sub project B &gt; Sub project C &gt; Sub sub project A &gt; Actions for sub sub project A &gt; Sub sub project B &gt; Actions for sub sub project B &gt; Actions for Sub project C &gt; Actions for Project B </code></pre> <p>It's quite clear to me that recursion is going to be used. I'm struggling with whether to create another class called SubProject and subclass Project to it. Something there just makes my brain raise an exception.</p> <p>I have been able to take projects and add them to the actions attribute in the Project class, however then I run into where MegaProject.actions.action.actions.action situations start popping up.</p> <p>If anyone could help out with the class structures, it would be greatly appreciated!</p>
2
2009-07-23T23:48:09Z
1,175,150
<p>I suggest you look at the <a href="http://en.wikipedia.org/wiki/Composite%5Fpattern" rel="nofollow">composite pattern</a> which can be applied to the "Project" class. If you make your structure correctly, you should be able to make action be a leaf of that tree, pretty much like you described in your example.</p> <p>You could, for instance, do a Project class (abstract), a ProjectComposite class (concrete) and your action class as a leaf.</p>
0
2009-07-23T23:59:57Z
[ "python", "design", "recursion", "gtd" ]
Python classes for simple GTD app
1,175,110
<p>I'm trying to code a very rudimentary GTD app for myself, not only to get organized, but to get better at coding and get better at Python. I'm having a bit of trouble with the classes however. </p> <p>Here are the classes I have so far:</p> <pre><code>class Project: def __init__(self, name, actions=[]): self.name = name self.actions = actions def add(self, action): self.actions.append(action) class Action: def __init__(self, do='', context=''): self.do = do self.context = context </code></pre> <p>Each project has actions to it, however I want to make it so that projects can also consist of other projects. Say daily I wanted to print out a list of everything. I'm having trouble coming up with how I would construct a list that looked like this</p> <pre><code>&gt; Project A &gt; Actions for Project A &gt; Project B &gt; Sub project A &gt; Actions for Sub project A &gt; Sub project B &gt; Actions for Sub project B &gt; Sub project C &gt; Sub sub project A &gt; Actions for sub sub project A &gt; Sub sub project B &gt; Actions for sub sub project B &gt; Actions for Sub project C &gt; Actions for Project B </code></pre> <p>It's quite clear to me that recursion is going to be used. I'm struggling with whether to create another class called SubProject and subclass Project to it. Something there just makes my brain raise an exception.</p> <p>I have been able to take projects and add them to the actions attribute in the Project class, however then I run into where MegaProject.actions.action.actions.action situations start popping up.</p> <p>If anyone could help out with the class structures, it would be greatly appreciated!</p>
2
2009-07-23T23:48:09Z
1,175,154
<p>You could create a subprojects member, similar to your actions list, and assign projects to it in a similar way. No subclassing of Project is necessary.</p> <pre><code>class Project: def __init__(self, name, actions=[], subprojects=[]): self.name = name self.actions = actions self.subprojects = subprojects def add(self, action): self.actions.append(action) def add_project(self, project) self.subprojects.append(project) </code></pre> <p>Even better, you may want to implement a composite pattern, where Projects are composites and Actions are leaves.</p> <pre><code>class Project: def __init__(self, name, children=[]): self.name = name self.children = children def add(self, object): self.children.append(object) def mark_done(self): for c in self.children: c.mark_done() class Action: def __init__(self, do): self.do = do self.done = False def mark_done(self): self.done = True </code></pre> <p>They key here is that the projects have the same interface as the actions (with the exception of the add/delete methods). This allows to to call methods on entire tree recursively. If you had a complex nested structure, you can call a method on the top level, and have it filter down to the bottom.</p> <p>If you'd like a method to get a flat list of all leaf nodes in the tree (Actions) you can implement a method like this in the Project class.</p> <pre><code>def get_action_list(self): actions = [] for c in self.children: if c.__class__ == self.__class__: actions += c.get_action_list() else: actions.append(c) return actions </code></pre>
3
2009-07-24T00:01:01Z
[ "python", "design", "recursion", "gtd" ]
Python classes for simple GTD app
1,175,110
<p>I'm trying to code a very rudimentary GTD app for myself, not only to get organized, but to get better at coding and get better at Python. I'm having a bit of trouble with the classes however. </p> <p>Here are the classes I have so far:</p> <pre><code>class Project: def __init__(self, name, actions=[]): self.name = name self.actions = actions def add(self, action): self.actions.append(action) class Action: def __init__(self, do='', context=''): self.do = do self.context = context </code></pre> <p>Each project has actions to it, however I want to make it so that projects can also consist of other projects. Say daily I wanted to print out a list of everything. I'm having trouble coming up with how I would construct a list that looked like this</p> <pre><code>&gt; Project A &gt; Actions for Project A &gt; Project B &gt; Sub project A &gt; Actions for Sub project A &gt; Sub project B &gt; Actions for Sub project B &gt; Sub project C &gt; Sub sub project A &gt; Actions for sub sub project A &gt; Sub sub project B &gt; Actions for sub sub project B &gt; Actions for Sub project C &gt; Actions for Project B </code></pre> <p>It's quite clear to me that recursion is going to be used. I'm struggling with whether to create another class called SubProject and subclass Project to it. Something there just makes my brain raise an exception.</p> <p>I have been able to take projects and add them to the actions attribute in the Project class, however then I run into where MegaProject.actions.action.actions.action situations start popping up.</p> <p>If anyone could help out with the class structures, it would be greatly appreciated!</p>
2
2009-07-23T23:48:09Z
1,192,266
<p>Have you evaluated existing GTD tools? I'd look at file formats used by existing GTD tools, esp. those that save to XML. That would give you an idea about which ways to organize this kind of data tend to work.</p> <p>Structure ranges from rather simplistic (TaskPaper) to baroque (OmniFocus). Look around and learn what others did before you.</p>
0
2009-07-28T06:44:48Z
[ "python", "design", "recursion", "gtd" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
1,175,221
<p>Not in the standard library, but I found <a href="http://pypi.python.org/pypi/from-camel/0.2.0" rel="nofollow">this script</a> that appears to contain the functionality you need.</p>
2
2009-07-24T00:27:58Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
1,175,366
<p><strong>For the fun of it:</strong></p> <pre><code>&gt;&gt;&gt; def un_camel(input): ... output = [input[0].lower()] ... for c in input[1:]: ... if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): ... output.append('_') ... output.append(c.lower()) ... else: ... output.append(c) ... return str.join('', output) ... &gt;&gt;&gt; un_camel("camel_case") 'camel_case' &gt;&gt;&gt; un_camel("CamelCase") 'camel_case' </code></pre> <p>Or, more for the fun of it:</p> <pre><code>&gt;&gt;&gt; un_camel = lambda i: i[0].lower() + str.join('', ("_" + c.lower() if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" else c for c in i[1:])) &gt;&gt;&gt; un_camel("camel_case") 'camel_case' &gt;&gt;&gt; un_camel("CamelCase") 'camel_case' </code></pre>
4
2009-07-24T01:20:40Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
1,175,421
<pre><code>''.join('_'+c.lower() if c.isupper() else c for c in "DeathToCamelCase").strip('_') re.sub("(.)([A-Z])", r'\1_\2', 'DeathToCamelCase').lower() </code></pre>
5
2009-07-24T01:48:27Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
1,175,443
<p>A horrendous example using regular expressions (you could <em>easily</em> clean this up :) ):</p> <pre><code>def f(s): return s.group(1).lower() + "_" + s.group(2).lower() p = re.compile("([A-Z]+[a-z]+)([A-Z]?)") print p.sub(f, "CamelCase") print p.sub(f, "getHTTPResponseCode") </code></pre> <p>Works for getHTTPResponseCode though!</p> <p>Alternatively, using lambda:</p> <pre><code>p = re.compile("([A-Z]+[a-z]+)([A-Z]?)") print p.sub(lambda x: x.group(1).lower() + "_" + x.group(2).lower(), "CamelCase") print p.sub(lambda x: x.group(1).lower() + "_" + x.group(2).lower(), "getHTTPResponseCode") </code></pre> <p>EDIT: It should also be pretty easy to see that there's room for improvement for cases like "Test", because the underscore is unconditionally inserted.</p>
0
2009-07-24T02:05:16Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
1,175,451
<p>Here's my solution:</p> <pre><code>def un_camel(text): """ Converts a CamelCase name into an under_score name. &gt;&gt;&gt; un_camel('CamelCase') 'camel_case' &gt;&gt;&gt; un_camel('getHTTPResponseCode') 'get_http_response_code' """ result = [] pos = 0 while pos &lt; len(text): if text[pos].isupper(): if pos-1 &gt; 0 and text[pos-1].islower() or pos-1 &gt; 0 and \ pos+1 &lt; len(text) and text[pos+1].islower(): result.append("_%s" % text[pos].lower()) else: result.append(text[pos].lower()) else: result.append(text[pos]) pos += 1 return "".join(result) </code></pre> <p>It supports those corner cases discussed in the comments. For instance, it'll convert <code>getHTTPResponseCode</code> to <code>get_http_response_code</code> like it should.</p>
3
2009-07-24T02:09:28Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
1,176,023
<p>This is pretty thorough:</p> <pre><code>def convert(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() </code></pre> <p>Works with all these (and doesn't harm already-un-cameled versions):</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' &gt;&gt;&gt; convert('CamelCamelCase') 'camel_camel_case' &gt;&gt;&gt; convert('Camel2Camel2Case') 'camel2_camel2_case' &gt;&gt;&gt; convert('getHTTPResponseCode') 'get_http_response_code' &gt;&gt;&gt; convert('get2HTTPResponseCode') 'get2_http_response_code' &gt;&gt;&gt; convert('HTTPResponseCode') 'http_response_code' &gt;&gt;&gt; convert('HTTPResponseCodeXYZ') 'http_response_code_xyz' </code></pre> <p>Or if you're going to call it a zillion times, you can pre-compile the regexes:</p> <pre><code>first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def convert(name): s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() </code></pre> <p>Don't forget to import the regular expression module</p> <pre><code>import re </code></pre>
365
2009-07-24T06:25:13Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
5,356,672
<p>Wow I just stole this from django snippets. ref <a href="http://djangosnippets.org/snippets/585/" rel="nofollow">http://djangosnippets.org/snippets/585/</a></p> <p>Pretty elegant </p> <pre><code>camelcase_to_underscore = lambda str: re.sub('(((?&lt;=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', str).lower().strip('_') </code></pre> <p>Example:</p> <pre><code>camelcase_to_underscore('ThisUser') </code></pre> <p>Returns:</p> <pre><code>'this_user' </code></pre>
0
2011-03-18T19:05:44Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
7,593,794
<p>Very nice RegEx proposed on <a href="http://jason.diamond.name/weblog/2009/08/15/splitting-camelcase-with-regular-expressions/comment-page-1/" rel="nofollow">this site</a>:</p> <pre class="lang-none prettyprint-override"><code>(?&lt;!^)(?=[A-Z]) </code></pre> <p>If python have a String Split method, it should work...</p> <p>In Java:</p> <pre class="lang-java prettyprint-override"><code>String s = "loremIpsum"; words = s.split("(?&amp;#60;!^)(?=[A-Z])"); </code></pre>
0
2011-09-29T07:19:31Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
8,452,630
<p>Here's something I did to change the headers on a tab-delimited file. I'm omitting the part where I only edited the first line of the file. You could adapt it to Python pretty easily with the re library. This also includes separating out numbers (but keeps the digits together). I did it in two steps because that was easier than telling it not to put an underscore at the start of a line or tab.</p> <p>Step One...find uppercase letters or integers preceded by lowercase letters, and precede them with an underscore:</p> <p>Search:</p> <pre><code>([a-z]+)([A-Z]|[0-9]+) </code></pre> <p>Replacement:</p> <pre><code>\1_\l\2/ </code></pre> <p>Step Two...take the above and run it again to convert all caps to lowercase:</p> <p>Search:</p> <pre><code>([A-Z]) </code></pre> <p>Replacement (that's backslash, lowercase L, backslash, one):</p> <pre><code>\l\1 </code></pre>
0
2011-12-09T22:41:32Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
10,985,418
<p>I have had pretty good luck with this one:</p> <pre><code>import re def camelcase_to_underscore(s): return re.sub(r'(^|[a-z])([A-Z])', lambda m: '_'.join([i.lower() for i in m.groups() if i]), s) </code></pre> <p>This could obviously be optimized for speed a <em>tiny</em> bit if you want to.</p> <pre><code>import re CC2US_RE = re.compile(r'(^|[a-z])([A-Z])') def _replace(match): return '_'.join([i.lower() for i in match.groups() if i]) def camelcase_to_underscores(s): return CC2US_RE.sub(_replace, s) </code></pre>
0
2012-06-11T18:17:16Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
12,867,228
<p>I don't know why these are all so complicating.</p> <p>for most cases the simple expression <code>([A-Z]+)</code> will do the trick</p> <pre><code>&gt;&gt;&gt; re.sub('([A-Z]+)', r'_\1','CamelCase').lower() '_camel_case' &gt;&gt;&gt; re.sub('([A-Z]+)', r'_\1','camelCase').lower() 'camel_case' &gt;&gt;&gt; re.sub('([A-Z]+)', r'_\1','camel2Case2').lower() 'camel2_case2' &gt;&gt;&gt; re.sub('([A-Z]+)', r'_\1','camelCamelCase').lower() 'camel_camel_case' &gt;&gt;&gt; re.sub('([A-Z]+)', r'_\1','getHTTPResponseCode').lower() 'get_httpresponse_code' </code></pre> <p>To ignore the first charachter simply add look behind <code>(?!^)</code></p> <pre><code>&gt;&gt;&gt; re.sub('(?!^)([A-Z]+)', r'_\1','CamelCase').lower() 'camel_case' &gt;&gt;&gt; re.sub('(?!^)([A-Z]+)', r'_\1','CamelCamelCase').lower() 'camel_camel_case' &gt;&gt;&gt; re.sub('(?!^)([A-Z]+)', r'_\1','Camel2Camel2Case').lower() 'camel2_camel2_case' &gt;&gt;&gt; re.sub('(?!^)([A-Z]+)', r'_\1','getHTTPResponseCode').lower() 'get_httpresponse_code' </code></pre> <p>If you want to separate ALLCaps to all_caps and expect numbers in your string you still don't need to do two separate runs just use <code>|</code> This expression <code>((?&lt;=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))</code> can handle just about every scenario in the book</p> <pre><code>&gt;&gt;&gt; a = re.compile('((?&lt;=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))') &gt;&gt;&gt; a.sub(r'_\1', 'getHTTPResponseCode').lower() 'get_http_response_code' &gt;&gt;&gt; a.sub(r'_\1', 'get2HTTPResponseCode').lower() 'get2_http_response_code' &gt;&gt;&gt; a.sub(r'_\1', 'get2HTTPResponse123Code').lower() 'get2_http_response123_code' &gt;&gt;&gt; a.sub(r'_\1', 'HTTPResponseCode').lower() 'http_response_code' &gt;&gt;&gt; a.sub(r'_\1', 'HTTPResponseCodeXYZ').lower() 'http_response_code_xyz' </code></pre> <p>It all depends on what you want so use the solution that best fits your needs as it should not be overly complicated.</p> <p>nJoy!</p>
56
2012-10-12T21:17:16Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
13,363,758
<p>I don't get idea why using both .sub() calls? :) I'm not regex guru, but I simplified function to this one, which is suitable for my certain needs, I just needed a solution to convert camelCasedVars from POST request to vars_with_underscore: </p> <pre><code>def myFunc(...): return re.sub('(.)([A-Z]{1})', r'\1_\2', "iTriedToWriteNicely").lower() </code></pre> <p>It does not work with such names like getHTTPResponse, cause I heard it is bad naming convention (should be like getHttpResponse, it's obviously, that it's much easier memorize this form).</p>
6
2012-11-13T15:39:08Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
14,634,975
<p>I was looking for a solution to the same problem, except that I needed a chain; e.g.</p> <pre><code>"CamelCamelCamelCase" -&gt; "Camel-camel-camel-case" </code></pre> <p>Starting from the nice two-word solutions here, I came up with the following:</p> <pre><code>"-".join(x.group(1).lower() if x.group(2) is None else x.group(1) \ for x in re.finditer("((^.[^A-Z]+)|([A-Z][^A-Z]+))", "stringToSplit")) </code></pre> <p>Most of the complicated logic is to avoid lowercasing the first word. Here's a simpler version if you don't mind altering the first word:</p> <pre><code>"-".join(x.group(1).lower() for x in re.finditer("(^[^A-Z]+|[A-Z][^A-Z]+)", "stringToSplit")) </code></pre> <p>Of course, you can pre-compile the regular expressions or join with underscore instead of hyphen, as discussed in the other solutions.</p>
0
2013-01-31T20:55:29Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
14,913,356
<p>This is not a elegant method, is a very 'low level' implementation of a simple state machine (bitfield state machine), possibly the most anti pythonic mode to resolve this, however re module also implements a too complex state machine to resolve this simple task, so i think this is a good solution.</p> <pre><code>def splitSymbol(s): si, ci, state = 0, 0, 0 # start_index, current_index ''' state bits: 0: no yields 1: lower yields 2: lower yields - 1 4: upper yields 8: digit yields 16: other yields 32 : upper sequence mark ''' for c in s: if c.islower(): if state &amp; 1: yield s[si:ci] si = ci elif state &amp; 2: yield s[si:ci - 1] si = ci - 1 state = 4 | 8 | 16 ci += 1 elif c.isupper(): if state &amp; 4: yield s[si:ci] si = ci if state &amp; 32: state = 2 | 8 | 16 | 32 else: state = 8 | 16 | 32 ci += 1 elif c.isdigit(): if state &amp; 8: yield s[si:ci] si = ci state = 1 | 4 | 16 ci += 1 else: if state &amp; 16: yield s[si:ci] state = 0 ci += 1 # eat ci si = ci print(' : ', c, bin(state)) if state: yield s[si:ci] def camelcaseToUnderscore(s): return '_'.join(splitSymbol(s)) </code></pre> <p>splitsymbol can parses all case types: UpperSEQUENCEInterleaved, under_score, BIG_SYMBOLS and cammelCasedMethods</p> <p>I hope it is useful</p>
2
2013-02-16T17:58:52Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
17,328,907
<p>There's an <a href="https://pypi.python.org/pypi/inflection">inflection library</a> in the package index that can handle these things for you. In this case, you'd be looking for <a href="http://inflection.readthedocs.org/en/latest/#inflection.underscore"><code>inflection.underscore()</code></a>:</p> <pre><code>&gt;&gt;&gt; inflection.underscore('CamelCase') 'camel_case' </code></pre>
64
2013-06-26T19:34:34Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
19,940,888
<p>Personally I am not sure how anything using regular expressions in python can be described as elegant. Most answers here are just doing "code golf" type RE tricks. Elegant coding is supposed to be easily understood.</p> <pre><code>def un_camel(x): final = '' for item in x: if item.isupper(): final += "_"+item.lower() else: final += item if final[0] == "_": final = final[1:] return final &gt;&gt;&gt; un_camel("RegularExpressionsAreFunky") 'regular_expressions_are_funky' </code></pre>
14
2013-11-12T22:05:05Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
23,561,109
<p>Concise without regular expressions, but HTTPResponseCode=> httpresponse_code:</p> <pre><code>def from_camel(name): """ ThisIsCamelCase ==&gt; this_is_camel_case """ name = name.replace("_", "") _cas = lambda _x : [_i.isupper() for _i in _x] seq = zip(_cas(name[1:-1]), _cas(name[2:])) ss = [_x + 1 for _x, (_i, _j) in enumerate(seq) if (_i, _j) == (False, True)] return "".join([ch + "_" if _x in ss else ch for _x, ch in numerate(name.lower())]) </code></pre>
0
2014-05-09T09:29:04Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
28,774,760
<p>Using regexes may be the shortest, but this solution is way more readable:</p> <pre><code>def to_snake_case(s): snake = "".join(["_"+c.lower() if c.isupper() else c for c in s]) return snake[1:] if snake.startswith("_") else snake </code></pre>
2
2015-02-27T21:39:18Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
32,064,723
<p>Use: <code>str.capitalize()</code> to convert first letter of the string (contained in variable str) to a capital letter and returns the entire string.</p> <p>Example: Command: "hello".capitalize() Output: Hello</p>
-3
2015-08-18T06:07:33Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
32,252,101
<p>Without any library :</p> <pre><code>def camelify(out): return (''.join(["_"+x.lower() if i&lt;len(out)-1 and x.isupper() and out[i+1].islower() else x.lower()+"_" if i&lt;len(out)-1 and x.islower() and out[i+1].isupper() else x.lower() for i,x in enumerate(list(out))])).lstrip('_').replace('__','_') </code></pre> <p>A bit heavy, but</p> <pre><code>CamelCamelCamelCase -&gt; camel_camel_camel_case HTTPRequest -&gt; http_request GetHTTPRequest -&gt; get_http_request getHTTPRequest -&gt; get_http_request </code></pre>
0
2015-08-27T14:27:01Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
33,516,645
<p>This simple method should do the job:</p> <pre><code>import re def convert(name): return re.sub(r'([A-Z]*)([A-Z][a-z]+)', lambda x: (x.group(1) + '_' if x.group(1) else '') + x.group(2) + '_', name).rstrip('_').lower() </code></pre> <ul> <li>We look for capital letters that are precedeed by any number of (or zero) capital letters, and followed by any number of lowercase characters.</li> <li>An underscore is placed just before the occurence of the last capital letter found in the group, and one can be placed before that capital letter in case it is preceded by other capital letters.</li> <li>If there are trailing underscores, remove those.</li> <li>Finally, the whole result string is changed to lower case.</li> </ul> <p>(taken from <a href="http://rodic.fr/blog/camelcase-and-snake_case-strings-conversion-with-python/" rel="nofollow">here</a>, see <a href="http://ideone.com/JyVkds" rel="nofollow">working example online</a>)</p>
0
2015-11-04T08:06:03Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
34,159,022
<p>Lightely adapted from <a href="http://stackoverflow.com/users/267781/matth">http://stackoverflow.com/users/267781/matth</a> who use generators.</p> <pre><code>def uncamelize(s): buff, l = '', [] for ltr in s: if ltr.isupper(): if buff: l.append(buff) buff = '' buff += ltr l.append(buff) return '_'.join(l).lower() </code></pre>
1
2015-12-08T14:57:20Z
[ "python", "camelcasing" ]
Elegant Python function to convert CamelCase to snake_case?
1,175,208
<p>Example:</p> <pre><code>&gt;&gt;&gt; convert('CamelCase') 'camel_case' </code></pre>
238
2009-07-24T00:22:02Z
36,357,670
<p>Take a look at the excellent Schematics lib </p> <p><a href="https://github.com/schematics/schematics" rel="nofollow">https://github.com/schematics/schematics</a></p> <p>It allows you to created typed data structures that can serialize/deserialize from python to Javascript flavour, eg:</p> <pre><code>class MapPrice(Model): price_before_vat = DecimalType(serialized_name='priceBeforeVat') vat_rate = DecimalType(serialized_name='vatRate') vat = DecimalType() total_price = DecimalType(serialized_name='totalPrice') </code></pre>
1
2016-04-01T13:30:43Z
[ "python", "camelcasing" ]
Comparing dissimilar types in python
1,175,529
<p>First the code:</p> <pre><code>class myClass(object): def __cmp__(self, other): return cmp(type(self), type(other)) or cmp(self.__something, other.__something) </code></pre> <p>Does this produce the same ordering as for other types in python? Is there a correct idiom for this?</p> <p><a href="http://stackoverflow.com/questions/1151658/python-hashable-dicts">Related question:</a> </p> <p>A bit of looking around on google I found some pertinent information in the <a href="http://docs.python.org/library/stdtypes.html#comparisons" rel="nofollow">python docs</a>. Quoting:</p> <blockquote> <p><strong>Implementation note:</strong> Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.</p> </blockquote> <p>This suggests that If I want to follow that behavior, I should use</p> <pre><code>class myClass(object): def __cmp__(self, other): return (cmp(self.__class__.__name__, other.__class__.__name) or cmp(self.__something, other.__something)) </code></pre> <p>Especially unfortunate is that I may have an extraordinarily difficult time mantaining transitivity with <code>dict</code>s, which is a special case I had hoped to implement. </p> <p>Do I even need to check the types of my arguments? does python even let me see this?</p>
3
2009-07-24T02:43:46Z
1,175,923
<p>Python 2 unfortunately did support such "alien" comparisons (fortunately abrogated in Python 3). It's NOT easy to emulate the built-ins behavior because it has so many special cases, for example float and int compare directly (no type-comparison override as you have it coded) but complex makes any comparison (except == and !=) always raise an exception. Do you <em>really</em> need to emulate all of these quirks and wiggles? Such a need would be very unusual. If your type is "numeric" (e.g. look at decimal.Decimal) it needs to play nice with other numerical types, I guess, but types that aren't "comparable numbers" have fewer real-word sensible constraints...!</p>
1
2009-07-24T05:58:13Z
[ "python" ]
Comparing dissimilar types in python
1,175,529
<p>First the code:</p> <pre><code>class myClass(object): def __cmp__(self, other): return cmp(type(self), type(other)) or cmp(self.__something, other.__something) </code></pre> <p>Does this produce the same ordering as for other types in python? Is there a correct idiom for this?</p> <p><a href="http://stackoverflow.com/questions/1151658/python-hashable-dicts">Related question:</a> </p> <p>A bit of looking around on google I found some pertinent information in the <a href="http://docs.python.org/library/stdtypes.html#comparisons" rel="nofollow">python docs</a>. Quoting:</p> <blockquote> <p><strong>Implementation note:</strong> Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.</p> </blockquote> <p>This suggests that If I want to follow that behavior, I should use</p> <pre><code>class myClass(object): def __cmp__(self, other): return (cmp(self.__class__.__name__, other.__class__.__name) or cmp(self.__something, other.__something)) </code></pre> <p>Especially unfortunate is that I may have an extraordinarily difficult time mantaining transitivity with <code>dict</code>s, which is a special case I had hoped to implement. </p> <p>Do I even need to check the types of my arguments? does python even let me see this?</p>
3
2009-07-24T02:43:46Z
1,183,941
<p>What are you actually trying to do? Why would you want to sort or compare instances of different classes by class/type?</p> <p>It's hard to propose a solution when you haven't actually posted the problem.</p> <p>You need to define your own comparison methods for custom classes, and it's largely up to you to make sure any comparisons you perform make sense.</p> <p>Please explain what you are trying to achieve. This might not be the Pythonic way.</p>
0
2009-07-26T07:05:10Z
[ "python" ]
Iterative find/replace from a list of tuples in Python
1,175,540
<p>I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this iteratively, so performance is my biggest concern.</p> <p>More concretely, what would the innards of processThis() look like?</p> <pre><code>x = 'find1, find2, find3' y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')] def processThis(str,lst): # Do something here return something &gt;&gt;&gt; processThis(x,y) 'replace1, replace2, replace3' </code></pre> <p>Thanks, all!</p>
3
2009-07-24T02:48:28Z
1,175,547
<pre><code>x = 'find1, find2, find3' y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')] def processThis(str,lst): for find, replace in lst: str = str.replace(find, replace) return str &gt;&gt;&gt; processThis(x,y) 'replace1, replace2, replace3' </code></pre>
0
2009-07-24T02:53:08Z
[ "python", "django", "list", "iteration", "tuples" ]
Iterative find/replace from a list of tuples in Python
1,175,540
<p>I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this iteratively, so performance is my biggest concern.</p> <p>More concretely, what would the innards of processThis() look like?</p> <pre><code>x = 'find1, find2, find3' y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')] def processThis(str,lst): # Do something here return something &gt;&gt;&gt; processThis(x,y) 'replace1, replace2, replace3' </code></pre> <p>Thanks, all!</p>
3
2009-07-24T02:48:28Z
1,175,554
<p>You could consider using <code>re.sub</code>:</p> <pre><code>import re REPLACEMENTS = dict([('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')]) def replacer(m): return REPLACEMENTS[m.group(0)] x = 'find1, find2, find3' r = re.compile('|'.join(REPLACEMENTS.keys())) print r.sub(replacer, x) </code></pre>
6
2009-07-24T02:55:05Z
[ "python", "django", "list", "iteration", "tuples" ]
Iterative find/replace from a list of tuples in Python
1,175,540
<p>I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this iteratively, so performance is my biggest concern.</p> <p>More concretely, what would the innards of processThis() look like?</p> <pre><code>x = 'find1, find2, find3' y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')] def processThis(str,lst): # Do something here return something &gt;&gt;&gt; processThis(x,y) 'replace1, replace2, replace3' </code></pre> <p>Thanks, all!</p>
3
2009-07-24T02:48:28Z
1,175,576
<pre><code>s = reduce(lambda x, repl: str.replace(x, *repl), lst, s) </code></pre>
0
2009-07-24T03:05:45Z
[ "python", "django", "list", "iteration", "tuples" ]
Iterative find/replace from a list of tuples in Python
1,175,540
<p>I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this iteratively, so performance is my biggest concern.</p> <p>More concretely, what would the innards of processThis() look like?</p> <pre><code>x = 'find1, find2, find3' y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')] def processThis(str,lst): # Do something here return something &gt;&gt;&gt; processThis(x,y) 'replace1, replace2, replace3' </code></pre> <p>Thanks, all!</p>
3
2009-07-24T02:48:28Z
1,175,640
<p>A couple notes:</p> <ol> <li>The boilerplate argument about premature optimization, benchmarking, bottlenecks, 100 is small, etc.</li> <li>There are cases where the different solutions will return different results. if <code>y = [('one', 'two'), ('two', 'three')]</code> and <code>x = 'one'</code> then mhawke's solution gives you <code>'two'</code> and Unknown's gives <code>'three'</code>. </li> <li>Testing this out in a silly contrived example mhawke's solution was a <em>tiny</em> bit faster. It should be easy to try it with your data though.</li> </ol>
1
2009-07-24T03:40:13Z
[ "python", "django", "list", "iteration", "tuples" ]
Iterative find/replace from a list of tuples in Python
1,175,540
<p>I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this iteratively, so performance is my biggest concern.</p> <p>More concretely, what would the innards of processThis() look like?</p> <pre><code>x = 'find1, find2, find3' y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')] def processThis(str,lst): # Do something here return something &gt;&gt;&gt; processThis(x,y) 'replace1, replace2, replace3' </code></pre> <p>Thanks, all!</p>
3
2009-07-24T02:48:28Z
38,260,657
<p>Same answer as mhawke, enclosed with method str_replace</p> <pre><code>def str_replace(data, search_n_replace_dict): import re REPLACEMENTS = search_n_replace_dict def replacer(m): return REPLACEMENTS[m.group(0)] r = re.compile('|'.join(REPLACEMENTS.keys())) return r.sub(replacer, data) </code></pre> <p>Then we can call this method with example as below</p> <pre><code>s = "abcd abcd efgh efgh;;;;;; lkmnkd kkkkk" d = dict({ 'abcd' : 'aaaa', 'efgh' : 'eeee', 'mnkd' : 'mmmm' }) print (s) print ("\n") print(str_replace(s, d)) </code></pre> <p>output :</p> <pre><code>abcd abcd efgh efgh;;;;;; lkmnkd kkkkk aaaa aaaa eeee eeee;;;;;; lkmmmm kkkkk </code></pre>
0
2016-07-08T06:57:41Z
[ "python", "django", "list", "iteration", "tuples" ]
How can I display updating output of a slow script using Pylons?
1,175,748
<p>I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once.</p> <p>I found how to access the output of the command in Python with the answer to this question:</p> <p><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></p> <p>Now I need to find a way to get this information to the browser as it is being generated. I was planning on using jQuery's loadContent() to load the output of a script into a . The problem is that Pylons controllers use <code>return</code> so the output has to be complete before Pylons renders the page and the web server responds to the client with the content.</p> <p>Is there any way to have a page display content as it is generated within Pylons or will this have to be done with scripting outside of Pylons?</p> <p>Basically, I'm trying to do something like this: <a href="http://network-tools.com/default.asp?prog=trace&amp;host=www.bbc.co.uk" rel="nofollow">http://network-tools.com/default.asp?prog=trace&amp;host=www.bbc.co.uk</a></p>
0
2009-07-24T04:26:26Z
1,175,909
<p><code>pexpect</code> will let you get the output as it comes, with no buffering.</p> <p>To update info promptly on the user's browser, you need javascript on that browser sending appropriate AJAX requests to your server (dojo or jquery will make that easier, though they're not strictly required) and updating the page as new responses come -- without client-side cooperation (and JS + AJAX is the simplest way to get that cooperation), there's no sensible way to do it on the server side alone.</p> <p>So the general approach is: send AJAX query from browser, have server respond as soon as it has one more line, JS on the browser updates contents then immediately sends another query, repeat until server responds with an "I'm all done" marker (e.g. an "empty" response may work for that purpose).</p>
1
2009-07-24T05:54:31Z
[ "python", "pylons" ]
How can I display updating output of a slow script using Pylons?
1,175,748
<p>I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once.</p> <p>I found how to access the output of the command in Python with the answer to this question:</p> <p><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></p> <p>Now I need to find a way to get this information to the browser as it is being generated. I was planning on using jQuery's loadContent() to load the output of a script into a . The problem is that Pylons controllers use <code>return</code> so the output has to be complete before Pylons renders the page and the web server responds to the client with the content.</p> <p>Is there any way to have a page display content as it is generated within Pylons or will this have to be done with scripting outside of Pylons?</p> <p>Basically, I'm trying to do something like this: <a href="http://network-tools.com/default.asp?prog=trace&amp;host=www.bbc.co.uk" rel="nofollow">http://network-tools.com/default.asp?prog=trace&amp;host=www.bbc.co.uk</a></p>
0
2009-07-24T04:26:26Z
1,178,314
<p>I haven't tried it with pylons, but you could try to show the output of the slow component in an iframe on the page (using mime type text/plain) and yield each chunk to the iframe as it is generated. For fun I just put this together as a WHIFF demo. Here is the slowly generated web content wsgi application:</p> <pre><code>import time def slow(env, start_response): start_response("200 OK", [('Content-Type', 'text/plain')]) return slow_generator() def slow_generator(): yield "slowly generating 20 timestamps\n" for i in range(20): yield "%s: %s\n" % (i, time.ctime()) time.sleep(1) yield "done!" __wsgi__ = slow </code></pre> <p>This file is deployed on my laptop at: <a href="http://aaron.oirt.rutgers.edu/myapp/root/misc/slow" rel="nofollow">http://aaron.oirt.rutgers.edu/myapp/root/misc/slow</a>.</p> <p>Here is the WHIFF configuration template which includes the slow page in an iframe:</p> <pre><code>{{env whiff.content_type: "text/html"/}} Here is an iframe with slowly generated content: &lt;hr&gt; &lt;iframe frameborder="1" height="300px" width="300px" scrolling="yes" style="background-color:#99dddd;" src="slow" &gt;&lt;/iframe&gt; &lt;hr&gt; Isn't that cool? </code></pre> <p>This is deployed on my laptop at <a href="http://aaron.oirt.rutgers.edu/myapp/root/misc/showSlowly" rel="nofollow">http://aaron.oirt.rutgers.edu/myapp/root/misc/showSlowly</a>.</p> <p>hmmm. I just tried the above link in safari and it didn't work right... apparently there are some browser differences... Seems to work on Firefox at least...</p>
0
2009-07-24T15:10:55Z
[ "python", "pylons" ]
How can I display updating output of a slow script using Pylons?
1,175,748
<p>I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once.</p> <p>I found how to access the output of the command in Python with the answer to this question:</p> <p><a href="http://stackoverflow.com/questions/1151897/how-can-i-perform-a-ping-or-traceroute-in-python-accessing-the-output-as-it-is-p">How can I perform a ping or traceroute in python, accessing the output as it is produced?</a></p> <p>Now I need to find a way to get this information to the browser as it is being generated. I was planning on using jQuery's loadContent() to load the output of a script into a . The problem is that Pylons controllers use <code>return</code> so the output has to be complete before Pylons renders the page and the web server responds to the client with the content.</p> <p>Is there any way to have a page display content as it is generated within Pylons or will this have to be done with scripting outside of Pylons?</p> <p>Basically, I'm trying to do something like this: <a href="http://network-tools.com/default.asp?prog=trace&amp;host=www.bbc.co.uk" rel="nofollow">http://network-tools.com/default.asp?prog=trace&amp;host=www.bbc.co.uk</a></p>
0
2009-07-24T04:26:26Z
1,224,684
<p>You may want to look at this <a href="http://wiki.pylonshq.com/display/pylonsfaq/Streaming+Content+to+the+Browser" rel="nofollow">faq</a> entry. Then with JS, you always clear the screen before writing new stuff.</p>
1
2009-08-03T21:15:37Z
[ "python", "pylons" ]
How to use .pem file with Python M2Crypto
1,176,055
<p>To generate an RSA key pair I used openssl:</p> <pre><code>openssl genrsa -out my_key.private.pem 1024 openssl rsa -in my_key.private.pem -pubout -out my_key.public.pem </code></pre> <p>Now I want to use this my_key.public.pem file in a function of another .py file:</p> <pre><code>import M2Crypto from M2Crypto import RSA,SSL def encrypt(): pk = open( 'my_key.public.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) print rsa; </code></pre> <p>Am I doing it right? Both files are in same directory, but this function is not giving any output.</p>
2
2009-07-24T06:34:57Z
1,176,205
<p>According to the <a href="http://www.heikkitoivonen.net/m2crypto/api/" rel="nofollow">documentation</a> the <code>load_pub_key</code> expects a file name as input. It returns a <code>M2Crypto.RSA.RSA_pub</code> object, which doesn't make sense to print. What exactly are trying to achieve?</p>
4
2009-07-24T07:19:14Z
[ "python", "m2crypto", "pem" ]
How to use .pem file with Python M2Crypto
1,176,055
<p>To generate an RSA key pair I used openssl:</p> <pre><code>openssl genrsa -out my_key.private.pem 1024 openssl rsa -in my_key.private.pem -pubout -out my_key.public.pem </code></pre> <p>Now I want to use this my_key.public.pem file in a function of another .py file:</p> <pre><code>import M2Crypto from M2Crypto import RSA,SSL def encrypt(): pk = open( 'my_key.public.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) print rsa; </code></pre> <p>Am I doing it right? Both files are in same directory, but this function is not giving any output.</p>
2
2009-07-24T06:34:57Z
4,145,761
<p>Try this:</p> <pre><code>RSA.load_key('mykey.pem') </code></pre>
0
2010-11-10T14:56:59Z
[ "python", "m2crypto", "pem" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
1,176,179
<p>You could do something like:</p> <pre><code>globals()[class_name] </code></pre>
60
2009-07-24T07:12:08Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
1,176,180
<p>This could work:</p> <pre><code>import sys def str_to_class(str): return getattr(sys.modules[__name__], str) </code></pre>
80
2009-07-24T07:13:10Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
1,176,194
<p>Yes, you can do this. Assuming your classes exist in the global namespace, something like this will do it:</p> <pre><code>import types class Foo: pass def str_to_class(s): if s in globals() and isinstance(globals()[s], types.ClassType): return globals()[s] return None str_to_class('Foo') ==&gt; &lt;class __main__.Foo at 0x340808cc&gt; </code></pre>
1
2009-07-24T07:16:32Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
1,176,225
<pre><code>import sys import types def str_to_class(field): try: identifier = getattr(sys.modules[__name__], field) except AttributeError: raise NameError("%s doesn't exist." % field) if isinstance(identifier, (types.ClassType, types.TypeType)): return identifier raise TypeError("%s is not a class." % field) </code></pre> <p>This accurately handles both old-style and new-style classes.</p>
16
2009-07-24T07:25:27Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
1,178,089
<p>This seems simplest.</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... pass ... &gt;&gt;&gt; eval("Foo") &lt;class '__main__.Foo'&gt; </code></pre>
55
2009-07-24T14:32:24Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
13,808,375
<p>You want the class "Baz", which lives in module "foo.bar". With python 2.7, you want to use importlib.import_module(), as this will make transitioning to python 3 easier: </p> <pre><code>import importlib def class_for_name(module_name, class_name): # load the module, will raise ImportError if module cannot be loaded m = importlib.import_module(module_name) # get the class, will raise AttributeError if class cannot be found c = getattr(m, class_name) return c </code></pre> <p>With python &lt; 2.7:</p> <pre><code>def class_for_name(module_name, class_name): # load the module, will raise ImportError if module cannot be loaded m = __import__(module_name, globals(), locals(), class_name) # get the class, will raise AttributeError if class cannot be found c = getattr(m, class_name) return c </code></pre> <p>Use:</p> <pre><code>loaded_class = class_for_name('foo.bar', 'Baz') </code></pre>
44
2012-12-10T20:08:18Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
19,273,974
<p>In terms of arbitrary code execution, or undesired user passed names, you could have a list of acceptable function/class names, and if the input matches one in the list, it is eval'd.</p> <p>PS: I know....kinda late....but it's for anyone else who stumbles across this in the future.</p>
1
2013-10-09T13:49:35Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
33,662,482
<p>Using <a href="https://docs.python.org/3/library/importlib.html" rel="nofollow">importlib</a> worked the best for me.</p> <pre><code>import importlib importlib.import_module('accounting.views') </code></pre> <p>This uses <em>string dot notation</em> for the python module that you want to import.</p>
0
2015-11-12T00:34:01Z
[ "python" ]
Convert string to Python class object?
1,176,136
<p>Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p> <pre><code>class Foo: pass str_to_class("Foo") ==&gt; &lt;class __main__.Foo at 0x69ba0&gt; </code></pre> <p>Is this possible?</p>
84
2009-07-24T07:01:23Z
34,963,527
<p>I've looked at how django handles this</p> <p>django.utils.module_loading has this</p> <pre><code>def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) </code></pre> <p>You can use it like <code>import_string("module_path.to.all.the.way.to.your_class")</code></p>
0
2016-01-23T12:36:01Z
[ "python" ]
Python equivalent of PropertyUtilsBean
1,176,139
<p><br /> I was wondering, is there a Python equivalent to Apache commons' PropertyUtilsBean?</p> <p><strong>Edit:</strong><br /> For example, I'd like to be able to make this assignment</p> <pre><code>x.y[2].z = v </code></pre> <p>given "y[2].z" as a string.<br /> Please note, I'm asking just because I'd like to not reinvent the wheel :)</p>
0
2009-07-24T07:02:19Z
1,176,272
<p>Do you mean something like <a href="http://docs.python.org/library/functions.html#setattr" rel="nofollow"><code>setattr</code></a>?</p> <p>From its docstring:</p> <blockquote> <pre><code>setattr(object, name, value) </code></pre> <p>Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''.</p> </blockquote>
1
2009-07-24T07:44:57Z
[ "python", "apache-commons" ]
Python equivalent of PropertyUtilsBean
1,176,139
<p><br /> I was wondering, is there a Python equivalent to Apache commons' PropertyUtilsBean?</p> <p><strong>Edit:</strong><br /> For example, I'd like to be able to make this assignment</p> <pre><code>x.y[2].z = v </code></pre> <p>given "y[2].z" as a string.<br /> Please note, I'm asking just because I'd like to not reinvent the wheel :)</p>
0
2009-07-24T07:02:19Z
1,176,293
<p>Why do you need such a thing when there's <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-exec-statement" rel="nofollow">exec</a>?</p>
1
2009-07-24T07:52:22Z
[ "python", "apache-commons" ]
How to generate pdf with epydoc?
1,176,407
<p>I am considering epydoc for the documentation of one module. It looks ok to me and is working fine when I am generating html document.</p> <p>I would like to try to generate the documenation in the pdf format. I've just modified the 'output' setting in my config file. </p> <p>Unfortunately, epydoc fails when generating the pdf file. The error is "Error: Error reading pstat file: [Errno 2] No such file or directory: 'profile.out'"</p> <p>it generates some tex files. I think that maybe I am missing latex but I am not very familliar with tex and latex. More over I am working on Windows.</p> <p>What should be the next steps for making epydoc generating pdf file?</p> <p>Thanks in advance for your help</p>
1
2009-07-24T08:32:10Z
1,180,671
<p>I suppose that you used an existing conf file.</p> <p>If you have a closer look inside, you will see an option <code>pstat: profile.out</code>. This options says that the file <code>profile.out</code> will be used to generate the call graph (see <a href="http://epydoc.sourceforge.net/manual-reference.html" rel="nofollow">doc</a>).</p> <pre><code># The name of one or more pstat files (generated by the profile # or hotshot module). These are used to generate call graphs. pstat: profile.out </code></pre> <p>You need to generate this file, by using the <code>profile</code>or <code>hotspot</code>module. For example, you can run your module by</p> <pre><code>python -m "profile" -o profile.out mymodule.py </code></pre> <p>(it is also possible to use <code>hotspot</code> or <code>cProfile</code>, that is much much faster than <code>profile</code>)</p> <p>This should works (I hope so)</p>
3
2009-07-24T23:34:32Z
[ "python", "documentation", "latex", "epydoc" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
1,176,465
<pre><code>files = [file for file in files if os.path.splitext(file)[1] != '.dat'] </code></pre>
2
2009-07-24T08:48:23Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
1,176,559
<p>A concise way of writing it, if you do this a lot:</p> <pre><code>def exclude_ext(ext): def compare(fn): return os.path.splitext(fn)[1] != ext return compare files = filter(exclude_ext(".dat"), files) </code></pre> <p>Of course, exclude_ext goes in your appropriate utility package.</p>
3
2009-07-24T09:16:36Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
1,176,824
<pre><code>files = [ fi for fi in files if not fi.endswith(".dat") ] </code></pre>
21
2009-07-24T10:23:41Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
1,179,222
<p>Should be exactly what you need:</p> <pre><code>if thisFile.endswith(".txt"): </code></pre>
0
2009-07-24T18:03:18Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
1,179,420
<p>Try this:</p> <pre><code>import os skippingWalk = lambda targetDirectory, excludedExtentions: ( (root, dirs, [F for F in files if os.path.splitext(F)[1] not in excludedExtentions]) for (root, dirs, files) in os.walk(targetDirectory) ) for line in skippingWalk("C:/My_files/test", [".dat"]): print line </code></pre> <p>This is a generator expression generating lambda function. You pass it a path and some extensions, and it invokes os.walk with the path, filters out the files with extensions in the list of unwanted extensions using a list comprehension, and returns the result.</p> <p>(edit: removed the <code>.upper()</code> statement because there might be an actual difference between extensions of different case - if you want this to be case insensitive, add <code>.upper()</code> after <code>os.path.splitext(F)[1]</code> and pass extensions in in capital letters.)</p>
2
2009-07-24T18:41:11Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
9,523,148
<p>And in one more way, because I just wrote this, and then stumbled upon this question:</p> <p><code>files = filter(lambda file: not file.endswith('.txt'), files)</code></p>
1
2012-03-01T20:02:06Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
10,812,969
<p>Exclude multiple extensions.</p> <pre><code>files = [ file for file in files if not file.endswith( ('.dat','.tar') ) ] </code></pre>
10
2012-05-30T08:52:24Z
[ "python" ]
How to filter files (with known type) from os.walk?
1,176,441
<p>I have list from <code>os.walk</code>. But I want to exclude some directories and files. I know how to do it with directories:</p> <pre><code>for root, dirs, files in os.walk('C:/My_files/test'): if "Update" in dirs: dirs.remove("Update") </code></pre> <p>But how can I do it with files, which type I know. because this doesn't work:</p> <pre><code>if "*.dat" in files: files.remove("*.dat") </code></pre>
17
2009-07-24T08:40:31Z
17,010,837
<p>Another solution would be to use the functions from <a href="http://docs.python.org/2/library/fnmatch.html" rel="nofollow">fnmatch</a> module:</p> <pre><code>def MatchesExtensions(name,extensions=["*.dat", "*.txt", "*.whatever"]): for pattern in extensions: if fnmatch.fnmatch(pattern): return True return False </code></pre> <p>This way you avoid all the hassle with upper/lower case extension. This means you don't need to convert to lower/upper when having to match *.JPEG, *.jpeg, *.JPeg, *.Jpeg</p>
1
2013-06-09T14:51:11Z
[ "python" ]
IO completion port key confusion
1,176,477
<p>I'm writing an IO completion port based server (<a href="http://code.google.com/p/pyiocp/source/browse/01%20-%20Work%20in%20Progress/03%20-%20Serving.py">source code here</a>) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.</p> <p>As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed.</p> <p>However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100.</p> <p>Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?</p>
6
2009-07-24T08:52:37Z
1,176,694
<p><code>GetQueuedCompletionStatus</code> returns two things, an <code>OVERLAPPED</code> structure and a completion key. The completion key represents per-device information, and the <code>OVERLAPPED</code> structure represents per-call information. The completion key should match what was given in the call to <code>CreateIoCompletionPort</code>. Typically, you would use a pointer to a structure containing information about the connection as the completion key.</p> <p>It looks like you're not doing anything with <code>completionKey</code> as returned by <code>GetQueuedCompletionStatus</code>.</p> <p>I'm guessing you want:</p> <pre><code>if completionKey != acceptKey: Cleanup() ... </code></pre> <p>edit:</p> <p>Does Python somehow know that the <code>OVERLAPPED</code> structure created in <code>CreateAcceptSocket</code> is being used asynchronously by the Win32 API and prevent it from being GC'd?</p>
1
2009-07-24T09:50:51Z
[ "python", "windows", "winsock", "ctypes", "iocp" ]
IO completion port key confusion
1,176,477
<p>I'm writing an IO completion port based server (<a href="http://code.google.com/p/pyiocp/source/browse/01%20-%20Work%20in%20Progress/03%20-%20Serving.py">source code here</a>) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.</p> <p>As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed.</p> <p>However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100.</p> <p>Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?</p>
6
2009-07-24T08:52:37Z
1,181,330
<p>The problem is in how I am passing the completion keys. The completion key argument is a pointer, yet it passes back the pointer not the value pointed to - a little confusing to me at least.</p> <p>Also the completion key passed for the accepted connection overlapped packet is that of the listening socket - not the accepted socket.</p>
0
2009-07-25T05:58:45Z
[ "python", "windows", "winsock", "ctypes", "iocp" ]
IO completion port key confusion
1,176,477
<p>I'm writing an IO completion port based server (<a href="http://code.google.com/p/pyiocp/source/browse/01%20-%20Work%20in%20Progress/03%20-%20Serving.py">source code here</a>) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.</p> <p>As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed.</p> <p>However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100.</p> <p>Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?</p>
6
2009-07-24T08:52:37Z
2,330,449
<p>What I've found in everyday practice is that it is best to simply focus on the <code>OVERLAPPED</code> result, as that will be unchanged. One way that you can use it effectively is to have something like the following:</p> <pre><code>struct CompletionHandler { OVERLAPPED dummy_ovl; /* Stuff that actually means something to you here */ }; </code></pre> <p>When you post something to the IOCP (whether via I/O call or just a post via Win32 API), you first create a <code>CompletionHandler</code> object that you will use to track the call, and cast the address of that object to <code>OVERLAPPED*</code>.</p> <pre><code>CompletionHander my_handler; // Fill in whatever you need to in my_handler // Don't forget to keep the original my_handler! // I/O call goes here, and for OVERLAPPED* give: (OVERLAPPED*)&amp;my_handler </code></pre> <p>This way, when you get the <code>OVERLAPPED</code> result all you have to do is cast it back to <code>CompletionHandler</code> and voila! You have the original context of your call.</p> <pre><code>OVERLAPPED* from_queued_completion_status; // Actually get a value into from_queued_completion_status CompletionHandler* handler_for_this_completion = (CompletionHandler*)from_queued_completion_status; // Have fun! </code></pre> <p>For more details in a real-world setting, check out Boost's implementation of ASIO for Windows (<a href="http://www.boost.org/doc/libs/1_42_0/boost/asio/detail/win_iocp_io_service.hpp" rel="nofollow">ver 1.42 header here</a>). There are some details like validation the <code>OVERLAPPED</code> pointer you get from <code>GetQueuedCompletionStatus</code>, but again, see the link for a good way to implement.</p>
4
2010-02-24T23:20:48Z
[ "python", "windows", "winsock", "ctypes", "iocp" ]
IO completion port key confusion
1,176,477
<p>I'm writing an IO completion port based server (<a href="http://code.google.com/p/pyiocp/source/browse/01%20-%20Work%20in%20Progress/03%20-%20Serving.py">source code here</a>) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.</p> <p>As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed.</p> <p>However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100.</p> <p>Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?</p>
6
2009-07-24T08:52:37Z
2,565,448
<p>Completion key is not a pointer - it is a number of type ULONG_PTR, which just means "an integer the size of a pointer" so it is 32-bits on x86 and 64-bits on x64. The typename is confusing, but when win32 typenames refer to a pointer they do it by having a P at the front of the name, not the end.</p>
0
2010-04-02T07:01:23Z
[ "python", "windows", "winsock", "ctypes", "iocp" ]
IO completion port key confusion
1,176,477
<p>I'm writing an IO completion port based server (<a href="http://code.google.com/p/pyiocp/source/browse/01%20-%20Work%20in%20Progress/03%20-%20Serving.py">source code here</a>) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.</p> <p>As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed.</p> <p>However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100.</p> <p>Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?</p>
6
2009-07-24T08:52:37Z
7,828,469
<p>If your application is multithreading, make sure that the CompletionKey you're passing is either constant or a pointer value to object on heap rather than on stack. In your example where 100 is passed as constant, you must be wrong to say any change. But as to the problem it could be that you pass a socket handle in CreateIoCompletionPort but not a reference to handle in GetQueuedCompletionStatus in order to retrive it. You can do</p> <pre><code>HANDLE socket; CreateIoCompletionPort((HANDLE)socket, existed_io_completion_port, (ULONG_PTR)socket, 0); /*some I/Os*/ ... </code></pre> <p>and</p> <pre><code>HANDLE socket; GetQueuedCompletionStatus(existed_io_completion_port, &amp;io_bytes_done, (PULONG_PTR)&amp;socket, &amp;overlapped); </code></pre> <p>and pay attention to the type in bracket.</p>
0
2011-10-19T21:34:49Z
[ "python", "windows", "winsock", "ctypes", "iocp" ]
IO completion port key confusion
1,176,477
<p>I'm writing an IO completion port based server (<a href="http://code.google.com/p/pyiocp/source/browse/01%20-%20Work%20in%20Progress/03%20-%20Serving.py">source code here</a>) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python.</p> <p>As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed.</p> <p>However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100.</p> <p>Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?</p>
6
2009-07-24T08:52:37Z
7,832,010
<p>You should think about the completion key as 'per connection' data and the (extended) overlapped structure as 'per i/o' operation. </p> <p>Some people use an extended overlapped structure for BOTH and store all the information that they need in the extended overlapped structure. I have always stored a reference counted object that wraps my socket in the completion key and a reference counted data buffer as an extended overlapped structure. If you're interested you can see <a href="http://www.serverframework.com/products---the-free-framework.html" rel="nofollow">some example IOCP code in C++ here</a>.</p> <p>The completion key is, effectively, just an opaque handle to data that the I/O completion system will give back to you when a completion occurs on the socket.</p>
1
2011-10-20T06:35:35Z
[ "python", "windows", "winsock", "ctypes", "iocp" ]
Using ADODBAPI-Python
1,176,521
<p>Can you list some resources that explain using ADODBAPI in python.?</p>
1
2009-07-24T09:06:23Z
1,177,335
<p>ADO can be accessed with <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">win32 extensions for python</a>.</p> <p>ADO is acessible through COM objects. </p> <p>You can have a look at this page that would give a lot of info: <a href="http://www.ecp.cc/pyado.html" rel="nofollow">http://www.ecp.cc/pyado.html</a></p>
0
2009-07-24T12:27:09Z
[ "python", "database" ]
Return files only from specific folder
1,176,624
<p>I wrote a function in Python, that must return file from specific folder and all subfolders. File name taken from function parameter:</p> <pre><code>def ReturnFile(fileName) return open("C:\\folder\\" + fileName,"r") </code></pre> <p>But as <code>fileName</code> you can pass for example: <code>"..\\Windows\\passwords.txt</code>" or some unicode symbols for dots.</p> <p>How to fix it? Some RegExp maybe?</p>
0
2009-07-24T09:34:44Z
1,176,757
<p>The <a href="http://docs.python.org/library/os.path.html#os.path.normpath" rel="nofollow"><code>os.path.normpath</code></a> function normalizes a given path py resolving things like "..". Then you can check if the resulting path is in the expected directory:</p> <pre><code>def ReturnFile(fileName) norm = os.path.abspath("C:\\folder\\" + fileName) if not norm.startswith("C:\\folder\\"): raise Exception("Invalid filename specified") return open(norm,"r") </code></pre>
4
2009-07-24T10:03:11Z
[ "python" ]
Return files only from specific folder
1,176,624
<p>I wrote a function in Python, that must return file from specific folder and all subfolders. File name taken from function parameter:</p> <pre><code>def ReturnFile(fileName) return open("C:\\folder\\" + fileName,"r") </code></pre> <p>But as <code>fileName</code> you can pass for example: <code>"..\\Windows\\passwords.txt</code>" or some unicode symbols for dots.</p> <p>How to fix it? Some RegExp maybe?</p>
0
2009-07-24T09:34:44Z
1,176,783
<p>How about this:</p> <pre><code>import os _BASE_PATH= "C:\\folder\\" def return_file(file_name): "Return File Object from Base Path named `file_name`" os.path.normpath(file_name).split(os.path.sep)[-1] return(open(_BASE_PATH+file_name)) </code></pre>
1
2009-07-24T10:09:01Z
[ "python" ]
How do I add items to a gtk.ComboBox created through glade at runtime?
1,176,748
<p>I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track. </p> <p>How do I add strings to the ComboBox at runtime? This is what I have so far:</p> <pre><code>self.tracked_interface = builder.get_object("tracked_interface") self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING) self.iface_list_store.append(["hello, "]) self.iface_list_store.append(["world."]) self.tracked_interface.set_model(self.iface_list_store) self.tracked_interface.set_active(0) </code></pre> <p>But the ComboBox remains empty. I tried RTFM'ing, but just came away more confused, if anything.</p> <p>Cheers.</p>
3
2009-07-24T10:01:58Z
1,176,848
<p>Hey, I actually get to answer my own question!</p> <p>You have to add gtk.CellRendererText into there for it to actually render:</p> <pre><code>self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING) self.iface_list_store.append(["hello, "]) self.iface_list_store.append(["world."]) self.tracked_interface.set_model(self.iface_list_store) self.tracked_interface.set_active(0) # And here's the new stuff: cell = gtk.CellRendererText() self.tracked_interface.pack_start(cell, True) self.tracked_interface.add_attribute(cell, "text", 0) </code></pre> <p>Retrieved from, of course, the <a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq16.008.htp" rel="nofollow">PyGTK FAQ</a>.</p> <p><em>Corrected example thanks to Joe McBride</em></p>
4
2009-07-24T10:31:33Z
[ "python", "gtk", "pygtk" ]
How do I add items to a gtk.ComboBox created through glade at runtime?
1,176,748
<p>I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track. </p> <p>How do I add strings to the ComboBox at runtime? This is what I have so far:</p> <pre><code>self.tracked_interface = builder.get_object("tracked_interface") self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING) self.iface_list_store.append(["hello, "]) self.iface_list_store.append(["world."]) self.tracked_interface.set_model(self.iface_list_store) self.tracked_interface.set_active(0) </code></pre> <p>But the ComboBox remains empty. I tried RTFM'ing, but just came away more confused, if anything.</p> <p>Cheers.</p>
3
2009-07-24T10:01:58Z
1,177,233
<p>Or you could just create and insert the combo box yourself using <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkcombobox.html#function-gtk--combo-box-new-text"><code>gtk.combo_box_new_text()</code></a>. Then you'll be able to use gtk shortcuts to <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkcombobox.html#method-gtkcombobox--append-text">append</a>, <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkcombobox.html#method-gtkcombobox--insert-text">insert</a>, <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkcombobox.html#method-gtkcombobox--prepend-text">prepend</a> and <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkcombobox.html#method-gtkcombobox--remove-text">remove</a> text.</p> <pre><code>combo = gtk.combo_box_new_text() combo.append_text('hello') combo.append_text('world') combo.set_active(0) box = builder.get_object('some-box') box.pack_start(combo, False, False) </code></pre>
5
2009-07-24T12:03:09Z
[ "python", "gtk", "pygtk" ]
How do I add items to a gtk.ComboBox created through glade at runtime?
1,176,748
<p>I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track. </p> <p>How do I add strings to the ComboBox at runtime? This is what I have so far:</p> <pre><code>self.tracked_interface = builder.get_object("tracked_interface") self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING) self.iface_list_store.append(["hello, "]) self.iface_list_store.append(["world."]) self.tracked_interface.set_model(self.iface_list_store) self.tracked_interface.set_active(0) </code></pre> <p>But the ComboBox remains empty. I tried RTFM'ing, but just came away more confused, if anything.</p> <p>Cheers.</p>
3
2009-07-24T10:01:58Z
5,987,859
<p>Just in case anyone else uses this, the last line of code should be:</p> <pre><code>self.tracked_interface.add_attribute(cell, "text", 0) </code></pre> <p>instead of:</p> <pre><code>self.tracked_interface.(cell, "text", 0) </code></pre>
2
2011-05-13T06:04:57Z
[ "python", "gtk", "pygtk" ]
Python file read problem
1,176,988
<pre><code>file_read = open("/var/www/rajaneesh/file/_config.php", "r") contents = file_read.read() print contents file_read.close() </code></pre> <p>The output is empty, but in that file all contents are there. Please help me how to do read and replace a string in <code>__conifg.php</code>.</p>
1
2009-07-24T11:06:10Z
1,177,049
<p>Usually, when there is such kind of issues, it is very useful to start the <strong>interactive shell</strong> and analyze all commands.</p> <p>For instance, it could be that the file does not exists (see comment from freiksenet) or you do not have privileges to it, or it is locked by another process.<br /> If you execute the script in some system (like a web server, as the path could suggest), the exception could go to a log - or simply be swallowed by other components in the system.<br /> On the contrary, if you execute it in the interactive shell, you can immediately see what the problem was, and eventually inspect the object (by using <a href="http://docs.python.org/library/functions.html#help" rel="nofollow"><code>help()</code></a>, <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> or the module <code>inspect</code>). By the way, this is also a good method for developing a script - just by tinkering around with the concept in the shell, then putting altogether.</p> <p>While we are here, I strongly suggest you usage of <a href="http://ipython.scipy.org/" rel="nofollow">IPython</a>. It is an evolution of the standard shell, with powerful aids for introspection (just press tab, or a put a question mark after an object). Unfortunately in the latest weeks the site is not often not available, but there are good chances you already have it installed on your system.</p>
4
2009-07-24T11:23:25Z
[ "python", "file-io" ]
Python file read problem
1,176,988
<pre><code>file_read = open("/var/www/rajaneesh/file/_config.php", "r") contents = file_read.read() print contents file_read.close() </code></pre> <p>The output is empty, but in that file all contents are there. Please help me how to do read and replace a string in <code>__conifg.php</code>.</p>
1
2009-07-24T11:06:10Z
1,178,039
<p>Would it be possible that you don't have read access to the file you are trying to open?</p>
0
2009-07-24T14:24:00Z
[ "python", "file-io" ]
Python file read problem
1,176,988
<pre><code>file_read = open("/var/www/rajaneesh/file/_config.php", "r") contents = file_read.read() print contents file_read.close() </code></pre> <p>The output is empty, but in that file all contents are there. Please help me how to do read and replace a string in <code>__conifg.php</code>.</p>
1
2009-07-24T11:06:10Z
1,178,203
<p>I copied your code onto my own system, and changed the filename so that it works on my system. Also, I changed the indenting (putting everything at the same level) from what shows in your question. With those changes, the code worked fine.</p> <p>Thus, I think it's something else specific to your system that we probably cannot solve here (easily).</p>
2
2009-07-24T14:51:19Z
[ "python", "file-io" ]
How to do scheduled sending of email with django-mailer
1,177,088
<p>I'm making a django app that needs to be able to make emails and then send these out at a given time. I was thinking i could use django-mailer to put things in que and then send it of. But even though theire sample case list, lists that this is a feature, I cant seem to find out how.</p> <p>What I need is to be able to set a 'when_to_send' field in the message model of django-mailer, and when the cron job fires the send_mail function this needs to filter out the ones that has a 'when_to_send' date that is greater than the current time...</p> <pre><code>def send_all(): """ Send all eligible messages in the queue. """ lock = FileLock("send_mail") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") start_time = time.time() dont_send = 0 deferred = 0 sent = 0 try: for message in prioritize(): if DontSendEntry.objects.has_address(message.to_address): logging.info("skipping email to %s as on don't send list " % message.to_address) MessageLog.objects.log(message, 2) # @@@ avoid using literal result code message.delete() dont_send += 1 else: try: logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8"))) core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address]) MessageLog.objects.log(message, 1) # @@@ avoid using literal result code message.delete() sent += 1 except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err: message.defer() logging.info("message deferred due to failure: %s" % err) MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code deferred += 1 finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send)) logging.info("done in %.2f seconds" % (time.time() - start_time)) </code></pre> <p>Anyone see how to customize this function to don't send email's where the message.when_to_send field is greater than the current time?</p>
3
2009-07-24T11:32:49Z
1,177,837
<p>You can just add another clause to the conditionals under your message processing loop (you will also need to import datetime at the top of your file):</p> <pre><code> for message in prioritize(): if DontSendEntry.objects.has_address(message.to_address): logging.info("skipping email to %s as on don't send list " % message.to_address) MessageLog.objects.log(message, 2) # @@@ avoid using literal result code message.delete() dont_send += 1 elif message.when_to_send &gt; datetime.datetime.now(): continue else: try: ... the rest of your code ... </code></pre>
0
2009-07-24T13:54:31Z
[ "python", "django", "email", "schedule", "django-mailer" ]
How to do scheduled sending of email with django-mailer
1,177,088
<p>I'm making a django app that needs to be able to make emails and then send these out at a given time. I was thinking i could use django-mailer to put things in que and then send it of. But even though theire sample case list, lists that this is a feature, I cant seem to find out how.</p> <p>What I need is to be able to set a 'when_to_send' field in the message model of django-mailer, and when the cron job fires the send_mail function this needs to filter out the ones that has a 'when_to_send' date that is greater than the current time...</p> <pre><code>def send_all(): """ Send all eligible messages in the queue. """ lock = FileLock("send_mail") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") start_time = time.time() dont_send = 0 deferred = 0 sent = 0 try: for message in prioritize(): if DontSendEntry.objects.has_address(message.to_address): logging.info("skipping email to %s as on don't send list " % message.to_address) MessageLog.objects.log(message, 2) # @@@ avoid using literal result code message.delete() dont_send += 1 else: try: logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8"))) core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address]) MessageLog.objects.log(message, 1) # @@@ avoid using literal result code message.delete() sent += 1 except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err: message.defer() logging.info("message deferred due to failure: %s" % err) MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code deferred += 1 finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send)) logging.info("done in %.2f seconds" % (time.time() - start_time)) </code></pre> <p>Anyone see how to customize this function to don't send email's where the message.when_to_send field is greater than the current time?</p>
3
2009-07-24T11:32:49Z
1,836,054
<p>You need to implement the cron job for <a href="http://github.com/jtauber/django-mailer/blob/master/docs/usage.txt" rel="nofollow">django-mailer</a>:</p> <pre><code>* * * * * (cd $PINAX; /usr/local/bin/python2.5 manage.py send_mail &gt;&gt; $PINAX/cron_mail.log 2&gt;&amp;1) </code></pre> <p>And then in <a href="http://github.com/jtauber/django-mailer/blob/master/mailer/engine.py" rel="nofollow">engine.py</a> line 96:</p> <pre><code> # Get rid of "while True:" while not Message.objects.all(): # Get rid of logging.debug("sleeping for %s seconds before checking queue again" % EMPTY_QUEUE_SLEEP) # Get rid of sleep send_all() </code></pre>
3
2009-12-02T21:48:42Z
[ "python", "django", "email", "schedule", "django-mailer" ]
Python- about file-handle limits on OS
1,177,230
<p>HI i wrote a program by python , and when i open too many tempfile, i will got an exception: Too many open files ... Then i figure out that windows OS or C runtime has the file-handle limits, so, i alter my program using StringIO(), but still don`t know whether StringIO also is limited??</p>
4
2009-07-24T12:02:40Z
1,177,261
<p>Python's StringIO does not use OS file handles, so it won't be limited in the same way. StringIO will be limited by available virtual memory, but you've probably got heaps of available memory.</p> <p>Normally the OS allows a single process to open thousands of files before running into the limit, so if your program is running out of file handles you might be forgetting to close them. Unless you're intending to open thousands of files and really have just run out, of course.</p>
7
2009-07-24T12:08:33Z
[ "python" ]
Decoding double encoded utf8 in Python
1,177,316
<p>I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaround for now before he fixes it.</p> <p>Raw string from tcp dump: </p> <pre><code>&lt;string&gt;Rafa\xc3\x85\xc2\x82&lt;/string&gt; </code></pre> <p>this is converted into:</p> <pre><code>u'Rafa\xc5\x82' </code></pre> <p>The best we get is:</p> <pre><code>eval(repr(u'Rafa\xc5\x82')[1:]).decode("utf8") </code></pre> <p>This results in correct string which is:</p> <pre><code>u'Rafa\u0142' </code></pre> <p>this works however is ugly as hell and cannot be used in production code. If anyone knows how to fix this problem in more suitable way please write. Thanks, Chris</p>
14
2009-07-24T12:23:26Z
1,177,542
<pre> >>> s = u'Rafa\xc5\x82' >>> s.encode('raw_unicode_escape').decode('utf-8') u'Rafa\u0142' >>> </pre>
32
2009-07-24T13:11:26Z
[ "python", "string", "utf-8", "decode" ]
Decoding double encoded utf8 in Python
1,177,316
<p>I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaround for now before he fixes it.</p> <p>Raw string from tcp dump: </p> <pre><code>&lt;string&gt;Rafa\xc3\x85\xc2\x82&lt;/string&gt; </code></pre> <p>this is converted into:</p> <pre><code>u'Rafa\xc5\x82' </code></pre> <p>The best we get is:</p> <pre><code>eval(repr(u'Rafa\xc5\x82')[1:]).decode("utf8") </code></pre> <p>This results in correct string which is:</p> <pre><code>u'Rafa\u0142' </code></pre> <p>this works however is ugly as hell and cannot be used in production code. If anyone knows how to fix this problem in more suitable way please write. Thanks, Chris</p>
14
2009-07-24T12:23:26Z
1,177,568
<p>Yow, that was fun!</p> <pre><code>&gt;&gt;&gt; original = "Rafa\xc3\x85\xc2\x82" &gt;&gt;&gt; first_decode = original.decode('utf-8') &gt;&gt;&gt; as_chars = ''.join([chr(ord(x)) for x in first_decode]) &gt;&gt;&gt; result = as_chars.decode('utf-8') &gt;&gt;&gt; result u'Rafa\u0142' </code></pre> <p>So you do the first decode, getting a Unicode string where each character is actually a UTF-8 byte value. You go via the integer value of each of those characters to get back to a genuine UTF-8 string, which you then decode as normal.</p>
3
2009-07-24T13:15:27Z
[ "python", "string", "utf-8", "decode" ]
Decoding double encoded utf8 in Python
1,177,316
<p>I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaround for now before he fixes it.</p> <p>Raw string from tcp dump: </p> <pre><code>&lt;string&gt;Rafa\xc3\x85\xc2\x82&lt;/string&gt; </code></pre> <p>this is converted into:</p> <pre><code>u'Rafa\xc5\x82' </code></pre> <p>The best we get is:</p> <pre><code>eval(repr(u'Rafa\xc5\x82')[1:]).decode("utf8") </code></pre> <p>This results in correct string which is:</p> <pre><code>u'Rafa\u0142' </code></pre> <p>this works however is ugly as hell and cannot be used in production code. If anyone knows how to fix this problem in more suitable way please write. Thanks, Chris</p>
14
2009-07-24T12:23:26Z
1,178,086
<pre><code>&gt;&gt;&gt; weird = u'Rafa\xc5\x82' &gt;&gt;&gt; weird.encode('latin1').decode('utf8') u'Rafa\u0142' &gt;&gt;&gt; </code></pre> <p>latin1 is just an abbreviation for Richie's nuts'n'bolts method.</p> <p>It is very curious that the seriously under-described <code>raw_unicode_escape</code> codec gives the same result as <code>latin1</code> in this case. Do they always give the same result? If so, why have such a codec? If not, it would preferable to know for sure exactly how the OP's client did the transformation from <code>'Rafa\xc5\x82'</code> to <code>u'Rafa\xc5\x82'</code> and then to reverse that process exactly -- otherwise we might come unstuck if different data crops up before the double encoding is fixed.</p>
1
2009-07-24T14:31:52Z
[ "python", "string", "utf-8", "decode" ]